mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-30 02:07:10 +01:00
Merge main into feat/scripts-api-d4b-text-styles
This commit is contained in:
commit
44c89a7912
88 files changed
+5138
-431
No files matched your search
@@ -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.
|
||||
|
||||
@@ -2626,6 +2626,83 @@ fn pattern_brush_scale_from_the_pen_fits_start_and_end_tiles_where_the_scale_fal
|
||||
}
|
||||
}
|
||||
|
||||
/// How far from y = 0 the outlines under `nodes` reach where they cross the vertical line at `x`.
|
||||
fn reach_at(nodes: &[Node], x: f64) -> f64 {
|
||||
let mut reach = 0.0f64;
|
||||
for n in nodes {
|
||||
n.walk(&mut |c| {
|
||||
for sp in c.path_data().into_iter().flat_map(|p| &p.subpaths) {
|
||||
for i in 0..sp.segment_count() {
|
||||
let s = sp.segment(i);
|
||||
let (a, b, c, d) = (s.p0.x, s.p1.x, s.p2.x, s.p3.x);
|
||||
let roots = kurbo::common::solve_cubic(a - x, 3.0 * (b - a), 3.0 * (c - 2.0 * b + a), d - 3.0 * c + 3.0 * b - a);
|
||||
for t in roots.into_iter().filter(|t| (-1e-9..=1.0 + 1e-9).contains(t)) {
|
||||
reach = reach.max(kurbo::ParamCurve::eval(&s, t.clamp(0.0, 1.0)).y.abs());
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
reach
|
||||
}
|
||||
|
||||
/// A pattern tile whose scale follows the pen is as tall as the scale at a short peak of the
|
||||
/// pressure, even where the peak falls between the positions the bent outline is checked at.
|
||||
#[test]
|
||||
fn pattern_brush_scale_from_the_pen_keeps_a_short_peak() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let b = scaled_pattern(PatternFit::Stretch, false, 100.0, Some(Variation::Pressure), Some(300.0));
|
||||
// One 10 × 4 pt tile on a 10 pt path: 100 % (2 pt either side) but for a peak at 2.2 pt, where
|
||||
// the scale reaches 300 % (6 pt either side).
|
||||
let peak = pressed(vec![(0.0, 0.0), (0.21, 0.0), (0.22, 1.0), (0.23, 0.0), (1.0, 0.0)]);
|
||||
let out = stroke_pieces(&doc, &b, &line(0.0, 0.0, 10.0, 0.0), &peak);
|
||||
// At the peak 300 %, half way up it 200 %, and 100 % on either side of it.
|
||||
for (x, want) in [(2.2, 6.0), (2.15, 4.0), (2.25, 4.0), (1.0, 2.0), (2.05, 2.0), (2.4, 2.0), (8.0, 2.0)] {
|
||||
assert!(near(reach_at(&out, x), want, 0.05), "at {x} pt: {} pt either side, not {want}", reach_at(&out, x));
|
||||
}
|
||||
}
|
||||
|
||||
/// An art brush whose width follows the pen is as wide as the pen gives at a short peak of the
|
||||
/// pressure, even where the peak falls between the positions the bent outline is checked at.
|
||||
#[test]
|
||||
fn art_brush_width_from_the_pen_keeps_a_short_peak() {
|
||||
let mut b = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch);
|
||||
if let BrushKind::Art(a) = &mut b.kind {
|
||||
(a.width, a.width_mode, a.width_max) = (100.0, Some(Variation::Pressure), Some(300.0));
|
||||
}
|
||||
// 4 pt art on a 100 pt path: 2 pt either side but for a peak at 22 pt, where it is 6 pt.
|
||||
let peak = pressed(vec![(0.0, 0.0), (0.21, 0.0), (0.22, 1.0), (0.23, 0.0), (1.0, 0.0)]);
|
||||
let out = stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 100.0, 0.0), &peak);
|
||||
for (x, want) in [(22.0, 6.0), (21.5, 4.0), (22.5, 4.0), (10.0, 2.0), (20.5, 2.0), (24.0, 2.0), (80.0, 2.0)] {
|
||||
assert!(near(reach_at(&out, x), want, 0.05), "at {x} pt: {} pt either side, not {want}", reach_at(&out, x));
|
||||
}
|
||||
}
|
||||
|
||||
/// A pen recording sampled many times along a straight ramp draws as many anchors as the ramp's
|
||||
/// two ends do: samples that leave the scale on the same straight course are not split at.
|
||||
#[test]
|
||||
fn pen_samples_on_a_straight_ramp_add_no_anchors() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let bp = line(0.0, 0.0, 1000.0, 0.0);
|
||||
let ramp = |n: usize| pressed((0..=n).map(|i| (i as f64 / n as f64, i as f64 / n as f64)).collect());
|
||||
let anchors = |out: &[Node]| {
|
||||
let mut count = 0;
|
||||
for n in out {
|
||||
n.walk(&mut |c| count += c.path_data().map_or(0, |p| p.subpaths.iter().map(|s| s.anchors.len()).sum::<usize>()));
|
||||
}
|
||||
count
|
||||
};
|
||||
let pattern = scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0));
|
||||
let mut art = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch);
|
||||
if let BrushKind::Art(a) = &mut art.kind {
|
||||
(a.width, a.width_mode, a.width_max) = (50.0, Some(Variation::Pressure), Some(300.0));
|
||||
}
|
||||
for b in [&pattern, &art] {
|
||||
let (few, many) = (stroke_pieces(&doc, b, &bp, &ramp(1)), stroke_pieces(&doc, b, &bp, &ramp(2000)));
|
||||
assert_eq!(anchors(&many), anchors(&few), "{}", b.name);
|
||||
}
|
||||
}
|
||||
|
||||
/// On a closed path, a tile that Approximate Path starts before the path's start takes the scale
|
||||
/// recorded at the end of the stroke there, where the tile is drawn.
|
||||
#[test]
|
||||
|
||||
+152
-30
@@ -40,23 +40,32 @@ const MASK_STEPS: usize = 32;
|
||||
/// through the bend to within [`fit_tol`] of `doc_tol`, the flattening tolerance in document
|
||||
/// space, so the art keeps its curves (#3926). Where that cannot be done in no more anchors than
|
||||
/// chords would take, the path is flattened with `flat_tol` (art space) and subdivided so no chord
|
||||
/// is longer than `max_du` along x, as it always was. Stroke widths scale by `width_scale`.
|
||||
/// Text, images and symbol instances can't bend and are dropped. The art of a linked opacity mask
|
||||
/// bends with the object it masks.
|
||||
pub(crate) fn warp_node(n: &Node, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, doc_tol: f64, width_scale: f64) -> Option<Node> {
|
||||
/// is longer than `max_du` along x, as it always was. Both routes also split the art where it
|
||||
/// crosses each of `breaks` (art x, in order), so a turn of the map there is not stepped over.
|
||||
/// Stroke widths scale by `width_scale`. Text, images and symbol instances can't bend and are
|
||||
/// dropped. The art of a linked opacity mask bends with the object it masks.
|
||||
pub(crate) fn warp_node(
|
||||
n: &Node,
|
||||
f: &dyn Fn(Point) -> Point,
|
||||
flat_tol: f64,
|
||||
max_du: f64,
|
||||
doc_tol: f64,
|
||||
width_scale: f64,
|
||||
breaks: &[f64],
|
||||
) -> Option<Node> {
|
||||
let mut out = n.clone();
|
||||
out.appearance.scale_strokes(width_scale);
|
||||
match &mut out.kind {
|
||||
NodeKind::Path { path, live, .. } => {
|
||||
*live = None;
|
||||
*path = warp_path(path, f, flat_tol, max_du, fit_tol(doc_tol));
|
||||
*path = warp_path(path, f, flat_tol, max_du, fit_tol(doc_tol), breaks);
|
||||
if path.is_empty() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } | NodeKind::Compound { children, .. } => {
|
||||
let kids: Vec<Arc<Node>> =
|
||||
children.iter().filter_map(|c| warp_node(c, f, flat_tol, max_du, doc_tol, width_scale)).map(Arc::new).collect();
|
||||
children.iter().filter_map(|c| warp_node(c, f, flat_tol, max_du, doc_tol, width_scale, breaks)).map(Arc::new).collect();
|
||||
if kids.is_empty() {
|
||||
return None;
|
||||
}
|
||||
@@ -64,7 +73,7 @@ pub(crate) fn warp_node(n: &Node, f: &dyn Fn(Point) -> Point, flat_tol: f64, max
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
map_mask(&mut out, |art| warp_node(art, f, flat_tol, max_du, doc_tol, width_scale));
|
||||
map_mask(&mut out, |art| warp_node(art, f, flat_tol, max_du, doc_tol, width_scale, breaks));
|
||||
Some(out)
|
||||
}
|
||||
|
||||
@@ -80,12 +89,13 @@ fn map_mask(n: &mut Node, map: impl FnOnce(&Node) -> Option<Node>) {
|
||||
}
|
||||
|
||||
/// Each subpath of `p` through `f`: fitted cubics when they take no more anchors than the chords
|
||||
/// would, else the chords. Points `f` cannot place (not finite) are left out of the chords.
|
||||
fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, fit_tol: f64) -> PathData {
|
||||
/// would, else the chords, both split at `breaks` ([`warp_node`]). Points `f` cannot place (not
|
||||
/// finite) are left out of the chords.
|
||||
fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, fit_tol: f64, breaks: &[f64]) -> PathData {
|
||||
let mut subs = vec![];
|
||||
for sp in &p.subpaths {
|
||||
let Some(dense) = densified(sp, flat_tol, max_du) else { continue };
|
||||
if let Some(fit) = fitted(sp, f, fit_tol, dense.len()) {
|
||||
let Some(dense) = densified(sp, flat_tol, max_du, breaks) else { continue };
|
||||
if let Some(fit) = fitted(sp, f, fit_tol, dense.len(), breaks) {
|
||||
subs.push(fit);
|
||||
continue;
|
||||
}
|
||||
@@ -98,8 +108,9 @@ fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f6
|
||||
}
|
||||
|
||||
/// `sp` flattened with `flat_tol` and its chords subdivided so none is longer than `max_du` along
|
||||
/// x, in art space: the points the chord route maps. `None` below two points.
|
||||
fn densified(sp: &SubPath, flat_tol: f64, max_du: f64) -> Option<Vec<Point>> {
|
||||
/// x, in art space, with a point where a chord crosses each of `breaks` (art x, in order): the
|
||||
/// points the chord route maps. `None` below two points.
|
||||
fn densified(sp: &SubPath, flat_tol: f64, max_du: f64, breaks: &[f64]) -> Option<Vec<Point>> {
|
||||
let mut bp = BezPath::new();
|
||||
sp.to_bezpath_into(&mut bp);
|
||||
let mut pts = vec![];
|
||||
@@ -118,16 +129,57 @@ fn densified(sp: &SubPath, flat_tol: f64, max_du: f64) -> Option<Vec<Point>> {
|
||||
let mut dense = vec![*pts.first()?];
|
||||
for (i, (&a, &b)) in pts.iter().zip(pts.iter().cycle().skip(1)).take(segs).enumerate() {
|
||||
let k = (((b.x - a.x).abs() / max_du).ceil() as usize).clamp(1, MAX_SUB);
|
||||
// The breaks the chord crosses, as parameters along it in order, go in among the even ones.
|
||||
let mut cuts: Vec<f64> = crossed(breaks, a.x, b.x).iter().map(|&x| (x - a.x) / (b.x - a.x)).collect();
|
||||
cuts.sort_by(f64::total_cmp);
|
||||
let mut cuts = cuts.into_iter().peekable();
|
||||
for j in 1..=k {
|
||||
let even = j as f64 / k as f64;
|
||||
while let Some(t) = cuts.next_if(|&t| t < even) {
|
||||
dense.push(a.lerp(b, t));
|
||||
}
|
||||
if sp.closed && i == segs - 1 && j == k {
|
||||
break;
|
||||
}
|
||||
dense.push(a.lerp(b, j as f64 / k as f64));
|
||||
dense.push(a.lerp(b, even));
|
||||
}
|
||||
}
|
||||
Some(dense)
|
||||
}
|
||||
|
||||
/// The values of `breaks` (in order) strictly between `a` and `b`, either way round.
|
||||
fn crossed(breaks: &[f64], a: f64, b: f64) -> &[f64] {
|
||||
let (lo, hi) = (a.min(b), a.max(b));
|
||||
let from = breaks.partition_point(|&x| x <= lo);
|
||||
let to = from + breaks[from..].partition_point(|&x| x < hi);
|
||||
&breaks[from..to]
|
||||
}
|
||||
|
||||
/// The parameters of `c` (in order, strictly between its ends) where its x is one of `breaks`;
|
||||
/// `line` when `c` is a line with its handles at thirds, whose x runs evenly.
|
||||
fn crossings(c: &CubicBez, line: bool, breaks: &[f64]) -> Vec<f64> {
|
||||
let xs = [c.p0.x, c.p1.x, c.p2.x, c.p3.x];
|
||||
let (lo, hi) = xs.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &x| (lo.min(x), hi.max(x)));
|
||||
let inside = crossed(breaks, lo, hi);
|
||||
if inside.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
let [a, b, cc, d] = xs;
|
||||
let mut ts: Vec<f64> = vec![];
|
||||
for &x in inside {
|
||||
if line {
|
||||
ts.push((x - a) / (d - a));
|
||||
} else {
|
||||
ts.extend(kurbo::common::solve_cubic(a - x, 3.0 * (b - a), 3.0 * (cc - 2.0 * b + a), d - 3.0 * cc + 3.0 * b - a));
|
||||
}
|
||||
}
|
||||
// Pieces are no shorter than the step the fit reads their ends' directions over.
|
||||
ts.retain(|t| t.is_finite() && *t > FIT_DT && *t < 1.0 - FIT_DT);
|
||||
ts.sort_by(f64::total_cmp);
|
||||
ts.dedup_by(|t, prev| *t - *prev <= FIT_DT);
|
||||
ts
|
||||
}
|
||||
|
||||
/// Times an art segment is halved at most while looking for cubics that fit it.
|
||||
const FIT_DEPTH: u32 = 12;
|
||||
/// Parameter step of the finite differences that stand in for the bend's derivative.
|
||||
@@ -156,7 +208,10 @@ fn fit_tol(doc_tol: f64) -> f64 {
|
||||
/// bend at the same parameters, so the distance measured is never less than the true one. The
|
||||
/// halving is our own rather than kurbo's `fit_to_bezpath`, which halves until the floats run out
|
||||
/// on a map that never fits; the depth and the anchor count bound this one.
|
||||
fn fitted(sp: &SubPath, f: &dyn Fn(Point) -> Point, tol: f64, most: usize) -> Option<SubPath> {
|
||||
///
|
||||
/// A segment is first split where its x crosses one of `breaks` (art x, in order), so a turn of
|
||||
/// the map there lands on an anchor rather than between the checked positions.
|
||||
fn fitted(sp: &SubPath, f: &dyn Fn(Point) -> Point, tol: f64, most: usize, breaks: &[f64]) -> Option<SubPath> {
|
||||
if !(tol.is_finite() && tol > 0.0) {
|
||||
return None;
|
||||
}
|
||||
@@ -174,7 +229,11 @@ fn fitted(sp: &SubPath, f: &dyn Fn(Point) -> Point, tol: f64, most: usize) -> Op
|
||||
// A line's handles sit on its ends, which stalls its parameter there; thirds keep it even.
|
||||
let c = if line { CubicBez::new(c.p0, c.p0.lerp(c.p3, 1.0 / 3.0), c.p0.lerp(c.p3, 2.0 / 3.0), c.p3) } else { c };
|
||||
let at = |t: f64| Some(f(c.eval(t))).filter(|q| q.is_finite());
|
||||
fit_into(&at, (0.0, 1.0), line, tol, FIT_DEPTH, &mut bp, &mut room)?;
|
||||
let mut t0 = 0.0;
|
||||
for t1 in crossings(&c, line, breaks).into_iter().chain([1.0]) {
|
||||
fit_into(&at, (t0, t1), line, tol, FIT_DEPTH, &mut bp, &mut room)?;
|
||||
t0 = t1;
|
||||
}
|
||||
}
|
||||
if sp.closed {
|
||||
bp.close_path();
|
||||
@@ -316,6 +375,16 @@ impl AlongMap {
|
||||
fn max_scale(&self) -> f64 {
|
||||
(0..3).map(|i| self.slope(i).abs()).fold(1e-6, f64::max)
|
||||
}
|
||||
|
||||
/// The art x (offset from the art's left edge) that [`AlongMap::at`] takes to arc length `s`,
|
||||
/// when a piece with width spans it.
|
||||
fn x_at(&self, s: f64) -> Option<f64> {
|
||||
(0..3).find_map(|i| {
|
||||
let ((x0, x1), (s0, s1)) = ((self.xs[i], self.xs[i + 1]), (self.ss[i], self.ss[i + 1]));
|
||||
let spans = x1 - x0 > 1e-12 && (s1 - s0).abs() > 1e-12 && s0.min(s1) <= s && s <= s0.max(s1);
|
||||
spans.then(|| x0 + (s - s0) / (s1 - s0) * (x1 - x0))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The affine that reproduces `f` over `b` to within `tol`, if one does.
|
||||
@@ -414,12 +483,14 @@ fn bend(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64) -> Option<N
|
||||
{
|
||||
return affine_node(art, a, cross.abs());
|
||||
}
|
||||
warp_node(art, &f, flat_tol, MAX_SEG / along.max_scale(), flat_tol * scale, cross.abs())
|
||||
warp_node(art, &f, flat_tol, MAX_SEG / along.max_scale(), flat_tol * scale, cross.abs(), &[])
|
||||
}
|
||||
|
||||
/// [`bend`], with the cross scale at arc length `s` multiplied by `widen(s)` (0..=1). The strokes
|
||||
/// of each object in the art take the factor at the middle of the object.
|
||||
fn bend_widened(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64, widen: &dyn Fn(f64) -> f64) -> Option<Node> {
|
||||
/// of each object in the art take the factor at the middle of the object. `marks` are the arc
|
||||
/// lengths (in order) of the recorded pen samples `widen` runs in a straight line between; the art
|
||||
/// is split where `widen` turns at one by more than the bent outline's tolerance ([`pen_breaks`]).
|
||||
fn bend_widened(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64, widen: &dyn Fn(f64) -> f64, marks: &[f64]) -> Option<Node> {
|
||||
let cy = b.center().y;
|
||||
let x0 = b.x0;
|
||||
let f = move |p: Point| {
|
||||
@@ -430,7 +501,45 @@ fn bend_widened(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64, wid
|
||||
let art = widen_strokes(art, &factor);
|
||||
let scale = along.max_scale().max(cross.abs()).max(1e-6);
|
||||
let flat_tol = tolerance(b.height().max(b.width()) * scale) / scale;
|
||||
warp_node(&art, &f, flat_tol, MAX_SEG / along.max_scale(), flat_tol * scale, cross.abs())
|
||||
// A change of `dw` in `widen` moves the art's top and bottom edges `dw × reach` across.
|
||||
let reach = b.height() / 2.0 * cross.abs();
|
||||
let mut breaks: Vec<f64> =
|
||||
pen_breaks(marks, along.span(), widen, fit_tol(flat_tol * scale) / reach).into_iter().filter_map(|s| along.x_at(s)).map(|x| x + x0).collect();
|
||||
breaks.sort_by(f64::total_cmp);
|
||||
breaks.dedup();
|
||||
warp_node(&art, &f, flat_tol, MAX_SEG / along.max_scale(), flat_tol * scale, cross.abs(), &breaks)
|
||||
}
|
||||
|
||||
/// The arc lengths among `marks` (in order) strictly within `(s0, s1)` at which the art is split:
|
||||
/// those where `widen` is more than `tol` from the straight line between the ones kept on either
|
||||
/// side (the span's ends to begin with), chosen by splitting at the farthest one until every
|
||||
/// sample left out is within `tol` of that line. `widen` runs straight between samples, so it
|
||||
/// is then within `tol` of the line between kept samples all along, and samples on a straight
|
||||
/// course add no splits.
|
||||
fn pen_breaks(marks: &[f64], (s0, s1): (f64, f64), widen: &dyn Fn(f64) -> f64, tol: f64) -> Vec<f64> {
|
||||
if !(s1 > s0 && tol > 0.0) {
|
||||
return vec![];
|
||||
}
|
||||
let inside = {
|
||||
let from = marks.partition_point(|&s| s <= s0);
|
||||
&marks[from..from + marks[from..].partition_point(|&s| s < s1)]
|
||||
};
|
||||
if inside.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
let pts: Vec<(f64, f64)> = std::iter::once(s0).chain(inside.iter().copied()).chain([s1]).map(|s| (s, widen(s))).collect();
|
||||
let mut keep = vec![false; pts.len()];
|
||||
let mut spans = vec![(0, pts.len() - 1)];
|
||||
while let Some((i, j)) = spans.pop() {
|
||||
let ((sa, wa), (sb, wb)) = (pts[i], pts[j]);
|
||||
let off = |&(s, w): &(f64, f64)| (w - if sb > sa { wa + (wb - wa) * (s - sa) / (sb - sa) } else { wa }).abs();
|
||||
let far = (i + 1..j).map(|k| (k, off(&pts[k]))).filter(|&(_, d)| d > tol).max_by(|a, b| a.1.total_cmp(&b.1));
|
||||
if let Some((k, _)) = far {
|
||||
keep[k] = true;
|
||||
spans.extend([(i, k), (k, j)]);
|
||||
}
|
||||
}
|
||||
pts.iter().zip(keep).filter(|&(_, k)| k).map(|(p, _)| p.0).collect()
|
||||
}
|
||||
|
||||
/// `n` with the strokes of it and of everything inside it scaled by `factor` of the object they
|
||||
@@ -465,8 +574,17 @@ fn art_runs(t: &Track) -> Vec<(f64, f64)> {
|
||||
bounds.windows(2).map(|w| (w[0], w[1])).collect()
|
||||
}
|
||||
|
||||
/// The art on [s0, s1] of `t`, `cross` across where `widen` (0..=1, by arc length) is 1.
|
||||
fn art_on_run(t: &Track, (s0, s1): (f64, f64), a: &ArtBrush, (art, b): (&Node, Rect), cross: f64, widen: &dyn Fn(f64) -> f64) -> Option<Node> {
|
||||
/// The art on [s0, s1] of `t`, `cross` across where `widen` (0..=1, by arc length) is 1 (`marks`
|
||||
/// as [`bend_widened`] takes them).
|
||||
fn art_on_run(
|
||||
t: &Track,
|
||||
(s0, s1): (f64, f64),
|
||||
a: &ArtBrush,
|
||||
(art, b): (&Node, Rect),
|
||||
cross: f64,
|
||||
widen: &dyn Fn(f64) -> f64,
|
||||
marks: &[f64],
|
||||
) -> Option<Node> {
|
||||
let l = s1 - s0;
|
||||
if l <= 1e-9 {
|
||||
return None;
|
||||
@@ -489,7 +607,7 @@ fn art_on_run(t: &Track, (s0, s1): (f64, f64), a: &ArtBrush, (art, b): (&Node, R
|
||||
}
|
||||
}
|
||||
};
|
||||
bend_widened(t, art, b, along, cross, widen)
|
||||
bend_widened(t, art, b, along, cross, widen, marks)
|
||||
}
|
||||
|
||||
/// An art brush's art along `bp`. With a width that follows the pen (its pressure, tilt, bearing
|
||||
@@ -515,9 +633,13 @@ pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64, stroke: &StrokeLayer)
|
||||
let p = a.width_mode.and_then(|m| PenAt::of(stroke, at / l).control(m)).unwrap_or(0.5);
|
||||
(light + (heavy - light) * p) / width
|
||||
};
|
||||
let marks = match a.width_mode {
|
||||
Some(m) if light != heavy && width > 0.0 => pen_marks(stroke, m, l),
|
||||
_ => vec![],
|
||||
};
|
||||
let runs = if a.overlap { art_runs(&t) } else { vec![(0.0, l)] };
|
||||
for run in runs {
|
||||
if let Some(n) = art_on_run(&t, run, a, (&art, b), cross, &widen) {
|
||||
if let Some(n) = art_on_run(&t, run, a, (&art, b), cross, &widen, &marks) {
|
||||
out.push(n);
|
||||
}
|
||||
}
|
||||
@@ -671,7 +793,7 @@ fn tile_scaled(t: &Track, tile: &(Node, Rect), s0: f64, s1: f64, k: &dyn Fn(f64)
|
||||
if mid <= 0.0 || marks.is_none_or(even) {
|
||||
return tile_on(t, tile, s0, s1, mid);
|
||||
}
|
||||
bend_widened(t, &tile.0, tile.1, AlongMap::linear(tile.1.width(), s0, s1), mid, &|s| k(s) / mid)
|
||||
bend_widened(t, &tile.0, tile.1, AlongMap::linear(tile.1.width(), s0, s1), mid, &|s| k(s) / mid, marks.unwrap_or_default())
|
||||
}
|
||||
|
||||
/// The most side tiles a run of a pattern brush places.
|
||||
@@ -966,7 +1088,7 @@ fn auto_corner(t: &Track, i: usize, source: CornerSource, side: &(Node, Rect), k
|
||||
}
|
||||
let s = if tw > 1e-9 { len / tw } else { 1.0 };
|
||||
let max_du = MAX_SEG / (2.0 * k * s.max(1.0));
|
||||
let warp = |f: &dyn Fn(Point) -> Point| warp_node(art, f, flat_tol, max_du, flat_tol * k, k);
|
||||
let warp = |f: &dyn Fn(Point) -> Point| warp_node(art, f, flat_tol, max_du, flat_tol * k, k, &[]);
|
||||
// Art point → (distance along from the left edge, stretched to `len`, and offset across).
|
||||
let along = move |q: Point| {
|
||||
let (x, y) = local(q);
|
||||
@@ -1393,7 +1515,7 @@ mod tests {
|
||||
let f = |p: Point| t.map(along.at(p.x - x0), p.y - cy);
|
||||
let tol = tolerance(b.height().max(b.width()));
|
||||
let exact = traced(art, &f, 1000);
|
||||
let chords: Vec<Point> = densified(art, tol, MAX_SEG).expect("the tile flattens").into_iter().map(f).collect();
|
||||
let chords: Vec<Point> = densified(art, tol, MAX_SEG, &[]).expect("the tile flattens").into_iter().map(f).collect();
|
||||
let curves = traced(sp, &|p| p, 200);
|
||||
let (e_curves, e_chords) = (apart(&curves, &exact), apart(&chords, &exact));
|
||||
// Checked at eight points a piece, so a little room between them.
|
||||
@@ -1419,7 +1541,7 @@ mod tests {
|
||||
let allowed: usize = path
|
||||
.subpaths
|
||||
.iter()
|
||||
.filter_map(|sp| densified(sp, 0.25, 1.5))
|
||||
.filter_map(|sp| densified(sp, 0.25, 1.5, &[]))
|
||||
.map(|dense| 1 + (FIT_CHECKS + 3) * (2 * dense.len() + FIT_DEPTH as usize + 1) + dense.len())
|
||||
.sum();
|
||||
let finite = |n: &Node| match &n.kind {
|
||||
@@ -1441,7 +1563,7 @@ mod tests {
|
||||
calls.set(calls.get() + 1);
|
||||
if calls.get() > allowed { Point::new(f64::NAN, f64::NAN) } else { f(p) }
|
||||
};
|
||||
let out = warp_node(&tile, &counted, 0.25, 1.5, 0.25, 1.0);
|
||||
let out = warp_node(&tile, &counted, 0.25, 1.5, 0.25, 1.0, &[]);
|
||||
assert!(calls.get() <= allowed, "map {i} was called {} times, {allowed} allowed", calls.get());
|
||||
match (i, &out) {
|
||||
(3, out) => assert!(out.is_none(), "a map that places nothing draws nothing"),
|
||||
@@ -1491,7 +1613,7 @@ mod tests {
|
||||
let mask = out.extras().mask.as_ref().expect("the mask is kept");
|
||||
assert_eq!(*mask.art, stroked(1), "{name} run: an unlinked mask stays where it was");
|
||||
|
||||
let out = bend_widened(t, &masked(true), b, along, 2.0, &|_| 0.5).expect("the art is drawn");
|
||||
let out = bend_widened(t, &masked(true), b, along, 2.0, &|_| 0.5, &[]).expect("the art is drawn");
|
||||
let mask = out.extras().mask.as_ref().expect("the mask is kept");
|
||||
assert_eq!(mask.art.kind, out.kind, "{name} run, widened: the mask's art bends with the art");
|
||||
assert_eq!(mask.art.appearance, out.appearance, "{name} run, widened: the mask's strokes narrow with the art's");
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
|
||||
@@ -82,6 +82,7 @@ impl Paths {
|
||||
/// isn't in the table or it, or a node it is in, was removed.
|
||||
pub(crate) fn get(&self, id: &NodeId) -> Option<Option<Vec<usize>>> {
|
||||
let e = (*self.table.ids.get(id)?)?;
|
||||
note_path_copy();
|
||||
let mut path = Vec::new();
|
||||
let mut cur = e;
|
||||
// Each step goes to a parent entry, made before its children: at most `at.len()` steps.
|
||||
@@ -96,6 +97,29 @@ impl Paths {
|
||||
}
|
||||
Some(None)
|
||||
}
|
||||
/// The node with `id` in `layers` at the place the table has for it, found without copying its index path: `None`
|
||||
/// when the table does not have one place for `id`, its path is deeper than [`NODE_IN_DEPTH`], or the node there
|
||||
/// does not have the id (the tree changed). The caller then looks it up as [`crate::Document::index_path`] does.
|
||||
pub(crate) fn node_in<'a>(&self, layers: &'a [Arc<Node>], id: NodeId) -> Option<&'a Node> {
|
||||
let mut cur = (*self.table.ids.get(&id)?)?;
|
||||
let mut steps = [0u32; NODE_IN_DEPTH];
|
||||
let mut depth = 0;
|
||||
loop {
|
||||
let &(parent, i) = self.table.at.get(cur as usize)?;
|
||||
*steps.get_mut(depth)? = self.shifted(parent, i)?;
|
||||
depth += 1;
|
||||
if parent == u32::MAX {
|
||||
break;
|
||||
}
|
||||
cur = parent;
|
||||
}
|
||||
let mut path = steps[..depth].iter().rev();
|
||||
let mut node: &Node = layers.get(*path.next()? as usize)?;
|
||||
for &i in path {
|
||||
node = node.children()?.get(i as usize)?;
|
||||
}
|
||||
(node.id == id).then_some(node)
|
||||
}
|
||||
/// Where the table has `id` as it was built: its parent's entry and its index among its
|
||||
/// siblings then; `None` when the id isn't in the table or appears more than once.
|
||||
pub(crate) fn table_place(&self, id: &NodeId) -> Option<(u32, u32)> {
|
||||
@@ -170,6 +194,25 @@ pub(crate) fn note_path_lookup() {
|
||||
PATH_LOOKUPS.set(PATH_LOOKUPS.get().saturating_add(1));
|
||||
}
|
||||
|
||||
/// The deepest index path [`Paths::node_in`] follows without copying it.
|
||||
const NODE_IN_DEPTH: usize = 32;
|
||||
|
||||
thread_local! {
|
||||
/// [`path_copies`] of this thread.
|
||||
static PATH_COPIES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many index paths the lookup cache has copied out on this thread, one for each [`crate::Document::index_path`]
|
||||
/// that it answered. [`crate::Document::node`] reads the node from the cache without one.
|
||||
pub fn path_copies() -> u64 {
|
||||
PATH_COPIES.get()
|
||||
}
|
||||
|
||||
/// Adds one to [`path_copies`].
|
||||
fn note_path_copy() {
|
||||
PATH_COPIES.set(PATH_COPIES.get().saturating_add(1));
|
||||
}
|
||||
|
||||
/// The cache, shared by clones of a document (each checks every path it uses against its own tree),
|
||||
/// the lookups that missed it, and the nodes removed from the tree since it was built.
|
||||
#[derive(Default)]
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -579,3 +579,32 @@ fn nearest_finder_reads_one_path_per_object() {
|
||||
assert_eq!(path_lookups() - lookups, 0, "lookups by id");
|
||||
assert_eq!(tree_walks() - walks, 0, "walks of the tree");
|
||||
}
|
||||
|
||||
/// `Document::node` reads a node from the lookup cache without copying its index path, in nested groups and after
|
||||
/// objects were removed, and finds what a walk finds: 10,000 objects looked up one at a time copy no path.
|
||||
#[test]
|
||||
fn node_lookups_copy_no_index_path() {
|
||||
let (mut d, ids) = squares(10_000);
|
||||
let layer = d.layers[0].id;
|
||||
let mut nested = vec![];
|
||||
for g in 0..50 {
|
||||
let kids: Vec<Arc<Node>> = (0..4)
|
||||
.map(|_| {
|
||||
let id = d.alloc_id();
|
||||
nested.push(id);
|
||||
Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art()))
|
||||
})
|
||||
.collect();
|
||||
let (gid, inner) = (d.alloc_id(), d.alloc_id());
|
||||
d.insert(Some(layer), g, Node::group(gid, vec![Arc::new(Node::group(inner, kids))])).unwrap();
|
||||
}
|
||||
d.remove_many(&ids[..100]).unwrap();
|
||||
d.node(layer);
|
||||
let copies = path_copies();
|
||||
let found = ids[100..].iter().chain(&nested).filter(|id| d.node(**id).is_some_and(|n| n.id == **id)).count();
|
||||
assert_eq!(found, ids.len() - 100 + nested.len());
|
||||
assert_eq!(path_copies() - copies, 0, "index paths copied");
|
||||
assert!(ids[..100].iter().all(|id| d.node(*id).is_none()), "removed objects are not found");
|
||||
agree(&d, &ids[..200], "after remove_many");
|
||||
agree(&d, &nested, "nested");
|
||||
}
|
||||
@@ -110,7 +110,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Three-Point Arc",
|
||||
[],
|
||||
None,
|
||||
"{start: [x, y], end: [x, y], through?: [x, y], toward?: [x, y], at?: \"start\"|\"end\" (default \"start\"; only with `toward`)} → {id, cx, cy, radius, sweep}: an open circular arc from `start` to `end` in the current stroke (black when it is none) with no fill, its ends exactly at the two points (not pixel-aligned). With `through`, the arc passes through that point, an anchor of the path; with `toward`, it leaves the end `at` names heading toward that point (its tangent there). Give exactly one of `through` and `toward`; `at` with `through` is an error. `sweep` is the arc's turn in degrees, positive clockwise on the page. Two points that are the same, three on one line, or an arc reaching past the canvas are an error, and nothing is drawn",
|
||||
"{start: [x, y], end: [x, y], through?: [x, y], toward?: [x, y], at?: \"start\"|\"end\" (default \"start\"; only with `toward`), join?: bool (default false)} → {id, cx, cy, radius, sweep, joined?}: an open circular arc from `start` to `end` in the current stroke (black when it is none) with no fill, its ends exactly at the two points (not pixel-aligned). With `through`, the arc passes through that point, an anchor of the path; with `toward`, it leaves the end `at` names heading toward that point (its tangent there). Give exactly one of `through` and `toward`; `at` with `through` is an error. `sweep` is the arc's turn in degrees, positive clockwise on the page. With `join`, an end of the arc on an end of an editable open path (inside the isolated group in isolation mode) joins the arc to that path, which keeps its look and, when one end joins, its direction (a path in the selection comes first); with both ends on open path ends the second path joins too, or the path closes when both are its own ends. The result then has `joined: true` and `id` is the joined path (or its compound path). A `join` that is not true or false is an error. Two points that are the same, three on one line, or an arc reaching past the canvas are an error, and nothing is drawn",
|
||||
has_doc,
|
||||
three_point_arc
|
||||
),
|
||||
@@ -747,7 +747,8 @@ fn arc(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// An open circular arc from `start` to `end` ([`shapes::CircularArc`]): through `through`, or
|
||||
/// leaving the end `at` names toward `toward`. One undo step, named as an Arc tool drag is.
|
||||
/// leaving the end `at` names toward `toward`. With `join`, joined to the open paths whose ends
|
||||
/// its ends lie on ([`super::path::join_arc`]). One undo step, named as an Arc tool drag is.
|
||||
fn three_point_arc(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "shape.threePointArc";
|
||||
let point = |key: &str| finite_numbers::<2>(&p[key]).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(C, format!("`{key}` must be [x, y]")));
|
||||
@@ -774,8 +775,32 @@ fn three_point_arc(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
_ => return Err(bad(C, "give exactly one of `through` and `toward`")),
|
||||
};
|
||||
let join = match p.get("join") {
|
||||
None => false,
|
||||
Some(Value::Bool(on)) => *on,
|
||||
Some(_) => return Err(bad(C, "`join` must be true or false")),
|
||||
};
|
||||
let arc = arc.ok_or_else(|| bad(C, "no arc fits these points: two are the same or all three lie on one line"))?;
|
||||
let path = via.map_or_else(|| arc.to_path(), |v| arc.to_path_via(v));
|
||||
let ends = if join {
|
||||
let st = s.doc()?;
|
||||
let selected = st.selection.objects.clone();
|
||||
let find = |at| super::path::open_end_at(&st.doc, st.isolation, &selected, at);
|
||||
(find(start), find(end))
|
||||
} else {
|
||||
(None, None)
|
||||
};
|
||||
if ends.0.is_some() || ends.1.is_some() {
|
||||
let sub = path.subpaths.first().cloned().ok_or_else(|| bad(C, "no arc fits these points"))?;
|
||||
let id = s.edit("Arc", |d, sel| {
|
||||
let id = super::path::join_arc(d, &sub, ends.0, ends.1)?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})?;
|
||||
return Ok(
|
||||
json!({ "id": id.0, "joined": true, "cx": arc.center.x, "cy": arc.center.y, "radius": arc.radius, "sweep": arc.sweep.to_degrees() }),
|
||||
);
|
||||
}
|
||||
let look = s.new_art_look(
|
||||
vectorcraft_color::Paint::None,
|
||||
if s.paint.stroke.is_none() { vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK) } else { s.paint.stroke.clone() },
|
||||
|
||||
@@ -268,16 +268,22 @@ fn from_editing_data_alone(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions)
|
||||
if !every_page(opened.page_count(), opts) || !opts.layers || !opts.editing_data {
|
||||
return None;
|
||||
}
|
||||
Some(editing_copy_alone(&decoded_copy(opened)?, opts))
|
||||
// A placeholder page's fonts aren't the art's.
|
||||
Some(editing_copy_alone(&decoded_copy(opened)?, opts, Default::default()))
|
||||
}
|
||||
|
||||
/// [`from_editing_data_alone`] of `decoded`, the editor's copy already read and decoded, or why it
|
||||
/// can't be decoded.
|
||||
fn editing_copy_alone(decoded: &std::result::Result<Vec<u8>, String>, opts: &LoadOptions) -> Result<(Document, Vec<String>)> {
|
||||
/// can't be decoded, with `widths`, the widths the file's PDF part gives the characters of its
|
||||
/// fonts, which tell installed copies of a font apart ([`vectorcraft_eps::AiLayers::with_page_widths`]).
|
||||
fn editing_copy_alone(
|
||||
decoded: &std::result::Result<Vec<u8>, String>,
|
||||
opts: &LoadOptions,
|
||||
widths: vectorcraft_pdf::PageWidths,
|
||||
) -> Result<(Document, Vec<String>)> {
|
||||
decoded
|
||||
.as_ref()
|
||||
.map_err(Clone::clone)
|
||||
.and_then(|data| vectorcraft_eps::ai_alone_decoded(data, opts.legacy_names))
|
||||
.and_then(|data| vectorcraft_eps::ai_alone_decoded(data, opts.legacy_names, widths))
|
||||
.map_err(|why| err(format!("this file was saved without PDF compatibility, and its editing data can't be read ({why})")))
|
||||
}
|
||||
|
||||
@@ -473,6 +479,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
Err(e) => Err(err(e)),
|
||||
};
|
||||
let mut read = restore_or_import(editing, || {
|
||||
// The widths the PDF part gives the characters of its fonts, which tell installed
|
||||
// copies of a font apart: read once, when the editing copy is.
|
||||
let page_widths = std::cell::OnceCell::new();
|
||||
let widths = || page_widths.get_or_init(|| opened.as_ref().map(vectorcraft_pdf::Opened::page_widths).unwrap_or_default()).clone();
|
||||
// Type all from the text document and nothing that needs the PDF part: the layers
|
||||
// alone, the PDF part not imported. Else what was read of the layers is kept for
|
||||
// reading them with the PDF part.
|
||||
@@ -480,7 +490,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
if let Some((o, private)) = opened.as_ref().ok().filter(|_| reads_layers_alone(opts)).and_then(|o| Some((o, editing_copy(o, opts)?)))
|
||||
{
|
||||
let pages = o.trim_pages();
|
||||
match vectorcraft_eps::ai_layers_alone_decoded(private, &pages.sizes, pages.user_unit, opts.legacy_names) {
|
||||
match vectorcraft_eps::ai_layers_alone_decoded(private, &pages.sizes, pages.user_unit, opts.legacy_names, widths()) {
|
||||
Ok((mut doc, warnings)) => {
|
||||
doc.setup.bleed = pages.bleed;
|
||||
editing_data = true;
|
||||
@@ -502,9 +512,9 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
// decoded draws nothing either): its notes are at most the page's own.
|
||||
let empty = draws_nothing(&r.document) && r.warnings.iter().all(|w| is_page_note(w));
|
||||
let copy_alone = || match &private {
|
||||
Some(private) => Some(editing_copy_alone(private, opts)),
|
||||
Some(private) => Some(editing_copy_alone(private, opts, widths())),
|
||||
None if layers.is_some() => {
|
||||
opened.as_ref().ok().and_then(|o| editing_copy(o, opts)).map(|p| editing_copy_alone(&p, opts))
|
||||
opened.as_ref().ok().and_then(|o| editing_copy(o, opts)).map(|p| editing_copy_alone(&p, opts, widths()))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
@@ -516,7 +526,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
let (doc, warnings, read) = match alone {
|
||||
Some((doc, warnings)) => (doc, warnings, true),
|
||||
None => {
|
||||
let layers = layers.or_else(|| private.map(vectorcraft_eps::AiLayers::decoded));
|
||||
let layers = layers.or_else(|| private.map(|p| vectorcraft_eps::AiLayers::decoded(p).with_page_widths(widths())));
|
||||
through_editing_data(layers, opts, r.document, r.warnings, r.user_unit)
|
||||
}
|
||||
};
|
||||
|
||||
@@ -2234,3 +2234,110 @@ fn an_illustrator_ai_file_opens_with_its_layers_closed() {
|
||||
assert_eq!(r["restored"], json!(true), "{r}");
|
||||
assert_eq!(open_rows(&s).1, ["Art", "Hidden"]);
|
||||
}
|
||||
|
||||
/// A `.ai` whose layer `Art` holds one line of type, `Hamburg`, that its text document sets in the
|
||||
/// font of PostScript name `name` (a font record without a version), and whose PDF part sets it in
|
||||
/// a subset of that font that gives each character the width `width` gives it, in thousandths of an
|
||||
/// em. With `square`, the layer and the page have a gray square too. The editing copy's artboard is
|
||||
/// 200 × 100 pt, and the page `page_width` × 100.
|
||||
fn type_in_copy_ai(name: &str, square: bool, page_width: f64, width: impl Fn(char) -> f64) -> Vec<u8> {
|
||||
let story = "Hamburg";
|
||||
let n = story.chars().count() + 1;
|
||||
let document = format!(
|
||||
"/0 << /1 << /0 [ << /0 << /0 << /0 ({name}) >> >> >> ] >> /8 << /0 [ << /0 << /0 [ 0 0 ] /2 << /2 [ 1 0 0 1 0 0 ] >> >> >> ] >> >>\n\
|
||||
/1 << /1 [ << /0 << /0 ({story}\r) /5 << /0 [ << /0 << /0 << /0 () /5 << /0 0 >> /6 0 >> >> /1 {n} >> ] >> \
|
||||
/6 << /0 [ << /0 << /0 << /0 () /5 0 /6 << /0 0 /1 10.0 >> >> >> /1 {n} >> ] >> >> \
|
||||
/1 << /0 [ << /0 0 >> ] /2 [ << /99 /PC /6 [ << /99 /F /0 << /0 [ 8105.5 8176.5 ] >> /6 [ << /99 /R /6 [ << /99 /R /6 [ << /99 /L /6 [ \
|
||||
<< /99 /S /0 << /0 [ 0.0 0.0 ] >> /15 << /0 {n} >> >> ] >> ] >> ] >> ] >> ] >> ] >> >> ] /2 << /1 12.0 >> >>\n"
|
||||
);
|
||||
let lines: Vec<String> = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect();
|
||||
let text = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n";
|
||||
let (art, drawn) =
|
||||
if square { (format!("0.5 g\n{}f\n{text}", ai::rect(120.0, 20.0, 160.0, 60.0)), "0.5 g 120 20 40 40 re f ") } else { (text.to_string(), "") };
|
||||
let body = format!(
|
||||
"%AI3_TemplateBox: 100 50 100 50\n{}%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n",
|
||||
ai::layer("Art", &art),
|
||||
lines.join("\n")
|
||||
);
|
||||
let data = ai::editing_data(200.0, 100.0, &body);
|
||||
let widths: Vec<String> = (32u8..=126).map(char::from).map(|c| if story.contains(c) { width(c).to_string() } else { "0".into() }).collect();
|
||||
let page = PdfPage {
|
||||
resources: format!(
|
||||
"/Font << /F1 << /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+{name} /FirstChar 32 /Widths [{}] /Encoding /WinAnsiEncoding >> >>",
|
||||
widths.join(" ")
|
||||
),
|
||||
entries: format!("/PieceInfo << /Illustrator << /Private << /AIPrivateData1 {} 0 R /NumBlock 1 >> >> >>", first_extra(1)),
|
||||
// A page that is only type, with its art box, isn't a placeholder.
|
||||
art: Some([0.0, 0.0, page_width, 100.0]),
|
||||
..PdfPage::new(page_width, 100.0, &format!("{drawn}BT /F1 10 Tf 14 65 Td ({story}) Tj ET"))
|
||||
};
|
||||
pdf_with(&[page], &[&format!("<< /Length {} >>\nstream\n{data}\nendstream", data.len())], None)
|
||||
}
|
||||
|
||||
/// Type from the text document of a `.ai` whose font record keeps no version, where two installed
|
||||
/// copies of the font share its PostScript name, family and style and differ in their widths, is
|
||||
/// set in the copy that sets its characters at the widths the file's PDF part gives them: whether
|
||||
/// its layers open alone, with the PDF part imported, or from the editing copy alone because the PDF
|
||||
/// part is only type (read after the layers alone, on a page of another size, were not used).
|
||||
#[test]
|
||||
fn type_from_the_text_document_takes_the_copy_its_pdf_part_sets_it_in() {
|
||||
let (db, width) = (vectorcraft_text::FontDb::global(), install_width_copies("Pagewtest Ink", "PagewtestInk-Regular"));
|
||||
let trim = LoadOptions { crop: vectorcraft_pdf::CropTo::Trim, ..Default::default() };
|
||||
// (a square beside the type, the page's width, the options, whether the PDF part is imported)
|
||||
let cases = [
|
||||
(true, 200.0, &LoadOptions::default(), false),
|
||||
(true, 200.0, &trim, true),
|
||||
(false, 200.0, &LoadOptions::default(), false),
|
||||
(false, 200.0, &trim, true),
|
||||
(false, 260.0, &LoadOptions::default(), true),
|
||||
];
|
||||
for (square, page_width, opts, imported) in cases {
|
||||
let file = type_in_copy_ai("PagewtestInk-Regular", square, page_width, &width);
|
||||
let before = vectorcraft_pdf::imports_of(&file);
|
||||
let loaded = load_with("copies.ai", &file, opts).unwrap();
|
||||
let case = format!("square {square}, page {page_width}, {:?}: {:?}", opts.crop, loaded.warnings);
|
||||
assert!(loaded.editing_data, "{case}");
|
||||
assert_eq!(vectorcraft_pdf::imports_of(&file) > before, imported, "{case}");
|
||||
let art = loaded.doc.layers[0].children().unwrap();
|
||||
assert_eq!(art.len(), 1 + usize::from(square), "{case}");
|
||||
let Some(NodeKind::Text(t)) = art.iter().map(|n| &n.kind).find(|k| matches!(k, NodeKind::Text(_))) else { panic!("type: {case}") };
|
||||
assert_eq!(t.plain_text(), "Hamburg");
|
||||
assert_eq!(db.style_face(&t.runs[0].style).unwrap().version, "1.1", "{case}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Installs two copies of family `family` and PostScript name `name`: Inter as version 1.0, loaded
|
||||
/// first, and Source Sans 3 as 1.1, whose advances (thousandths of an em) the returned function gives.
|
||||
fn install_width_copies(family: &str, name: &str) -> impl Fn(char) -> f64 + use<> {
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
for (inter, version) in [(true, "1.0"), (false, "1.1")] {
|
||||
let font = vectorcraft_text::test_fonts::named_copy(inter, (family, "Regular", version, name)).unwrap();
|
||||
assert_eq!(db.add_font(font), 1);
|
||||
}
|
||||
let newer = db.postscript_faces(name).into_iter().find(|f| f.version == "1.1").unwrap();
|
||||
move |c: char| newer.advance(newer.glyph_for(c)) * 1000.0 / newer.units_per_em()
|
||||
}
|
||||
|
||||
/// Type the PDF part's widths set in the second copy of its font is saved as `.ai` with that
|
||||
/// copy's version in its font record, so it opens in the same copy again, from the editing copy
|
||||
/// alone as from the whole file.
|
||||
#[test]
|
||||
fn type_in_the_copy_its_pdf_part_sets_comes_back_in_it_from_a_save() {
|
||||
let (db, width) = (vectorcraft_text::FontDb::global(), install_width_copies("Pagewrt Ink", "PagewrtInk-Regular"));
|
||||
let mut s = Session::new();
|
||||
let r = open(&mut s, "copies.ai", &type_in_copy_ai("PagewrtInk-Regular", true, 200.0, &width), json!({})).unwrap();
|
||||
let saved = s.execute("file.saveCopy", &json!({"format": "ai"})).unwrap();
|
||||
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
|
||||
let versions = |doc: &vectorcraft_doc::Document| -> Vec<String> {
|
||||
let art = doc.layers[0].children().unwrap();
|
||||
art.iter()
|
||||
.filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some(db.style_face(&t.runs[0].style).unwrap().version.clone()) } else { None })
|
||||
.collect()
|
||||
};
|
||||
assert_eq!(versions(&s.doc().unwrap().doc), ["1.1"], "{r}");
|
||||
let loaded = load_with("saved.ai", &bytes, &LoadOptions { native: false, ..Default::default() }).unwrap();
|
||||
assert!(loaded.editing_data, "{:?}", loaded.warnings);
|
||||
assert_eq!(versions(&loaded.doc), ["1.1"], "{:?}", loaded.warnings);
|
||||
let private = vectorcraft_pdf::illustrator_data(&bytes, None).unwrap();
|
||||
assert_eq!(versions(&vectorcraft_eps::ai_alone(&private).unwrap().0), ["1.1"]);
|
||||
}
|
||||
@@ -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)?;
|
||||
|
||||
@@ -59,7 +59,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Direction Handles",
|
||||
[],
|
||||
None,
|
||||
"{handles: [{id, subpath?, anchor, which: \"in\"|\"out\"}, ...], dx, dy, independent?: bool} move several direction handles by (dx, dy) as one undo step; an anchor with one handle listed moves it as path.setHandle does (a smooth anchor turns its other handle in line at its own length), and an anchor with both handles listed moves both and becomes a corner; independent (default false) makes every listed handle's anchor a corner and leaves its other handle; a handle listed twice moves once; an empty list, a missing or unknown path, subpath or anchor, or a which other than \"in\" or \"out\" is refused",
|
||||
"{handles: [{id, subpath?, anchor, which: \"in\"|\"out\"}, ...], dx, dy, independent?: bool} move several direction handles by (dx, dy) as one undo step; an anchor with one handle listed moves it as path.setHandle does (a smooth anchor turns its other handle in line at its own length), and an anchor with both handles listed moves both and becomes a corner; independent (default false) makes every listed handle's anchor a corner and leaves its other handle; a handle listed twice moves once; a move by 0, 0 changes only the anchors it makes corners, so a live shape with no such anchor stays live and one with such an anchor becomes a plain path, and with none it changes nothing and records no undo step; an empty list, a missing or unknown path, subpath or anchor, or a which other than \"in\" or \"out\" is refused",
|
||||
has_doc,
|
||||
move_handles
|
||||
),
|
||||
@@ -643,8 +643,9 @@ fn move_handles(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// A move by nothing changes only the kind of anchors that become corners: those with both
|
||||
// handles listed, or every listed one with `independent`.
|
||||
// The other anchors are left out, so a live shape that only they lie on is not expanded.
|
||||
if d == Vec2::ZERO {
|
||||
let corners = anchors.iter().any(|(&(id, si, ai), &(inn, out))| {
|
||||
anchors.retain(|&(id, si, ai), &mut (inn, out)| {
|
||||
(independent || (inn && out))
|
||||
&& doc
|
||||
.node(id)
|
||||
@@ -652,7 +653,7 @@ fn move_handles(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai))
|
||||
.is_some_and(|a| a.kind != AnchorKind::Corner)
|
||||
});
|
||||
if !corners {
|
||||
if anchors.is_empty() {
|
||||
return ok();
|
||||
}
|
||||
}
|
||||
@@ -1593,6 +1594,91 @@ fn join_pair(d: &mut Document, (a, sa): (NodeId, usize), (b, sb): (NodeId, usize
|
||||
Ok(compound_or_self(d, a))
|
||||
}
|
||||
|
||||
/// An end of an open subpath of an editable path (not a guide) at `at`: the path, the subpath and
|
||||
/// whether the end is the subpath's first anchor. In isolation mode (`scope`), only a path inside
|
||||
/// the isolated node counts. Among several, one in or inside the selection `selected` comes first,
|
||||
/// then the last in paint order.
|
||||
pub(super) fn open_end_at(d: &Document, scope: Option<NodeId>, selected: &[NodeId], at: Point) -> Option<(NodeId, usize, bool)> {
|
||||
let editable = d.editable();
|
||||
let mut found: Option<((NodeId, usize, bool), bool)> = None;
|
||||
d.walk(|n| {
|
||||
let NodeKind::Path { path, guide: false, .. } = &n.kind else { return };
|
||||
if !editable(n.id) {
|
||||
return;
|
||||
}
|
||||
let chain = d.ancestry(n.id).unwrap_or_default();
|
||||
if scope.is_some_and(|s| !chain.contains(&s)) {
|
||||
return;
|
||||
}
|
||||
let chosen = chain.iter().any(|id| selected.contains(id));
|
||||
for (si, sp) in path.subpaths.iter().enumerate().filter(|(_, sp)| !sp.closed) {
|
||||
let Some((first, last)) = end_points(sp) else { continue };
|
||||
let end = if last.distance(at) < 1e-6 {
|
||||
false
|
||||
} else if first.distance(at) < 1e-6 {
|
||||
true
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
if found.is_none_or(|(_, was)| chosen || !was) {
|
||||
found = Some(((n.id, si, end), chosen));
|
||||
}
|
||||
}
|
||||
});
|
||||
found.map(|(end, _)| end)
|
||||
}
|
||||
|
||||
/// `sp`, an open subpath whose end (its first anchor when `at_first`) lies on an end of `arc`
|
||||
/// (its first anchor when `arc_at_start`), with `arc` added there: one subpath running the way
|
||||
/// `sp` runs. The anchor where they meet is `sp`'s, with its handle on the arc's side taken from
|
||||
/// the arc.
|
||||
fn splice(sp: &SubPath, at_first: bool, arc: &SubPath, arc_at_start: bool) -> SubPath {
|
||||
let mut arc = arc.clone();
|
||||
if arc_at_start == at_first {
|
||||
arc.reverse();
|
||||
}
|
||||
let mut out = sp.clone();
|
||||
if at_first {
|
||||
let meet = arc.anchors.pop();
|
||||
if let (Some(meet), Some(first)) = (meet, out.anchors.first_mut()) {
|
||||
first.h_in = meet.h_in;
|
||||
}
|
||||
arc.anchors.extend(out.anchors);
|
||||
out.anchors = arc.anchors;
|
||||
} else {
|
||||
if !arc.anchors.is_empty() {
|
||||
let meet = arc.anchors.remove(0);
|
||||
if let Some(last) = out.anchors.last_mut() {
|
||||
last.h_out = meet.h_out;
|
||||
}
|
||||
}
|
||||
out.anchors.extend(arc.anchors);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The arc `arc` joined to the open path ends `start` (at its first anchor) and `end` (at its
|
||||
/// last), as [`open_end_at`] gives them, at least one of them. The arc joins the path at `start`
|
||||
/// first, keeping that path's direction and look, and then, when `end` is an end of another open
|
||||
/// subpath, that subpath joins it as Join joins two paths; when `end` is the other end of the same
|
||||
/// subpath, the subpath closes. Returns what to select: the joined path, or its compound path.
|
||||
pub(super) fn join_arc(d: &mut Document, arc: &SubPath, start: Option<(NodeId, usize, bool)>, end: Option<(NodeId, usize, bool)>) -> Result<NodeId> {
|
||||
let err = || EngineError::Other("join needs open paths".into());
|
||||
let ((id, si, at_first), arc_at_start, rest) = match (start, end) {
|
||||
(Some(s), e) => (s, true, e),
|
||||
(None, Some(e)) => (e, false, None),
|
||||
(None, None) => return Err(err()),
|
||||
};
|
||||
let path = path_mut(d, id)?;
|
||||
let sp = path.subpaths.get_mut(si).filter(|sp| !sp.closed && !sp.anchors.is_empty()).ok_or_else(err)?;
|
||||
*sp = splice(sp, at_first, arc, arc_at_start);
|
||||
match rest {
|
||||
// The arc's far end is the first anchor of the joined subpath when it was added before it.
|
||||
Some((other, osi, other_first)) => join_pair(d, (id, si), (other, osi), (at_first, !other_first), None),
|
||||
None => Ok(compound_or_self(d, id)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) type AnchorTargets = Vec<(NodeId, Vec<(usize, usize)>)>;
|
||||
|
||||
pub(super) fn anchor_targets(s: &Session) -> Result<AnchorTargets> {
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -59,6 +59,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
break_thread
|
||||
),
|
||||
cmd!(
|
||||
"text.thread.setNeighbor",
|
||||
"Thread Text",
|
||||
[],
|
||||
None,
|
||||
"{id, side: \"next\"|\"previous\", neighbor: id|null} link area type or type on a path `id` to the frame that follows it (`next`) or comes before it (`previous`) in its story, or with null break that one link, as a script's `nextFrame` and `previousFrame` assignments do. Linking joins two stories: `id` must be the last frame of its story for `next` (the first for `previous`) and `neighbor` the first (the last) of another one, and the second story's text flows on after the first's. Breaking a link makes each side of it a story of its own: no text moves across the break, and the frames after it flow their own text again from their first frame, which now starts a paragraph. An error, with nothing changed, for point type or other art, a frame linked to itself, a link that would make a loop or go to a frame inside a story, and a frame of either story that is hidden or locked; a link that is already there, or a break where there is no link, changes nothing and records no undo step; the selection is kept → {changed: bool, threads: [[id…]] (the stories of the frames involved, after the change, a one-frame story as [id])}",
|
||||
has_doc,
|
||||
set_neighbor
|
||||
),
|
||||
cmd!(query "text.thread.info", "Threads", [], None, "{} → [[id…]] every thread in order", has_doc, |s, _| {
|
||||
Ok(json!(s.doc()?.doc.text_threads.iter().map(|t| t.iter().map(|i| i.0).collect::<Vec<_>>()).collect::<Vec<_>>()))
|
||||
}),
|
||||
@@ -986,5 +995,111 @@ fn break_thread(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// The frames of the story `id` is a frame of, in thread order: its thread's area type and type on
|
||||
/// a path, each once, or `id` alone when it is in no thread.
|
||||
fn chain_of(d: &Document, id: NodeId) -> Vec<NodeId> {
|
||||
let mut frames = story_of(d, id);
|
||||
let mut seen = Ids::default();
|
||||
frames.retain(|f| seen.insert(*f));
|
||||
if frames.len() < 2 { vec![id] } else { frames }
|
||||
}
|
||||
|
||||
fn chain_ids(chains: &[&[NodeId]]) -> Value {
|
||||
json!(chains.iter().filter(|c| !c.is_empty()).map(|c| c.iter().map(|i| i.0).collect::<Vec<_>>()).collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
/// `text.thread.setNeighbor`: link a frame to the frame after or before it, or break that link.
|
||||
fn set_neighbor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.thread.setNeighbor";
|
||||
let id = checked_id(s, p.get("id").unwrap_or(&Value::Null), C)?;
|
||||
let next = match p.get("side").and_then(Value::as_str) {
|
||||
Some("next") => true,
|
||||
Some("previous") => false,
|
||||
_ => return Err(bad(C, "`side` must be \"next\" or \"previous\"")),
|
||||
};
|
||||
let neighbor = match p.get("neighbor") {
|
||||
None => return Err(bad(C, "missing `neighbor` (an id, or null to break the link)")),
|
||||
Some(Value::Null) => None,
|
||||
Some(v) => Some(checked_id(s, v, C)?),
|
||||
};
|
||||
let d = &s.doc()?.doc;
|
||||
if text_of(d, id).is_none() {
|
||||
return Err(bad(C, "`id` must be area type or type on a path"));
|
||||
}
|
||||
let locked = |frames: &[NodeId]| {
|
||||
let editable = d.editable();
|
||||
frames.iter().any(|f| !editable(*f))
|
||||
};
|
||||
let chain = chain_of(d, id);
|
||||
let Some(n) = neighbor else {
|
||||
// Break the link on that side: the frames before it and the frames after it.
|
||||
let i = chain.iter().position(|f| *f == id).unwrap_or(0);
|
||||
let at = if next { i + 1 } else { i };
|
||||
if at == 0 || at >= chain.len() {
|
||||
return Ok(json!({"changed": false, "threads": chain_ids(&[&chain])}));
|
||||
}
|
||||
if locked(&chain) {
|
||||
return Err(bad(C, "a frame of the story is hidden or locked"));
|
||||
}
|
||||
let (head, tail) = (chain[..at].to_vec(), chain[at..].to_vec());
|
||||
let cut: Ids = chain.iter().copied().collect();
|
||||
s.edit("Break Thread", |d, _| {
|
||||
d.text_threads.retain(|t| !t.iter().any(|f| cut.contains(f)));
|
||||
for part in [&head, &tail] {
|
||||
if part.len() >= 2 {
|
||||
d.text_threads.push(part.clone());
|
||||
}
|
||||
}
|
||||
// The first frame after the break starts its story, which flows again on this edit so
|
||||
// that its numbered paragraphs count from 1.
|
||||
if let Some(f) = tail.first() {
|
||||
touch(d, *f);
|
||||
}
|
||||
if let Some(NodeKind::Text(t)) = tail.first().and_then(|f| d.node_mut(*f)).map(|n| &mut n.kind)
|
||||
&& t.first_para_continues
|
||||
{
|
||||
t.first_para_continues = false;
|
||||
refresh_bounds(t);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
return Ok(json!({"changed": true, "threads": chain_ids(&[&head, &tail])}));
|
||||
};
|
||||
if n == id {
|
||||
return Err(bad(C, "a frame cannot be linked to itself"));
|
||||
}
|
||||
if text_of(d, n).is_none() {
|
||||
return Err(bad(C, "`neighbor` must be area type or type on a path"));
|
||||
}
|
||||
// `first` is to flow into `second`.
|
||||
let (first, second) = if next { (id, n) } else { (n, id) };
|
||||
let (a, b) = if next { (chain, chain_of(d, n)) } else { (chain_of(d, n), chain) };
|
||||
if a.contains(&second) {
|
||||
if a.windows(2).any(|w| w == [first, second]) {
|
||||
return Ok(json!({"changed": false, "threads": chain_ids(&[&a])}));
|
||||
}
|
||||
return Err(bad(C, "the two frames are already in one story: the link would make a loop or reorder it"));
|
||||
}
|
||||
if a.last() != Some(&first) {
|
||||
return Err(bad(C, format!("frame {} already has a next frame: break that link first", first.0)));
|
||||
}
|
||||
if b.first() != Some(&second) {
|
||||
return Err(bad(C, format!("frame {} already has a previous frame: break that link first", second.0)));
|
||||
}
|
||||
if locked(&a) || locked(&b) {
|
||||
return Err(bad(C, "a frame of either story is hidden or locked"));
|
||||
}
|
||||
let joined: Vec<NodeId> = a.iter().chain(&b).copied().collect();
|
||||
let affected: Ids = joined.iter().copied().collect();
|
||||
s.edit("Thread Text", |d, _| {
|
||||
d.text_threads.retain(|t| !t.iter().any(|f| affected.contains(f)));
|
||||
d.text_threads.push(joined.clone());
|
||||
// Force a re-flow of the joined story on this edit.
|
||||
touch(d, first);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"changed": true, "threads": chain_ids(&[&joined])}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -961,11 +961,19 @@ fn front_docs(s: &Session) -> impl Iterator<Item = &DocState> {
|
||||
s.front_order().into_iter().map(|i| &s.documents()[i])
|
||||
}
|
||||
|
||||
/// `documents[i]`, and `documents["name"]` as `getByName` reads it.
|
||||
/// `documents[i]`, and `documents["name"]` as `getByName` reads it. A key that is the text of a
|
||||
/// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is
|
||||
/// looked up as that name, giving `undefined` when no document has it.
|
||||
fn docs_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let s = h.session.borrow();
|
||||
let at = match arg(a, 1) {
|
||||
Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()).and_then(|i| front_docs(&s).nth(i)),
|
||||
Data::Number(n) => match position(*n) {
|
||||
Some(i) => front_docs(&s).nth(i),
|
||||
None => {
|
||||
let name = vectorcraft_js::number_to_string(*n);
|
||||
front_docs(&s).find(|d| d.title() == name)
|
||||
}
|
||||
},
|
||||
Data::String(name) => match front_docs(&s).find(|d| d.title() == *name) {
|
||||
None if !probing(a) => return Err(HostError::Error(NOT_FOUND.into())),
|
||||
found => found,
|
||||
@@ -985,10 +993,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())),
|
||||
}
|
||||
}
|
||||
@@ -1830,27 +1839,49 @@ fn probing(a: &[Data]) -> bool {
|
||||
matches!(arg(a, 2), Data::Bool(true))
|
||||
}
|
||||
|
||||
/// `pageItems[i]`, and `pageItems["name"]` as `getByName` reads it.
|
||||
/// The position an indexer key names when it is an array index, 0 to 2^32 - 2.
|
||||
fn position(n: f64) -> Option<usize> {
|
||||
whole(n).filter(|i| *i < u64::from(u32::MAX)).and_then(|i| usize::try_from(i).ok())
|
||||
}
|
||||
|
||||
/// `pageItems[i]`, and `pageItems["name"]` as `getByName` reads it. A key that is the text of a
|
||||
/// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is
|
||||
/// looked up as that name, giving `undefined` when no object has it.
|
||||
fn items_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
if let Data::String(_) = arg(a, 1) {
|
||||
return match items_by_name(h, a) {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => match items_by_name(h, a) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined),
|
||||
r => r,
|
||||
};
|
||||
},
|
||||
Data::Number(n) => match position(*n) {
|
||||
Some(i) => Ok(item_at(h, doc, i)),
|
||||
None => match items_named(h, doc, &vectorcraft_js::number_to_string(*n)) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined),
|
||||
r => r,
|
||||
},
|
||||
},
|
||||
_ => Ok(Data::Undefined),
|
||||
}
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) };
|
||||
Ok(with_doc(h, doc, |_, st| page_items(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
|
||||
}
|
||||
|
||||
/// The object at position `i` of `pageItems`, or `undefined` past the end.
|
||||
fn item_at(h: &Host, doc: Doc, i: usize) -> Data {
|
||||
with_doc(h, doc, |_, st| page_items(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))
|
||||
}
|
||||
|
||||
fn items_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
items_named(h, doc, name)
|
||||
}
|
||||
|
||||
/// The first object of `pageItems` named `name`, or `Not found`.
|
||||
fn items_named(h: &Host, doc: Doc, name: &str) -> Answer {
|
||||
with_doc(h, doc, |_, st| {
|
||||
let ids = page_items(h, st);
|
||||
h.charge_call(ids.len() as u64)?;
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name));
|
||||
id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
})
|
||||
}
|
||||
@@ -1858,10 +1889,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())),
|
||||
}
|
||||
}
|
||||
@@ -2716,6 +2750,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
),
|
||||
("pageItems", get(l, doc_page_items), MemberInfo { collection: true, ..typed("PageItems") }),
|
||||
("textFrames", text::doc_text_frames(l), MemberInfo { collection: true, ..typed("TextFrames") }),
|
||||
("stories", text::threads::doc_stories(l), MemberInfo { collection: true, ..typed("Stories") }),
|
||||
("selection", property(l, doc_selection, doc_set_selection), typed("*")),
|
||||
("views", get(l, doc_views), MemberInfo { collection: true, ..typed("Views") }),
|
||||
("toString", method(l, doc_to_string), returns("string", &[])),
|
||||
|
||||
@@ -51,6 +51,7 @@ use super::{
|
||||
use crate::{DocState, Document, NodeId, NodeKind};
|
||||
|
||||
pub(super) mod styles;
|
||||
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.
|
||||
@@ -196,6 +197,7 @@ pub(in crate::script) struct TextState {
|
||||
/// The fonts `app.textFonts` lists, as family and style, read once a run; a font a character
|
||||
/// names that is not installed is added at the end.
|
||||
fonts: RefCell<Option<Vec<(String, String)>>>,
|
||||
stories: threads::StoryState,
|
||||
/// The number of text range objects made, which numbers the next one.
|
||||
made: Cell<u64>,
|
||||
/// The span of each range object, by its number, whose `length` the script set.
|
||||
@@ -613,7 +615,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)
|
||||
}
|
||||
|
||||
@@ -1326,28 +1331,36 @@ 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, or one on a
|
||||
/// locked artboard, stops it first.
|
||||
/// 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, on_locked) = with_doc(h, doc, |_, st| {
|
||||
@@ -1536,6 +1549,23 @@ fn read_only(link: &Link, g: super::Member, class: &'static str, name: &'static
|
||||
}
|
||||
}
|
||||
|
||||
/// The type `reflect` gives for character attribute `attr`.
|
||||
fn attr_type(attr: Attr) -> &'static str {
|
||||
match attr {
|
||||
Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean",
|
||||
Attr::TextFont => "TextFont",
|
||||
_ => "number",
|
||||
}
|
||||
}
|
||||
|
||||
/// The type `reflect` gives for paragraph attribute `attr`.
|
||||
fn para_type(attr: ParaAttr) -> &'static str {
|
||||
match attr {
|
||||
ParaAttr::Justification => "Justification",
|
||||
_ => "number",
|
||||
}
|
||||
}
|
||||
|
||||
fn attr_members(link: &Link) -> Vec<Described> {
|
||||
let mut out = Vec::new();
|
||||
for (name, attr) in ATTRS {
|
||||
@@ -1551,12 +1581,7 @@ fn attr_members(link: &Link) -> Vec<Described> {
|
||||
h.charge_call(16 + a.iter().map(super::data_size).sum::<u64>())?;
|
||||
write_attr(&h, &a, attr, name)
|
||||
});
|
||||
let data_type = match attr {
|
||||
Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean",
|
||||
Attr::TextFont => "TextFont",
|
||||
_ => "number",
|
||||
};
|
||||
out.push((name.to_string(), HostMember::Property { get: g, set: s }, typed(data_type)));
|
||||
out.push((name.to_string(), HostMember::Property { get: g, set: s }, typed(attr_type(attr))));
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -1576,8 +1601,7 @@ fn para_members(link: &Link) -> Vec<Described> {
|
||||
h.charge_call(16 + a.iter().map(super::data_size).sum::<u64>())?;
|
||||
write_para(&h, &a, attr, name)
|
||||
});
|
||||
let data_type = if matches!(attr, ParaAttr::Justification) { "Justification" } else { "number" };
|
||||
out.push((name.to_string(), HostMember::Property { get: g, set: s }, typed(data_type)));
|
||||
out.push((name.to_string(), HostMember::Property { get: g, set: s }, typed(para_type(attr))));
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -1603,27 +1627,26 @@ pub(super) fn install_enums(realm: &mut Realm) -> std::result::Result<(), RunErr
|
||||
|
||||
/// The classes of type, `TextFrame` among them, which inherits from `PageItem`.
|
||||
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
let collection = |t: &str| MemberInfo { collection: true, ..typed(t) };
|
||||
let mut frame = named(vec![
|
||||
("kind", get(l, frame_kind), typed("TextType")),
|
||||
("contents", property(l, frame_contents, frame_set_contents), typed("string")),
|
||||
("textRange", get(l, frame_range), typed("TextRange")),
|
||||
("characters", get(l, characters), MemberInfo { collection: true, ..typed("Characters") }),
|
||||
("words", get(l, words), MemberInfo { collection: true, ..typed("Words") }),
|
||||
("paragraphs", get(l, paragraphs), MemberInfo { collection: true, ..typed("Paragraphs") }),
|
||||
("characters", get(l, characters), collection("Characters")),
|
||||
("words", get(l, words), collection("Words")),
|
||||
("paragraphs", get(l, paragraphs), collection("Paragraphs")),
|
||||
("orientation", read_only(l, frame_orientation, "TextFrame", "orientation"), typed("TextOrientation")),
|
||||
("createOutline", method(l, frame_outline), returns("GroupItem", &[])),
|
||||
("convertAreaObjectToPointObject", method(l, frame_to_point), returns("TextFrame", &[])),
|
||||
("convertPointObjectToAreaObject", method(l, frame_to_area), returns("TextFrame", &[])),
|
||||
]);
|
||||
frame.extend(super::variables::item_members(l, "TextFrame"));
|
||||
frame.extend(threads::frame_members(l));
|
||||
frame.extend(
|
||||
[
|
||||
"lines",
|
||||
"insertionPoints",
|
||||
"textRanges",
|
||||
"story",
|
||||
"nextFrame",
|
||||
"previousFrame",
|
||||
"textPath",
|
||||
"anchor",
|
||||
"antialias",
|
||||
@@ -1648,9 +1671,9 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("end", read_only(l, range_end, "TextRange", "end"), typed("number")),
|
||||
("characterOffset", read_only(l, range_start, "TextRange", "characterOffset"), typed("number")),
|
||||
("length", property(l, range_length, range_set_length), typed("number")),
|
||||
("characters", get(l, characters), MemberInfo { collection: true, ..typed("Characters") }),
|
||||
("words", get(l, words), MemberInfo { collection: true, ..typed("Words") }),
|
||||
("paragraphs", get(l, paragraphs), MemberInfo { collection: true, ..typed("Paragraphs") }),
|
||||
("characters", get(l, characters), collection("Characters")),
|
||||
("words", get(l, words), collection("Words")),
|
||||
("paragraphs", get(l, paragraphs), collection("Paragraphs")),
|
||||
("characterAttributes", get(l, character_attributes), typed("CharacterAttributes")),
|
||||
("paragraphAttributes", get(l, paragraph_attributes), typed("ParagraphAttributes")),
|
||||
("getParagraphLength", method(l, range_paragraph_length), returns("number", &[("charIndex", "number")])),
|
||||
@@ -1658,6 +1681,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("remove", method(l, range_remove), returns("undefined", &[])),
|
||||
]);
|
||||
range.extend(attr_members(l));
|
||||
range.push(threads::range_member(l));
|
||||
range.extend(para_members(l));
|
||||
range.extend(styles::range_members(l));
|
||||
range.extend(
|
||||
@@ -1665,7 +1689,6 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
"lines",
|
||||
"insertionPoints",
|
||||
"textRanges",
|
||||
"story",
|
||||
"kerning",
|
||||
"textSelection",
|
||||
"changeCaseTo",
|
||||
@@ -1686,8 +1709,8 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
named(vec![
|
||||
("typename", get(l, part_typename), typed("string")),
|
||||
("length", get(l, part_length), typed("number")),
|
||||
("parent", get(l, part_parent), typed("*")),
|
||||
("add", method(l, part_add_after), returns("TextRange", &[("contents", "string")])),
|
||||
("parent", get(l, part_parent), typed("TextRange")),
|
||||
("add", method(l, part_add_after), returns("TextRange", &[("contents", "string"), ("relativeObject", "TextRange")])),
|
||||
("addBefore", method(l, part_add_before), returns("TextRange", &[("contents", "string")])),
|
||||
]),
|
||||
Some(function(l, part_at)),
|
||||
@@ -1697,6 +1720,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
chars.extend(attr_members(l));
|
||||
let mut paras = named(vec![("typename", get(l, para_attrs_typename), typed("string"))]);
|
||||
paras.extend(para_members(l));
|
||||
let stories = threads::classes(l);
|
||||
let mut out = vec![
|
||||
class("TextFrame", Some("PageItem"), frame, None),
|
||||
class("TextRange", None, range, None),
|
||||
@@ -1712,12 +1736,29 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("typename", get(l, frames_typename), typed("string")),
|
||||
("length", get(l, frames_length), typed("number")),
|
||||
("parent", get(l, frames_parent), typed("Document")),
|
||||
("index", method(l, frames_index), returns("number", &[("itemKey", "TextFrame")])),
|
||||
("index", method(l, frames_index), returns("number", &[("itemKey", "*")])),
|
||||
("getByName", method(l, frames_by_name), returns("TextFrame", &[("name", "string")])),
|
||||
("add", method(l, frames_add), returns("TextFrame", &[])),
|
||||
("pointText", method(l, frames_point_text), returns("TextFrame", &[("anchor", "Array"), ("orientation", "TextOrientation")])),
|
||||
("areaText", method(l, frames_area_text), returns("TextFrame", &[("textPath", "PathItem"), ("orientation", "TextOrientation")])),
|
||||
("pathText", method(l, frames_path_text), returns("TextFrame", &[("textPath", "PathItem"), ("startTValue", "number")])),
|
||||
(
|
||||
"areaText",
|
||||
method(l, frames_area_text),
|
||||
returns("TextFrame", &[("textPath", "PathItem"), ("orientation", "TextOrientation"), ("baseFrame", "TextFrame")]),
|
||||
),
|
||||
(
|
||||
"pathText",
|
||||
method(l, frames_path_text),
|
||||
returns(
|
||||
"TextFrame",
|
||||
&[
|
||||
("textPath", "PathItem"),
|
||||
("startTValue", "number"),
|
||||
("endTValue", "number"),
|
||||
("orientation", "TextOrientation"),
|
||||
("baseFrame", "TextFrame"),
|
||||
],
|
||||
),
|
||||
),
|
||||
("removeAll", method(l, frames_remove_all), returns("undefined", &[])),
|
||||
]),
|
||||
Some(function(l, frames_at)),
|
||||
@@ -1729,7 +1770,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("typename", typename_of("TextFonts"), typed("string")),
|
||||
("length", get(l, fonts_length), typed("number")),
|
||||
("parent", get(l, app_ref), typed("Application")),
|
||||
("index", method(l, fonts_index), returns("number", &[("itemKey", "TextFont")])),
|
||||
("index", method(l, fonts_index), returns("number", &[("itemKey", "*")])),
|
||||
("getByName", method(l, fonts_by_name), returns("TextFont", &[("name", "string")])),
|
||||
]),
|
||||
Some(function(l, fonts_at)),
|
||||
@@ -1748,6 +1789,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
),
|
||||
];
|
||||
out.extend(styles::classes(l));
|
||||
out.extend(stories);
|
||||
out
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,829 @@
|
||||
//! Threaded type in the script object model: a text frame's `nextFrame`, `previousFrame` and
|
||||
//! `story`, `document.stories`, and each `Story` with its frames and its text, as the help pages
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Story/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Stories/> describe them.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state:
|
||||
//! - Assigning `nextFrame` links the last frame of a story to the first frame of another story,
|
||||
//! whose text then flows on after it; `previousFrame` links the other way. Assigning `null`
|
||||
//! breaks that link, and no text moves across it. Point type, a frame of another
|
||||
//! document, the frame itself, a frame inside a story, a link that would make a loop and a hidden
|
||||
//! or locked frame in either story are refused with nothing changed. Assigning the frame that is
|
||||
//! already linked, or `null` where there is no link, changes nothing.
|
||||
//! - A `Story` is the story of the frame it was read from as that frame is threaded now; when the
|
||||
//! frame is deleted, it throws `Stale story`.
|
||||
//! - `document.stories` lists one story for each type object in no thread and one for each thread,
|
||||
//! in the order of their first frames in `document.textFrames`, topmost first. `index` with a string finds the first story whose
|
||||
//! first frame has that name.
|
||||
//! - The text of a story of two or more frames is its frames' text in thread order. Its ranges keep
|
||||
//! their place through edits made through them, as a frame's ranges do, and are stale after any
|
||||
//! other change to the story's text and after File › Revert. A story of one frame gives that
|
||||
//! frame's own ranges.
|
||||
//! - `areaText` and `pathText` with a `baseFrame` thread the new frame after it, or before it when
|
||||
//! `postFix` is false; `postFix` is true when it is left out.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::rc::Rc;
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::TextKind;
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember, MemberInfo, host_ref};
|
||||
|
||||
use super::super::{
|
||||
Answer, Described, Doc, Host, Item, Link, NOT_FOUND, arg, boolean, class, current, doc_of, doc_ref, edit_item, find_doc, float, function, get,
|
||||
handle_of, id_of, id_parts, in_compound, item_of, item_ref, method, named, num, property, returns, text, typed, whole, with_doc,
|
||||
};
|
||||
use super::{
|
||||
ATTRS, Index, Log, Part, STALE_RANGE, frame_ids, from_script, part_spans, range_ref, read_only, text_of, this_frame, to_script, touched,
|
||||
usize_of, whole_span,
|
||||
};
|
||||
use crate::cmd::threads::story_of;
|
||||
use crate::{DocState, Document, NodeId};
|
||||
|
||||
/// The error of a `Story` whose frame was deleted, or that came from an earlier run.
|
||||
pub const STALE_STORY: &str = "Stale story";
|
||||
|
||||
/// A document's uid, the document, and the first frame of each of its stories then.
|
||||
type StoryList = (u64, Weak<Document>, Rc<Vec<NodeId>>);
|
||||
|
||||
/// The story state of one run: the text of each story of two or more frames that a range was made
|
||||
/// of, by document and the frame the `Story` was read from, and the last list of stories.
|
||||
#[derive(Default)]
|
||||
pub(in crate::script) struct StoryState {
|
||||
logs: RefCell<HashMap<(u64, u64), Log>>,
|
||||
list: RefCell<Option<StoryList>>,
|
||||
}
|
||||
|
||||
/// The frames of the story `id` is a frame of, in thread order, each once, or `id` alone.
|
||||
fn frames_of(st: &DocState, id: NodeId) -> Vec<NodeId> {
|
||||
let mut frames = story_of(&st.doc, id);
|
||||
let mut seen = HashSet::new();
|
||||
frames.retain(|f| seen.insert(*f));
|
||||
if frames.len() < 2 { vec![id] } else { frames }
|
||||
}
|
||||
|
||||
/// The frames of the story `id` is a frame of, charged to the run.
|
||||
fn charged_frames(h: &Host, st: &DocState, id: NodeId) -> std::result::Result<Vec<NodeId>, HostError> {
|
||||
h.charge_call(st.doc.text_threads.len() as u64)?;
|
||||
let frames = frames_of(st, id);
|
||||
h.charge_call(frames.len() as u64)?;
|
||||
Ok(frames)
|
||||
}
|
||||
|
||||
/// Whether type object `id` is area type or type on a path.
|
||||
fn threadable(st: &DocState, id: NodeId) -> bool {
|
||||
text_of(st, id).is_some_and(|t| !matches!(t.kind, TextKind::Point))
|
||||
}
|
||||
|
||||
// ---- nextFrame and previousFrame ----
|
||||
|
||||
fn neighbor(h: &Host, a: &[Data], next: bool) -> Answer {
|
||||
let item = this_frame(h, a)?;
|
||||
with_doc(h, item.doc, |_, st| {
|
||||
let frames = charged_frames(h, st, item.id)?;
|
||||
let i = frames.iter().position(|f| *f == item.id);
|
||||
let other = i.and_then(|i| if next { frames.get(i + 1) } else { i.checked_sub(1).and_then(|i| frames.get(i)) });
|
||||
Ok(other.map_or(Data::Null, |f| item_ref(h, st, *f)))
|
||||
})
|
||||
}
|
||||
|
||||
fn next_frame(h: &Host, a: &[Data]) -> Answer {
|
||||
neighbor(h, a, true)
|
||||
}
|
||||
|
||||
fn previous_frame(h: &Host, a: &[Data]) -> Answer {
|
||||
neighbor(h, a, false)
|
||||
}
|
||||
|
||||
/// Assigns `nextFrame` (`next`) or `previousFrame` with `text.thread.setNeighbor`.
|
||||
fn set_neighbor(h: &Host, a: &[Data], next: bool) -> Answer {
|
||||
let name = if next { "nextFrame" } else { "previousFrame" };
|
||||
let item = this_frame(h, a)?;
|
||||
let other = match arg(a, 1) {
|
||||
Data::Null => None,
|
||||
d if handle_of(d, "TextFrame").is_some() => Some(item_of(h, d)?),
|
||||
_ => return Err(HostError::Type(format!("{name} must be a TextFrame or null"))),
|
||||
};
|
||||
if other.is_some_and(|o| o.doc.uid != item.doc.uid) {
|
||||
return Err(HostError::Error(format!("{name}: the two frames are in different documents")));
|
||||
}
|
||||
let now = with_doc(h, item.doc, |_, st| {
|
||||
if !threadable(st, item.id) || other.is_some_and(|o| !threadable(st, o.id)) {
|
||||
return Err(HostError::Error(format!("{name}: only area type and type on a path can be threaded")));
|
||||
}
|
||||
let frames = charged_frames(h, st, item.id)?;
|
||||
let i = frames.iter().position(|f| *f == item.id);
|
||||
let current = i.and_then(|i| if next { frames.get(i + 1) } else { i.checked_sub(1).and_then(|i| frames.get(i)) });
|
||||
Ok(current.copied())
|
||||
})?;
|
||||
if now == other.map(|o| o.id) {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
let side = if next { "next" } else { "previous" };
|
||||
let params = json!({"id": item.id.0, "side": side, "neighbor": other.map(|o| o.id.0)});
|
||||
edit_item(h, item, "text.thread.setNeighbor", ¶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<Option<(Item, bool)>, HostError> {
|
||||
if matches!(base, Data::Undefined | Data::Null) {
|
||||
return Ok(None);
|
||||
}
|
||||
if handle_of(base, "TextFrame").is_none() {
|
||||
return Err(HostError::Type("baseFrame must be a TextFrame".into()));
|
||||
}
|
||||
let item = item_of(h, base)?;
|
||||
if item.doc.uid != doc.uid {
|
||||
return Err(HostError::Error("baseFrame: the frame is in another document".into()));
|
||||
}
|
||||
let postfix = match post {
|
||||
Data::Undefined => true,
|
||||
d => boolean(d, "postFix")?,
|
||||
};
|
||||
with_doc(h, item.doc, |_, st| {
|
||||
if !threadable(st, item.id) {
|
||||
return Err(HostError::Error("baseFrame: only area type and type on a path can be threaded".into()));
|
||||
}
|
||||
let editable = st.doc.editable();
|
||||
if charged_frames(h, st, item.id)?.iter().any(|f| !editable(*f)) {
|
||||
return Err(HostError::Error("baseFrame: a frame of its story is hidden or locked".into()));
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Some((item, postfix)))
|
||||
}
|
||||
|
||||
/// Refuses a `baseFrame` for a path inside a compound path before the path is turned into type:
|
||||
/// `text.thread.add` does not thread type there.
|
||||
pub(super) fn check_base_path(h: &Host, path: Item) -> std::result::Result<(), HostError> {
|
||||
if in_compound(h, path) {
|
||||
return Err(HostError::Error("baseFrame: type made from a path inside a compound path cannot be threaded".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Threads the new frame `id` after `base`, or before it when `postfix` is false.
|
||||
pub(super) fn thread_new(h: &Host, base: Item, id: NodeId, postfix: bool) -> std::result::Result<(), HostError> {
|
||||
edit_item(h, base, "text.thread.add", &json!({"from": base.id.0, "to": id.0, "before": !postfix}))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---- Story ----
|
||||
|
||||
fn story_ref(h: &Host, item: Item) -> Data {
|
||||
let [high, low] = id_parts(item.id);
|
||||
host_ref("Story", &[float(h.run), float(item.doc.uid), high, low])
|
||||
}
|
||||
|
||||
/// The frame the story `d` was read from, which must still be a type object.
|
||||
fn story_of_data(h: &Host, d: &Data) -> std::result::Result<Item, HostError> {
|
||||
let Some(handle) = handle_of(d, "Story") else { return Err(HostError::Type("this is not a Story".into())) };
|
||||
let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a Story".into())) };
|
||||
let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_STORY.into()))?;
|
||||
let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_STORY.into()))?;
|
||||
match with_doc(h, doc, |_, st| text_of(st, id).is_some()) {
|
||||
true => Ok(Item { doc, id }),
|
||||
false => Err(HostError::Error(STALE_STORY.into())),
|
||||
}
|
||||
}
|
||||
|
||||
fn this_story(h: &Host, a: &[Data]) -> std::result::Result<Item, HostError> {
|
||||
story_of_data(h, arg(a, 0))
|
||||
}
|
||||
|
||||
fn story_frames(h: &Host, a: &[Data]) -> Answer {
|
||||
let story = this_story(h, a)?;
|
||||
with_doc(h, story.doc, |_, st| Ok(Data::Array(charged_frames(h, st, story.id)?.iter().map(|f| item_ref(h, st, *f)).collect())))
|
||||
}
|
||||
|
||||
fn story_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let story = this_story(h, a)?;
|
||||
Ok(doc_ref(h, story.doc.uid))
|
||||
}
|
||||
|
||||
/// The story's one frame, or `None` for a story of two or more frames.
|
||||
fn single(h: &Host, story: Item) -> std::result::Result<Option<Item>, HostError> {
|
||||
with_doc(h, story.doc, |_, st| {
|
||||
let frames = charged_frames(h, st, story.id)?;
|
||||
Ok(match frames[..] {
|
||||
[one] => Some(Item { doc: story.doc, id: one }),
|
||||
_ => None,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn story_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let story = this_story(h, a)?;
|
||||
let (index, _) = with_doc(h, story.doc, |_, st| observe(h, st, story.id))?;
|
||||
Ok(num(float(index.len() as u64)))
|
||||
}
|
||||
|
||||
/// A range or a collection of the whole story, as `frame_class` for a story of one frame and
|
||||
/// `story_class` for a longer one.
|
||||
fn story_whole(h: &Host, a: &[Data], frame_class: &str, story_class: &str) -> Answer {
|
||||
let story = this_story(h, a)?;
|
||||
if let Some(frame) = single(h, story)? {
|
||||
let (_, r) = whole_span(h, frame)?;
|
||||
return Ok(range_ref(h, frame, r.start, r.end, r.stamp, frame_class));
|
||||
}
|
||||
let (index, stamp) = with_doc(h, story.doc, |_, st| observe(h, st, story.id))?;
|
||||
Ok(span_ref(h, story, 0, index.len(), stamp, story_class))
|
||||
}
|
||||
|
||||
fn story_text_range(h: &Host, a: &[Data]) -> Answer {
|
||||
story_whole(h, a, "TextRange", "StoryRange")
|
||||
}
|
||||
|
||||
fn story_characters(h: &Host, a: &[Data]) -> Answer {
|
||||
story_whole(h, a, "Characters", "StoryCharacters")
|
||||
}
|
||||
|
||||
fn story_words(h: &Host, a: &[Data]) -> Answer {
|
||||
story_whole(h, a, "Words", "StoryWords")
|
||||
}
|
||||
|
||||
fn story_paragraphs(h: &Host, a: &[Data]) -> Answer {
|
||||
story_whole(h, a, "Paragraphs", "StoryParagraphs")
|
||||
}
|
||||
|
||||
// ---- the text of a story of two or more frames ----
|
||||
|
||||
/// The frames of the story and the text of each, in thread order.
|
||||
fn story_text(st: &DocState, frames: &[NodeId]) -> String {
|
||||
frames.iter().filter_map(|f| text_of(st, *f)).flat_map(|t| t.runs.iter().map(|r| r.text.as_str())).collect()
|
||||
}
|
||||
|
||||
/// The story's index and its generation now, read again when its document changed. The stories
|
||||
/// read from the frames of one story share one index of its text while the document is unchanged.
|
||||
fn observe(h: &Host, st: &DocState, anchor: NodeId) -> std::result::Result<(Rc<Index>, u64), HostError> {
|
||||
if text_of(st, anchor).is_none() {
|
||||
return Err(HostError::Error(STALE_STORY.into()));
|
||||
}
|
||||
let mut logs = h.dom.text.stories.logs.borrow_mut();
|
||||
let key = (st.uid, anchor.0);
|
||||
let now = Arc::as_ptr(&st.doc);
|
||||
let current = |l: &Log| std::ptr::eq(l.doc.as_ptr(), now) && l.reverts == st.reverts;
|
||||
if !logs.get(&key).is_some_and(current) {
|
||||
let frames = charged_frames(h, st, anchor)?;
|
||||
// Another frame of the same story read at this state of the document has the same text;
|
||||
// a frame listed in two threads can belong to another story, so its frames must match.
|
||||
let mut shared = None;
|
||||
if frames.len() > 1 {
|
||||
h.charge_call(frames.len() as u64)?;
|
||||
if let Some((f, l)) =
|
||||
frames.iter().filter(|f| **f != anchor).find_map(|f| logs.get(&(st.uid, f.0)).filter(|l| current(l)).map(|l| (*f, l)))
|
||||
&& charged_frames(h, st, f)? == frames
|
||||
{
|
||||
shared = Some(l.index.clone());
|
||||
}
|
||||
}
|
||||
let index = match shared {
|
||||
Some(index) => index,
|
||||
None => {
|
||||
let text = story_text(st, &frames);
|
||||
// Joining the frames' text costs its length, as rebuilding the index does elsewhere.
|
||||
h.charge_call(text.len() as u64)?;
|
||||
match logs.get(&key) {
|
||||
Some(l) if l.reverts == st.reverts && l.index.text == text => l.index.clone(),
|
||||
_ => Rc::new(Index::new(text)),
|
||||
}
|
||||
}
|
||||
};
|
||||
match logs.get_mut(&key) {
|
||||
Some(l) => {
|
||||
if l.reverts != st.reverts || index.text != l.index.text {
|
||||
l.stamp += 1;
|
||||
l.floor = l.stamp;
|
||||
l.edits.clear();
|
||||
}
|
||||
l.index = index;
|
||||
l.doc = Arc::downgrade(&st.doc);
|
||||
l.reverts = st.reverts;
|
||||
}
|
||||
None => {
|
||||
logs.insert(key, Log { doc: Arc::downgrade(&st.doc), reverts: st.reverts, index, stamp: 0, floor: 0, edits: VecDeque::new() });
|
||||
}
|
||||
}
|
||||
}
|
||||
let l = logs.get(&key).ok_or_else(|| HostError::Error(STALE_STORY.into()))?;
|
||||
Ok((l.index.clone(), l.stamp))
|
||||
}
|
||||
|
||||
/// A range of a story: the frame the story was read from, its span in UTF-16 units and the
|
||||
/// generation it was made at.
|
||||
#[derive(Clone, Copy)]
|
||||
struct StorySpan {
|
||||
story: Item,
|
||||
start: usize,
|
||||
end: usize,
|
||||
stamp: u64,
|
||||
}
|
||||
|
||||
const STORY_PARTS: [(&str, Part); 3] = [("StoryCharacters", Part::Characters), ("StoryWords", Part::Words), ("StoryParagraphs", Part::Paragraphs)];
|
||||
|
||||
fn span_ref(h: &Host, story: Item, s: usize, e: usize, stamp: u64, class: &str) -> Data {
|
||||
let [high, low] = id_parts(story.id);
|
||||
host_ref(class, &[float(h.run), float(story.doc.uid), high, low, float(s as u64), float(e as u64), float(stamp)])
|
||||
}
|
||||
|
||||
/// The story span `d` names, when it is an object of one of `classes`.
|
||||
fn span_of(h: &Host, d: &Data, classes: &[&str]) -> std::result::Result<StorySpan, HostError> {
|
||||
let handle = classes.iter().find_map(|c| handle_of(d, c));
|
||||
let Some(&[run, uid, high, low, s, e, stamp]) = handle.as_deref() else {
|
||||
return Err(HostError::Type(format!("this is not a {}", classes.first().copied().unwrap_or("TextRange"))));
|
||||
};
|
||||
let story = story_of_data(h, &host_ref("Story", &[run, uid, high, low])).map_err(|_| HostError::Error(STALE_RANGE.into()))?;
|
||||
let (Some(start), Some(end), Some(stamp)) = (usize_of(s), usize_of(e), whole(stamp)) else { return Err(HostError::Error(STALE_RANGE.into())) };
|
||||
Ok(StorySpan { story, start, end, stamp })
|
||||
}
|
||||
|
||||
fn this_span(h: &Host, a: &[Data]) -> std::result::Result<StorySpan, HostError> {
|
||||
span_of(h, arg(a, 0), &["StoryRange"])
|
||||
}
|
||||
|
||||
/// The span and index of `r` now.
|
||||
fn resolve(h: &Host, r: StorySpan) -> std::result::Result<(Rc<Index>, usize, usize, u64), HostError> {
|
||||
with_doc(h, r.story.doc, |_, st| {
|
||||
let (index, stamp) = observe(h, st, r.story.id)?;
|
||||
let logs = h.dom.text.stories.logs.borrow();
|
||||
let l = logs.get(&(st.uid, r.story.id.0)).ok_or_else(|| HostError::Error(STALE_RANGE.into()))?;
|
||||
if r.stamp < l.floor || r.stamp > l.stamp {
|
||||
return Err(HostError::Error(STALE_RANGE.into()));
|
||||
}
|
||||
let (mut s, mut e) = (r.start, r.end);
|
||||
let from = l.edits.partition_point(|x| x.stamp <= r.stamp);
|
||||
for x in l.edits.range(from..) {
|
||||
let moved = |v: usize| v - x.removed + x.inserted;
|
||||
s = if s <= x.at {
|
||||
s
|
||||
} else if s >= x.at + x.removed {
|
||||
moved(s)
|
||||
} else {
|
||||
x.at
|
||||
};
|
||||
// An end inside the removed text goes to the end of the new text.
|
||||
e = if e < x.at || (e == x.at && x.removed > 0) {
|
||||
e
|
||||
} else if e >= x.at + x.removed {
|
||||
moved(e)
|
||||
} else {
|
||||
x.at + x.inserted
|
||||
};
|
||||
}
|
||||
let e = e.min(index.len());
|
||||
Ok((index, s.min(e), e, stamp))
|
||||
})
|
||||
}
|
||||
|
||||
/// Records an edit the model made to the story: `removed` units at `at` replaced by `inserted`.
|
||||
/// When the text is not what that edit gives, every earlier range goes stale. The ranges of the
|
||||
/// same story read from its other frames record the edit too, when they knew the text before it.
|
||||
fn record(h: &Host, story: Item, before: &Index, at: usize, removed: usize, inserted: &str) -> std::result::Result<(), HostError> {
|
||||
with_doc(h, story.doc, |_, st| {
|
||||
if text_of(st, story.id).is_none() {
|
||||
return Err(HostError::Error(STALE_STORY.into()));
|
||||
}
|
||||
let frames = charged_frames(h, st, story.id)?;
|
||||
let now = story_text(st, &frames);
|
||||
let (a, b) = (before.byte(at, false), before.byte(at + removed, true));
|
||||
let expected = before.text.len() - (b - a) + inserted.len() == now.len()
|
||||
&& now.as_bytes().starts_with(&before.text.as_bytes()[..a])
|
||||
&& now.as_bytes().ends_with(&before.text.as_bytes()[b..])
|
||||
&& now.get(a..a + inserted.len()) == Some(inserted);
|
||||
let members: HashSet<u64> = frames.iter().map(|f| f.0).collect();
|
||||
let index = Rc::new(Index::new(now));
|
||||
let inserted = inserted.encode_utf16().count();
|
||||
let mut logs = h.dom.text.stories.logs.borrow_mut();
|
||||
let mut found = false;
|
||||
for (&(uid, anchor), l) in logs.iter_mut() {
|
||||
if uid != st.uid || !members.contains(&anchor) {
|
||||
continue;
|
||||
}
|
||||
let own = anchor == story.id.0;
|
||||
let current = l.reverts == st.reverts;
|
||||
if !own {
|
||||
h.charge_call(l.index.text.len() as u64)?;
|
||||
if !expected || !current || l.index.text != before.text {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
found |= own;
|
||||
if expected && current {
|
||||
l.push(at, removed, inserted);
|
||||
} else {
|
||||
l.stamp += 1;
|
||||
l.floor = l.stamp;
|
||||
l.edits.clear();
|
||||
}
|
||||
l.index = index.clone();
|
||||
l.doc = Arc::downgrade(&st.doc);
|
||||
l.reverts = st.reverts;
|
||||
}
|
||||
if found { Ok(()) } else { Err(HostError::Error(STALE_RANGE.into())) }
|
||||
})
|
||||
}
|
||||
|
||||
/// Replaces bytes `a..b` of the story's text with `insert`, a frame at a time from the end, with
|
||||
/// `text.editRange`: the frames before the one an edit changes keep their text, so `a` stays in
|
||||
/// place while the frames after it flow again.
|
||||
fn replace(h: &Host, story: Item, a: usize, mut b: usize, insert: &str) -> std::result::Result<(), HostError> {
|
||||
loop {
|
||||
let spans: Vec<(NodeId, usize, usize)> = with_doc(h, story.doc, |_, st| {
|
||||
if text_of(st, story.id).is_none() {
|
||||
return Err(HostError::Error(STALE_STORY.into()));
|
||||
}
|
||||
let mut at = 0;
|
||||
let spans = charged_frames(h, st, story.id)?
|
||||
.into_iter()
|
||||
.map(|f| {
|
||||
let n: usize = text_of(st, f).map_or(0, |t| t.runs.iter().map(|r| r.text.len()).sum());
|
||||
at += n;
|
||||
(f, at - n, at)
|
||||
})
|
||||
.collect();
|
||||
Ok(spans)
|
||||
})?;
|
||||
let target =
|
||||
if b > a { spans.iter().find(|(_, x, y)| *x < b && b <= *y) } else { spans.iter().find(|(_, x, y)| *x < a && a <= *y).or(spans.first()) };
|
||||
let Some(&(f, x, _)) = target else { return Err(HostError::Error(STALE_RANGE.into())) };
|
||||
let item = Item { doc: story.doc, id: f };
|
||||
if x <= a {
|
||||
edit_item(h, item, "text.editRange", &json!({"id": f.0, "start": a - x, "end": b - x, "insert": insert}))?;
|
||||
return Ok(());
|
||||
}
|
||||
edit_item(h, item, "text.editRange", &json!({"id": f.0, "start": 0, "end": b - x, "insert": ""}))?;
|
||||
b = x;
|
||||
}
|
||||
}
|
||||
|
||||
fn write_contents(h: &Host, r: StorySpan, value: &Data) -> Answer {
|
||||
let Data::String(v) = value else { return Err(HostError::Type("contents must be a string".into())) };
|
||||
let insert = from_script(v);
|
||||
let (index, s, e, _) = resolve(h, r)?;
|
||||
let (a, b) = (index.byte(s, false), index.byte(e, true));
|
||||
if index.text[a..b] == insert {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
let (s, e) = (index.text[..a].encode_utf16().count(), index.text[..b].encode_utf16().count());
|
||||
replace(h, r.story, a, b, &insert)?;
|
||||
record(h, r.story, &index, s, e - s, &insert)?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn span_contents(h: &Host, a: &[Data]) -> Answer {
|
||||
let (index, s, e, _) = resolve(h, this_span(h, a)?)?;
|
||||
let (x, y) = (index.byte(s, false), index.byte(e, true));
|
||||
Ok(text(to_script(&index.text[x..y])))
|
||||
}
|
||||
|
||||
fn span_set_contents(h: &Host, a: &[Data]) -> Answer {
|
||||
write_contents(h, this_span(h, a)?, arg(a, 1))
|
||||
}
|
||||
|
||||
fn span_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
write_contents(h, this_span(h, a)?, &text(""))
|
||||
}
|
||||
|
||||
fn span_start(h: &Host, a: &[Data]) -> Answer {
|
||||
let (_, s, _, _) = resolve(h, this_span(h, a)?)?;
|
||||
Ok(num(float(s as u64)))
|
||||
}
|
||||
|
||||
fn span_end(h: &Host, a: &[Data]) -> Answer {
|
||||
let (_, _, e, _) = resolve(h, this_span(h, a)?)?;
|
||||
Ok(num(float(e as u64)))
|
||||
}
|
||||
|
||||
fn span_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let (_, s, e, _) = resolve(h, this_span(h, a)?)?;
|
||||
Ok(num(float((e - s) as u64)))
|
||||
}
|
||||
|
||||
fn span_story(h: &Host, a: &[Data]) -> Answer {
|
||||
let r = this_span(h, a)?;
|
||||
resolve(h, r)?;
|
||||
Ok(story_ref(h, r.story))
|
||||
}
|
||||
|
||||
fn span_paragraph_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let (index, s, e, _) = resolve(h, this_span(h, a)?)?;
|
||||
let p = touched(&index.paras, s, e).next().and_then(|i| index.paras.get(i)).map_or(0, |(x, y)| y - x);
|
||||
Ok(num(float(p as u64)))
|
||||
}
|
||||
|
||||
fn span_part(h: &Host, a: &[Data], class: &str) -> Answer {
|
||||
let r = this_span(h, a)?;
|
||||
let (_, s, e, stamp) = resolve(h, r)?;
|
||||
Ok(span_ref(h, r.story, s, e, stamp, class))
|
||||
}
|
||||
|
||||
fn span_characters(h: &Host, a: &[Data]) -> Answer {
|
||||
span_part(h, a, "StoryCharacters")
|
||||
}
|
||||
|
||||
fn span_words(h: &Host, a: &[Data]) -> Answer {
|
||||
span_part(h, a, "StoryWords")
|
||||
}
|
||||
|
||||
fn span_paragraphs(h: &Host, a: &[Data]) -> Answer {
|
||||
span_part(h, a, "StoryParagraphs")
|
||||
}
|
||||
|
||||
fn this_part(h: &Host, a: &[Data]) -> std::result::Result<(StorySpan, Part), HostError> {
|
||||
let part = STORY_PARTS.iter().find(|(c, _)| handle_of(arg(a, 0), c).is_some()).map(|(_, p)| *p);
|
||||
let part = part.ok_or_else(|| HostError::Type("this is not a collection of text".into()))?;
|
||||
Ok((span_of(h, arg(a, 0), &STORY_PARTS.map(|(c, _)| c))?, part))
|
||||
}
|
||||
|
||||
fn part_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
let (r, part) = this_part(h, a)?;
|
||||
resolve(h, r)?;
|
||||
Ok(text(match part {
|
||||
Part::Characters => "Characters",
|
||||
Part::Words => "Words",
|
||||
Part::Paragraphs => "Paragraphs",
|
||||
}))
|
||||
}
|
||||
|
||||
fn span_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
resolve(h, this_span(h, a)?)?;
|
||||
Ok(text("TextRange"))
|
||||
}
|
||||
|
||||
fn story_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
this_story(h, a)?;
|
||||
Ok(text("Story"))
|
||||
}
|
||||
|
||||
fn part_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let (r, part) = this_part(h, a)?;
|
||||
let (index, s, e, _) = resolve(h, r)?;
|
||||
Ok(num(float(part_spans(&index, part, s, e).0.len() as u64)))
|
||||
}
|
||||
|
||||
fn part_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let (r, _) = this_part(h, a)?;
|
||||
let (_, s, e, stamp) = resolve(h, r)?;
|
||||
Ok(span_ref(h, r.story, s, e, stamp, "StoryRange"))
|
||||
}
|
||||
|
||||
fn part_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let (r, part) = this_part(h, a)?;
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) };
|
||||
let (index, s, e, stamp) = resolve(h, r)?;
|
||||
let (items, spans) = part_spans(&index, part, s, e);
|
||||
let Some(k) = items.start.checked_add(i).filter(|k| *k < items.end) else { return Ok(Data::Undefined) };
|
||||
let span = match spans {
|
||||
None => index.char_span(k),
|
||||
Some(list) => list.get(k).copied(),
|
||||
};
|
||||
Ok(span.map_or(Data::Undefined, |(x, y)| span_ref(h, r.story, x, y, stamp, "StoryRange")))
|
||||
}
|
||||
|
||||
// ---- Stories ----
|
||||
|
||||
fn doc_stories_impl(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = doc_of(h, arg(a, 0), "Document")?;
|
||||
Ok(host_ref("Stories", &[float(h.run), float(doc.uid)]))
|
||||
}
|
||||
|
||||
/// `document.stories`.
|
||||
pub(in crate::script::dom) fn doc_stories(link: &Link) -> HostMember {
|
||||
get(link, doc_stories_impl)
|
||||
}
|
||||
|
||||
/// The first frame of each story of the document in paint order, kept while the document is
|
||||
/// unchanged.
|
||||
fn heads(h: &Host, st: &DocState) -> std::result::Result<Rc<Vec<NodeId>>, HostError> {
|
||||
if let Some((uid, doc, ids)) = &*h.dom.text.stories.list.borrow()
|
||||
&& *uid == st.uid
|
||||
&& std::ptr::eq(doc.as_ptr(), Arc::as_ptr(&st.doc))
|
||||
{
|
||||
return Ok(ids.clone());
|
||||
}
|
||||
let ids = frame_ids(h, st);
|
||||
h.charge_call(ids.len() as u64 + st.doc.text_threads.iter().map(|t| t.len() as u64).sum::<u64>())?;
|
||||
// A frame listed by an earlier thread belongs to that one, as `story_of` finds it.
|
||||
let (mut threaded, mut first) = (HashSet::new(), HashSet::new());
|
||||
let mut seen = HashSet::new();
|
||||
for thread in &st.doc.text_threads {
|
||||
let live: Vec<NodeId> = thread.iter().copied().filter(|f| threadable(st, *f) && seen.insert(*f)).collect();
|
||||
if live.len() >= 2 {
|
||||
first.insert(live[0]);
|
||||
threaded.extend(live);
|
||||
}
|
||||
}
|
||||
let heads: Vec<NodeId> = ids.iter().copied().filter(|id| !threaded.contains(id) || first.contains(id)).collect();
|
||||
let heads = Rc::new(heads);
|
||||
*h.dom.text.stories.list.borrow_mut() = Some((st.uid, Arc::downgrade(&st.doc), heads.clone()));
|
||||
Ok(heads)
|
||||
}
|
||||
|
||||
fn stories_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
doc_of(h, arg(a, 0), "Stories")
|
||||
}
|
||||
|
||||
fn stories_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = stories_doc(h, a)?;
|
||||
let n = with_doc(h, doc, |_, st| heads(h, st).map(|l| l.len()))?;
|
||||
Ok(num(float(n as u64)))
|
||||
}
|
||||
|
||||
fn stories_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
stories_doc(h, a)?;
|
||||
Ok(text("Stories"))
|
||||
}
|
||||
|
||||
fn stories_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = stories_doc(h, a)?;
|
||||
Ok(doc_ref(h, doc.uid))
|
||||
}
|
||||
|
||||
fn stories_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = stories_doc(h, a)?;
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) };
|
||||
let id = with_doc(h, doc, |_, st| heads(h, st).map(|l| l.get(i).copied()))?;
|
||||
Ok(id.map_or(Data::Undefined, |id| story_ref(h, Item { doc, id })))
|
||||
}
|
||||
|
||||
/// `stories.index(key)`: by number, or by the name of a story's first frame.
|
||||
fn stories_index(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = stories_doc(h, a)?;
|
||||
match arg(a, 1) {
|
||||
Data::Number(_) => match stories_at(h, a)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
},
|
||||
Data::String(name) => {
|
||||
let id = with_doc(h, doc, |_, st| {
|
||||
let list = heads(h, st)?;
|
||||
h.charge_call(list.len() as u64)?;
|
||||
Ok::<_, HostError>(list.iter().copied().find(|i| st.doc.node(*i).and_then(|n| n.name.as_deref()) == Some(name.as_str())))
|
||||
})?;
|
||||
id.map(|id| story_ref(h, Item { doc, id })).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
}
|
||||
_ => Err(HostError::Type("give a name or an index".into())),
|
||||
}
|
||||
}
|
||||
|
||||
// ---- classes ----
|
||||
|
||||
/// A member of the range of a story of two or more frames that is not available yet: reading or
|
||||
/// assigning it throws, after the check that the range is still there, and `reflect` leaves it out.
|
||||
fn range_later(link: &Link, name: &'static str) -> Described {
|
||||
let message = format!("TextRange.{name} is not available yet");
|
||||
let l = link.clone();
|
||||
let f: HostFunction = Rc::new(move |a: Vec<Data>| {
|
||||
let h = current(&l)?;
|
||||
h.charge_call(16)?;
|
||||
resolve(&h, this_span(&h, &a)?)?;
|
||||
Err(HostError::Error(message.clone()))
|
||||
});
|
||||
(name.to_string(), HostMember::Unavailable(f), MemberInfo { unavailable: true, ..MemberInfo::default() })
|
||||
}
|
||||
|
||||
/// A member of `Story` that is not available yet: reading or assigning it throws, after the check
|
||||
/// that the story is still there, and `reflect` leaves it out.
|
||||
fn story_later(link: &Link, name: &'static str) -> Described {
|
||||
let message = format!("Story.{name} is not available yet");
|
||||
let l = link.clone();
|
||||
let f: HostFunction = Rc::new(move |a: Vec<Data>| {
|
||||
let h = current(&l)?;
|
||||
h.charge_call(16)?;
|
||||
this_story(&h, &a)?;
|
||||
Err(HostError::Error(message.clone()))
|
||||
});
|
||||
(name.to_string(), HostMember::Unavailable(f), MemberInfo { unavailable: true, ..MemberInfo::default() })
|
||||
}
|
||||
|
||||
/// The members of `TextFrame` this module adds.
|
||||
pub(super) fn frame_members(l: &Link) -> Vec<Described> {
|
||||
named(vec![
|
||||
("nextFrame", property(l, next_frame, set_next_frame), typed("TextFrame")),
|
||||
("previousFrame", property(l, previous_frame, set_previous_frame), typed("TextFrame")),
|
||||
("story", get(l, frame_story), typed("Story")),
|
||||
])
|
||||
}
|
||||
|
||||
/// `TextRange.story`.
|
||||
pub(super) fn range_member(l: &Link) -> Described {
|
||||
("story".into(), get(l, range_story), typed("Story"))
|
||||
}
|
||||
|
||||
/// `Story`, `Stories` and the range and collections of the text of a story of two or more frames.
|
||||
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
let collection = |t: &str| MemberInfo { collection: true, ..typed(t) };
|
||||
let mut story = named(vec![
|
||||
("typename", get(l, story_typename), typed("string")),
|
||||
("parent", get(l, story_parent), typed("Document")),
|
||||
("length", get(l, story_length), typed("number")),
|
||||
("textFrames", get(l, story_frames), typed("Array")),
|
||||
("textRange", get(l, story_text_range), typed("*")),
|
||||
("characters", get(l, story_characters), collection("*")),
|
||||
("words", get(l, story_words), collection("*")),
|
||||
("paragraphs", get(l, story_paragraphs), collection("*")),
|
||||
]);
|
||||
story.extend(["lines", "insertionPoints", "textRanges", "textSelection"].into_iter().map(|m| story_later(l, m)));
|
||||
let mut range = named(vec![
|
||||
("typename", get(l, span_typename), typed("string")),
|
||||
("parent", get(l, span_story), typed("Story")),
|
||||
("story", get(l, span_story), typed("Story")),
|
||||
("contents", property(l, span_contents, span_set_contents), typed("string")),
|
||||
("start", read_only(l, span_start, "TextRange", "start"), typed("number")),
|
||||
("end", read_only(l, span_end, "TextRange", "end"), typed("number")),
|
||||
("characterOffset", read_only(l, span_start, "TextRange", "characterOffset"), typed("number")),
|
||||
("length", read_only(l, span_length, "TextRange", "length"), typed("number")),
|
||||
("characters", get(l, span_characters), collection("StoryCharacters")),
|
||||
("words", get(l, span_words), collection("StoryWords")),
|
||||
("paragraphs", get(l, span_paragraphs), collection("StoryParagraphs")),
|
||||
("getParagraphLength", method(l, span_paragraph_length), returns("number", &[])),
|
||||
("remove", method(l, span_remove), returns("undefined", &[])),
|
||||
]);
|
||||
range.extend(
|
||||
[
|
||||
"lines",
|
||||
"insertionPoints",
|
||||
"textRanges",
|
||||
"characterAttributes",
|
||||
"paragraphAttributes",
|
||||
"kerning",
|
||||
"characterStyles",
|
||||
"paragraphStyles",
|
||||
"textSelection",
|
||||
"changeCaseTo",
|
||||
"select",
|
||||
"deSelect",
|
||||
"duplicate",
|
||||
"move",
|
||||
"getTextRunLength",
|
||||
"getLocalCharOverridesJSON",
|
||||
"getLocalParaOverridesJSON",
|
||||
]
|
||||
.into_iter()
|
||||
.chain(ATTRS.iter().map(|(n, _)| *n))
|
||||
.map(|m| range_later(l, m)),
|
||||
);
|
||||
let part = |name: &'static str| {
|
||||
class(
|
||||
name,
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, part_typename), typed("string")),
|
||||
("length", get(l, part_length), typed("number")),
|
||||
("parent", get(l, part_parent), typed("StoryRange")),
|
||||
]),
|
||||
Some(function(l, part_at)),
|
||||
)
|
||||
};
|
||||
vec![
|
||||
class("Story", None, story, None),
|
||||
class("StoryRange", None, range, None),
|
||||
part("StoryCharacters"),
|
||||
part("StoryWords"),
|
||||
part("StoryParagraphs"),
|
||||
class(
|
||||
"Stories",
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, stories_typename), typed("string")),
|
||||
("length", get(l, stories_length), typed("number")),
|
||||
("parent", get(l, stories_parent), typed("Document")),
|
||||
("index", method(l, stories_index), returns("number", &[("itemKey", "*")])),
|
||||
]),
|
||||
Some(function(l, stories_at)),
|
||||
),
|
||||
]
|
||||
}
|
||||
@@ -188,6 +188,7 @@ mod script_scriptui;
|
||||
mod script_styles;
|
||||
mod script_tags;
|
||||
mod script_text;
|
||||
mod script_threads;
|
||||
mod script_variables;
|
||||
mod script_xmp;
|
||||
mod scripts;
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -2249,6 +2249,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.
|
||||
|
||||
@@ -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 = [
|
||||
|
||||
@@ -0,0 +1,639 @@
|
||||
//! Threaded type in the script object model: `nextFrame`, `previousFrame`, `story`,
|
||||
//! `document.stories`, and the text of a story of several frames.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn run(s: &mut Session, source: &str) -> Result<Value> {
|
||||
s.execute("script.run", &json!({"source": source, "name": "t.js"}))
|
||||
}
|
||||
|
||||
/// What the run logged.
|
||||
fn log(s: &mut Session, source: &str) -> Vec<Value> {
|
||||
let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}"));
|
||||
r["log"].as_array().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The message of the run's failure.
|
||||
fn failure(s: &mut Session, source: &str) -> String {
|
||||
run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string()
|
||||
}
|
||||
|
||||
fn undo_steps(s: &Session) -> usize {
|
||||
s.active().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn new_doc() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// Area type `width` × `height` at `x` holding `text`.
|
||||
fn area(s: &mut Session, x: f64, width: f64, height: f64, text: &str) -> NodeId {
|
||||
let r = s.execute("text.create", &json!({"x": x, "y": 10, "text": text, "size": 12, "area": {"width": width, "height": height}})).unwrap();
|
||||
NodeId(r["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn plain(s: &Session, id: NodeId) -> String {
|
||||
match &s.active().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Text(t) => t.plain_text(),
|
||||
_ => panic!("not text"),
|
||||
}
|
||||
}
|
||||
|
||||
fn threads(s: &Session) -> Vec<Vec<NodeId>> {
|
||||
s.active().unwrap().doc.text_threads.clone()
|
||||
}
|
||||
|
||||
/// The text of every frame of the document's threads, in thread order.
|
||||
fn story(s: &Session, frames: &[NodeId]) -> String {
|
||||
frames.iter().map(|f| plain(s, *f)).collect()
|
||||
}
|
||||
|
||||
/// Two area frames threaded into one story whose text starts in the first, one line high, and
|
||||
/// flows on into the second.
|
||||
fn threaded(text: &str) -> (Session, NodeId, NodeId) {
|
||||
let mut s = new_doc();
|
||||
let a = area(&mut s, 10.0, 90.0, 18.0, text);
|
||||
let b = area(&mut s, 150.0, 200.0, 200.0, "");
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert_eq!(threads(&s), vec![vec![a, b]]);
|
||||
(s, a, b)
|
||||
}
|
||||
|
||||
const STORY: &str = "alpha beta gamma\ndelta \u{1F600}";
|
||||
|
||||
#[test]
|
||||
fn stories_list_one_story_for_each_thread_and_each_frame_in_none() {
|
||||
let (mut s, _, _) = threaded(STORY);
|
||||
area(&mut s, 400.0, 120.0, 40.0, "Alone");
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, st = d.stories[1];\
|
||||
vc.log(d.stories.length); vc.log(st.typename); vc.log(st.textFrames.length);\
|
||||
vc.log(st.textFrames[0].nextFrame.previousFrame.contents === st.textFrames[0].contents);\
|
||||
vc.log(st.textFrames[1].nextFrame === null && st.textFrames[0].previousFrame === null);\
|
||||
vc.log(d.stories[0].textFrames[0].contents); vc.log(d.stories[0].textFrames.length);\
|
||||
d.textFrames.add(); vc.log(d.stories.length);\
|
||||
vc.log(d.stories.parent.typename); vc.log(st.parent.typename); vc.log(d.stories.typename);\
|
||||
vc.log(d.textFrames[1].story.textFrames[0].contents);",
|
||||
);
|
||||
assert_eq!(
|
||||
out,
|
||||
vec![
|
||||
json!(2),
|
||||
json!("Story"),
|
||||
json!(2),
|
||||
json!(true),
|
||||
json!(true),
|
||||
json!("Alone"),
|
||||
json!(1),
|
||||
json!(3),
|
||||
json!("Document"),
|
||||
json!("Document"),
|
||||
json!("Stories"),
|
||||
json!("Alone")
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_story_range_counts_utf16_units_across_its_frames() {
|
||||
let (mut s, a, b) = threaded(STORY);
|
||||
let (first, second) = (plain(&s, a), plain(&s, b));
|
||||
assert!(!first.is_empty() && !second.is_empty(), "the story flows through both frames: {first:?} {second:?}");
|
||||
assert_eq!(first.clone() + &second, STORY);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var st = app.activeDocument.textFrames[0].story, r = st.textRange;\
|
||||
vc.log(st.length); vc.log(r.length); vc.log(r.contents); vc.log(r.typename);\
|
||||
vc.log(st.characters.length); vc.log(st.words.length); vc.log(st.paragraphs.length);\
|
||||
vc.log(st.paragraphs[0].contents); vc.log(st.words[4].contents); vc.log(st.words[4].start);\
|
||||
vc.log(r.paragraphs[1].getParagraphLength()); vc.log(r.story.length);\
|
||||
vc.log(app.activeDocument.textFrames[0].textRange.length < r.length);",
|
||||
);
|
||||
assert_eq!(
|
||||
out,
|
||||
vec![
|
||||
json!(25),
|
||||
json!(25),
|
||||
json!("alpha beta gamma\rdelta \u{1F600}"),
|
||||
json!("TextRange"),
|
||||
json!(24),
|
||||
json!(5),
|
||||
json!(2),
|
||||
json!("alpha beta gamma\r"),
|
||||
json!("\u{1F600}"),
|
||||
json!(23),
|
||||
json!(8),
|
||||
json!(25),
|
||||
json!(true)
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// The members a long story's range does not have yet throw that they are not available, and
|
||||
/// first that a range that went stale is stale.
|
||||
#[test]
|
||||
fn a_story_range_names_the_members_it_does_not_have_yet() {
|
||||
let (mut s, _, b) = threaded(STORY);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var r = app.activeDocument.textFrames[0].story.textRange;\
|
||||
try { r.characterAttributes; } catch (e) { vc.log(String(e.message)); }\
|
||||
try { r.size = 20; } catch (e) { vc.log(String(e.message)); }\
|
||||
try { app.activeDocument.textFrames[0].story.lines; } catch (e) { vc.log(String(e.message)); }",
|
||||
);
|
||||
assert_eq!(
|
||||
out,
|
||||
vec![
|
||||
json!("TextRange.characterAttributes is not available yet"),
|
||||
json!("TextRange.size is not available yet"),
|
||||
json!("Story.lines is not available yet")
|
||||
]
|
||||
);
|
||||
let message = failure(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var r = app.activeDocument.textFrames[0].story.textRange; vc.run('text.editRange', {{id: {}, start: 0, end: 0, insert: 'z'}}); r.characterAttributes;",
|
||||
b.0
|
||||
),
|
||||
);
|
||||
assert!(message.contains("Stale text range"), "{message}");
|
||||
let message = failure(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var r = app.activeDocument.textFrames[0].story.textRange; vc.run('text.editRange', {{id: {}, start: 0, end: 0, insert: 'z'}}); r.typename;",
|
||||
b.0
|
||||
),
|
||||
);
|
||||
assert!(message.contains("Stale text range"), "{message}");
|
||||
}
|
||||
|
||||
/// Ranges of one story read from different frames keep their places through each other's edits.
|
||||
#[test]
|
||||
fn story_ranges_read_from_different_frames_follow_each_others_edits() {
|
||||
let (mut s, _, _) = threaded(STORY);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames, x = t[0].story.words[0], y = t[1].story.words[1];\
|
||||
x.contents = 'Q'; vc.log(y.contents); vc.log(y.start); y.contents = 'B'; vc.log(x.contents);\
|
||||
vc.log(t[1].story.textRange.contents);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("beta"), json!(2), json!("Q"), json!("Q B gamma\rdelta \u{1F600}")]);
|
||||
}
|
||||
|
||||
/// A story range that an edit covers holds the edit's new text, as a frame's range does.
|
||||
#[test]
|
||||
fn a_story_range_an_edit_covers_holds_the_new_text() {
|
||||
let (mut s, _, _) = threaded(STORY);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var st = app.activeDocument.textFrames[0].story, w = st.words[1], p = st.paragraphs[1];\
|
||||
st.textRange.contents = 'Z'; vc.log(w.contents); vc.log(p.contents); vc.log(w.typename); vc.log(st.words.typename);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("Z"), json!("Z"), json!("TextRange"), json!("Words")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_story_edit_across_frames_reflows_in_one_undo_step() {
|
||||
let (mut s, a, b) = threaded(STORY);
|
||||
let before = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var st = app.activeDocument.textFrames[0].story, frame = app.activeDocument.textFrames[1].textRange;\
|
||||
var p = st.paragraphs[0], tail = st.paragraphs[1];\
|
||||
p.contents = 'X\\r'; vc.log(st.textRange.contents); vc.log(tail.contents); vc.log(tail.start);\
|
||||
try { frame.contents; } catch (e) { vc.log(String(e.message)); }\
|
||||
st.words[2].remove(); vc.log(st.textRange.contents);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("X\rdelta \u{1F600}"), json!("delta \u{1F600}"), json!(2), json!("Stale text range"), json!("X\rdelta ")]);
|
||||
assert_eq!(story(&s, &[a, b]), "X\ndelta ");
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(story(&s, &[a, b]), STORY);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_story_range_is_stale_after_another_change_to_the_story() {
|
||||
let (mut s, _, b) = threaded(STORY);
|
||||
let message = failure(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var r = app.activeDocument.textFrames[0].story.textRange; vc.run('text.editRange', {{id: {}, start: 0, end: 0, insert: 'z'}}); r.contents;",
|
||||
b.0
|
||||
),
|
||||
);
|
||||
assert!(message.contains("Stale text range"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_story_range_made_before_file_revert_is_stale_even_when_the_text_is_the_same() {
|
||||
let (mut s, _, _) = threaded(STORY);
|
||||
let path = std::env::temp_dir().join(format!("vc-story-revert-{}.vectorcraft", std::process::id()));
|
||||
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var r = app.activeDocument.textFrames[0].story.words[1];\
|
||||
vc.run('shape.rectangle', {x: 1, y: 1, width: 5, height: 5}); vc.run('file.revert', {});\
|
||||
var st = app.activeDocument.textFrames[0].story;\
|
||||
vc.log(st.textFrames.length); vc.log(st.textRange.contents);\
|
||||
try { vc.log(r.contents); } catch (e) { vc.log(String(e.message)); }\
|
||||
vc.log(st.words[1].contents);",
|
||||
);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
assert_eq!(out[0], json!(2), "the reverted file keeps the thread");
|
||||
assert_eq!(out[1], json!("alpha beta gamma\rdelta \u{1F600}"), "the reverted file holds the same text");
|
||||
assert!(out[2].as_str().is_some_and(|m| m.contains("Stale text range")), "{out:?}");
|
||||
assert_eq!(out[3], json!("beta"), "a range made after the revert reads the reverted text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_frame_joins_two_stories_in_one_undo_step_keeping_the_selection() {
|
||||
let mut s = new_doc();
|
||||
let a = area(&mut s, 10.0, 120.0, 60.0, "First story.");
|
||||
let b = area(&mut s, 150.0, 120.0, 60.0, "Second.");
|
||||
let p = NodeId(s.execute("text.create", &json!({"x": 20, "y": 300, "text": "Point"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [p.0]})).unwrap();
|
||||
let before = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames; t[2].nextFrame = t[1];\
|
||||
vc.log(app.activeDocument.stories.length); vc.log(t[1].previousFrame.contents); vc.log(t[2].story.textRange.contents);\
|
||||
t[2].nextFrame = t[1];",
|
||||
);
|
||||
assert_eq!(out, vec![json!(2), json!("First story.Second."), json!("First story.Second.")]);
|
||||
assert_eq!(threads(&s), vec![vec![a, b]]);
|
||||
assert_eq!(story(&s, &[a, b]), "First story.Second.");
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
assert_eq!(s.active().unwrap().selection.objects.to_vec(), vec![p]);
|
||||
// previousFrame links the other way.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(threads(&s).is_empty());
|
||||
assert_eq!((plain(&s, a), plain(&s, b)), ("First story.".into(), "Second.".into()));
|
||||
log(&mut s, "var t = app.activeDocument.textFrames; t[2].previousFrame = t[1];");
|
||||
assert_eq!(threads(&s), vec![vec![b, a]]);
|
||||
assert_eq!(story(&s, &[b, a]), "Second.First story.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn null_breaks_the_link_and_each_frame_keeps_its_text() {
|
||||
let (mut s, a, b) = threaded(STORY);
|
||||
let (first, second) = (plain(&s, a), plain(&s, b));
|
||||
let before = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames, st = t[0].story; t[0].previousFrame = null;\
|
||||
vc.log(app.activeDocument.stories.length); vc.log(st.textFrames.length); vc.log(t[1].nextFrame);\
|
||||
t[1].nextFrame = null;",
|
||||
);
|
||||
assert_eq!(out, vec![json!(2), json!(1), json!(null)]);
|
||||
assert!(threads(&s).is_empty());
|
||||
assert_eq!((plain(&s, a), plain(&s, b)), (first, second));
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(threads(&s), vec![vec![a, b]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn area_and_path_text_thread_the_new_frame_to_a_base_frame() {
|
||||
let mut s = new_doc();
|
||||
let base = area(&mut s, 10.0, 120.0, 40.0, "Base text that is long enough to flow on into the frames made after it.");
|
||||
s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 120, "height": 60})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 350, "y": 10, "width": 120, "height": 60})).unwrap();
|
||||
s.execute("path.create", &json!({"anchors": [{"x": 20, "y": 300}, {"x": 400, "y": 320}], "closed": false})).unwrap();
|
||||
let before = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, p = d.pageItems, base = d.textFrames[0];\
|
||||
var after = d.textFrames.areaText(p[2], undefined, base);\
|
||||
var first = d.textFrames.areaText(p[1], TextOrientation.HORIZONTAL, base, false);\
|
||||
var last = d.textFrames.pathText(p[0], undefined, undefined, undefined, after, true);\
|
||||
vc.log(base.story.textFrames.length); vc.log(base.previousFrame.kind); vc.log(after.nextFrame.kind); vc.log(d.stories.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(4), json!("TextType.AREATEXT"), json!("TextType.PATHTEXT"), json!(1)]);
|
||||
let t = threads(&s);
|
||||
assert_eq!(t.len(), 1);
|
||||
assert_eq!(t[0][1], base, "the frame made with postFix false comes before the base frame: {t:?}");
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_base_frame_is_refused_before_a_frame_is_made() {
|
||||
let mut s = new_doc();
|
||||
s.execute("text.create", &json!({"x": 20, "y": 300, "text": "Point"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 120, "height": 60})).unwrap();
|
||||
let count = |s: &Session| s.active().unwrap().doc.node_count();
|
||||
let (n, before) = (count(&s), undo_steps(&s));
|
||||
let d = "var d = app.activeDocument, p = d.pageItems;";
|
||||
assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[0], undefined, d.textFrames[0]);")).contains("only area type"));
|
||||
assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[0], undefined, p[0]);")).contains("baseFrame must be a TextFrame"));
|
||||
assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[0], undefined, d.textFrames[0], 'yes');")).contains("postFix"));
|
||||
assert_eq!((count(&s), undo_steps(&s)), (n, before));
|
||||
}
|
||||
|
||||
/// A base frame given with a path inside a compound path is refused before the path is turned
|
||||
/// into type, so a script that catches the error finds the path as it was.
|
||||
#[test]
|
||||
fn a_base_frame_for_a_path_in_a_compound_path_leaves_the_path() {
|
||||
let mut s = new_doc();
|
||||
area(&mut s, 10.0, 120.0, 60.0, "Base.");
|
||||
let r1 = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 80, "height": 80})).unwrap()["id"].as_u64().unwrap();
|
||||
let r2 = s.execute("shape.rectangle", &json!({"x": 300, "y": 10, "width": 80, "height": 80})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [r1, r2]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let before = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, p = null;\
|
||||
for (var i = 0; i < d.pageItems.length; i++) { if (d.pageItems[i].typename == 'PathItem') { p = d.pageItems[i]; break; } }\
|
||||
try { d.textFrames.areaText(p, undefined, d.textFrames[0]); } catch (e) { vc.log(String(e.message)); }\
|
||||
vc.log(p.typename); vc.log(d.textFrames.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("baseFrame: type made from a path inside a compound path cannot be threaded"), json!("PathItem"), json!(1)]);
|
||||
assert_eq!(undo_steps(&s), before);
|
||||
}
|
||||
|
||||
/// A thread of `a` and `b`, a third area frame `c`, and point type `p`; what the document holds
|
||||
/// now, to check that a refused change left it alone.
|
||||
fn three() -> (Session, [NodeId; 4]) {
|
||||
let (mut s, a, b) = threaded(STORY);
|
||||
let c = area(&mut s, 400.0, 120.0, 40.0, "Third");
|
||||
let p = NodeId(s.execute("text.create", &json!({"x": 20, "y": 300, "text": "Point"})).unwrap()["id"].as_u64().unwrap());
|
||||
(s, [a, b, c, p])
|
||||
}
|
||||
|
||||
fn unchanged(s: &Session, ids: &[NodeId], before: &(Vec<Vec<NodeId>>, Vec<String>, usize)) {
|
||||
assert_eq!((threads(s), ids.iter().map(|i| plain(s, *i)).collect::<Vec<_>>(), undo_steps(s)), *before);
|
||||
}
|
||||
|
||||
fn state(s: &Session, ids: &[NodeId]) -> (Vec<Vec<NodeId>>, Vec<String>, usize) {
|
||||
(threads(s), ids.iter().map(|i| plain(s, *i)).collect(), undo_steps(s))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_link_to_the_frame_itself_is_refused() {
|
||||
let (mut s, ids) = three();
|
||||
let before = state(&s, &ids);
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[2];");
|
||||
assert!(m.contains("nextFrame") && m.contains("itself"), "{m}");
|
||||
unchanged(&s, &ids, &before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_link_that_makes_a_loop_is_refused() {
|
||||
let (mut s, ids) = three();
|
||||
let before = state(&s, &ids);
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[3];");
|
||||
assert!(m.contains("loop"), "{m}");
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[3].previousFrame = t[2];");
|
||||
assert!(m.contains("loop"), "{m}");
|
||||
unchanged(&s, &ids, &before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_link_into_the_middle_of_a_story_is_refused() {
|
||||
let (mut s, ids) = three();
|
||||
let before = state(&s, &ids);
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].nextFrame = t[2];");
|
||||
assert!(m.contains("already has a previous frame"), "{m}");
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].previousFrame = t[3];");
|
||||
assert!(m.contains("already has a next frame"), "{m}");
|
||||
unchanged(&s, &ids, &before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_type_and_other_values_cannot_be_linked() {
|
||||
let (mut s, ids) = three();
|
||||
let before = state(&s, &ids);
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].nextFrame = t[0];");
|
||||
assert!(m.contains("only area type"), "{m}");
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[0].previousFrame = t[1];");
|
||||
assert!(m.contains("only area type"), "{m}");
|
||||
let m = failure(&mut s, "app.activeDocument.textFrames[1].nextFrame = 5;");
|
||||
assert!(m.contains("TypeError") && m.contains("TextFrame or null"), "{m}");
|
||||
let m = failure(&mut s, "app.activeDocument.textFrames[1].nextFrame = undefined;");
|
||||
assert!(m.contains("TextFrame or null"), "{m}");
|
||||
unchanged(&s, &ids, &before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hidden_or_locked_frame_in_either_story_stops_a_link() {
|
||||
let (mut s, ids) = three();
|
||||
log(&mut s, "app.activeDocument.textFrames[2].locked = true;");
|
||||
let before = state(&s, &ids);
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[1];");
|
||||
assert!(m.contains("hidden or locked"), "{m}");
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[3].nextFrame = null;");
|
||||
assert!(m.contains("hidden or locked"), "{m}");
|
||||
// A script that catches the error goes on, and the links stay as they were.
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames; try { t[2].nextFrame = t[1]; } catch (e) { vc.log([e.name, /hidden or locked/.test(e.message)]); }\
|
||||
vc.log(t[2].nextFrame === null);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(["Error", true]), json!(true)]);
|
||||
unchanged(&s, &ids, &before);
|
||||
}
|
||||
|
||||
/// Reading a story whose text is larger than what one run may pass to and from the host stops
|
||||
/// the run when the story's text is joined.
|
||||
#[test]
|
||||
fn joining_a_storys_text_counts_toward_the_runs_data_limit() {
|
||||
let text = "word ".repeat(40_000);
|
||||
let (mut s, _, _) = threaded(&text);
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(100_000)));
|
||||
let r = run(&mut s, "vc.log(app.activeDocument.stories[0].length);");
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
|
||||
let e = r.map(|r| panic!("the run read a 200 KB story within a 100 KB limit: {r}")).unwrap_err().to_string();
|
||||
assert!(e.contains("more data to and from commands"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frame_of_another_document_cannot_be_linked() {
|
||||
let (mut s, ids) = three();
|
||||
let before = state(&s, &ids);
|
||||
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
|
||||
area(&mut s, 10.0, 100.0, 40.0, "Elsewhere");
|
||||
s.execute("shape.rectangle", &json!({"x": 150, "y": 10, "width": 80, "height": 60})).unwrap();
|
||||
let m = failure(&mut s, "app.documents[1].textFrames[1].nextFrame = app.documents[0].textFrames[0];");
|
||||
assert!(m.contains("different documents"), "{m}");
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.documents[0], p = d.pageItems[0];\
|
||||
try { d.textFrames.areaText(p, undefined, app.documents[1].textFrames[1]); } catch (e) { vc.log(String(e.message)); }\
|
||||
vc.log(p.typename); vc.log(d.textFrames.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("baseFrame: the frame is in another document"), json!("PathItem"), json!(1)]);
|
||||
s.execute("document.activate", &json!({"index": 0})).unwrap();
|
||||
unchanged(&s, &ids, &before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deleted_frame_makes_its_story_and_links_stale() {
|
||||
let (mut s, _, _) = threaded(STORY);
|
||||
let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], st = f.story; f.remove(); st.length;");
|
||||
assert!(m.contains("Stale story"), "{m}");
|
||||
let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], st = f.story; f.remove(); st.lines;");
|
||||
assert!(m.contains("Stale story"), "{m}");
|
||||
let m = failure(&mut s, "var f = app.activeDocument.textFrames[1], g = app.activeDocument.textFrames[0]; g.remove(); f.nextFrame = g;");
|
||||
assert!(m.contains("Stale page item"), "{m}");
|
||||
let m = failure(&mut s, "var f = app.activeDocument.textFrames[1], r = f.story.textRange; f.remove(); r.contents;");
|
||||
assert!(m.contains("Stale text range"), "{m}");
|
||||
// A story read from a frame that stays follows it when its link is broken.
|
||||
let out = log(&mut s, "var t = app.activeDocument.textFrames, st = t[0].story; t[1].nextFrame = null; vc.log(st.textFrames.length);");
|
||||
assert_eq!(out, vec![json!(1)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stories_refuse_bad_keys_and_huge_numbers() {
|
||||
let (mut s, _, _) = threaded(STORY);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var st = app.activeDocument.stories; vc.log(st[1e300] === undefined); vc.log(st[-1] === undefined); vc.log(st[0.5] === undefined);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(true), json!(true), json!(true)]);
|
||||
assert!(failure(&mut s, "app.activeDocument.stories.index(1e20);").contains("Not found"));
|
||||
assert!(failure(&mut s, "app.activeDocument.stories.index('nobody');").contains("Not found"));
|
||||
assert!(failure(&mut s, "app.activeDocument.stories.index({});").contains("TypeError"));
|
||||
log(&mut s, "app.activeDocument.textFrames[1].name = 'Lead';");
|
||||
assert_eq!(log(&mut s, "vc.log(app.activeDocument.stories.index('Lead').textFrames.length);"), vec![json!(2)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_story_walks_to_its_end_and_refuses_a_loop() {
|
||||
let mut s = new_doc();
|
||||
let ids: Vec<NodeId> = (0..120).map(|i| area(&mut s, f64::from(i % 12) * 45.0, 40.0, 20.0, if i == 0 { STORY } else { "" })).collect();
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert_eq!(threads(&s), vec![ids.clone()]);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, f = d.stories[0].textFrames[0], n = 1; while (f.nextFrame) { f = f.nextFrame; n++; } \
|
||||
vc.log(n); vc.log(f.story.textFrames.length); vc.log(d.stories.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(120), json!(120), json!(1)]);
|
||||
let before = state(&s, &ids);
|
||||
let m = failure(&mut s, "var t = app.activeDocument.stories[0].textFrames; t[t.length - 1].nextFrame = t[0];");
|
||||
assert!(m.contains("loop"), "{m}");
|
||||
let m = failure(&mut s, "var t = app.activeDocument.stories[0].textFrames; t[0].previousFrame = t[t.length - 1];");
|
||||
assert!(m.contains("loop"), "{m}");
|
||||
let m = failure(&mut s, "var t = app.activeDocument.stories[0].textFrames; t[60].nextFrame = t[30];");
|
||||
assert!(m.contains("loop"), "{m}");
|
||||
unchanged(&s, &ids, &before);
|
||||
}
|
||||
|
||||
/// A stored thread that lists a frame twice, as a file can, is a story that visits each frame
|
||||
/// once, so a walk along `nextFrame` ends.
|
||||
#[test]
|
||||
fn a_thread_listing_a_frame_twice_is_walked_once() {
|
||||
let mut s = new_doc();
|
||||
let a = area(&mut s, 10.0, 120.0, 60.0, "One.");
|
||||
let b = area(&mut s, 150.0, 120.0, 60.0, "Two.");
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).text_threads = vec![vec![a, b, a]];
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, f = d.stories[0].textFrames[0], n = 1; while (f.nextFrame && n < 10) { f = f.nextFrame; n++; } \
|
||||
vc.log(n); vc.log(d.stories[0].textFrames.length); vc.log(d.stories.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(2), json!(2), json!(1)]);
|
||||
let r = s.execute("text.thread.setNeighbor", &json!({"id": b.0, "side": "previous", "neighbor": null})).unwrap();
|
||||
assert_eq!(r, json!({"changed": true, "threads": [[a.0], [b.0]]}));
|
||||
assert!(threads(&s).is_empty());
|
||||
}
|
||||
|
||||
/// When a frame is listed in two threads, a story read from a frame of the second thread reads
|
||||
/// that thread's text, not the text of the story read before it from a shared frame.
|
||||
#[test]
|
||||
fn stories_of_threads_that_share_a_frame_keep_their_own_text() {
|
||||
let mut s = new_doc();
|
||||
let a = area(&mut s, 10.0, 120.0, 60.0, "One.");
|
||||
let b = area(&mut s, 150.0, 120.0, 60.0, "Two.");
|
||||
let c = area(&mut s, 300.0, 120.0, 60.0, "Three!");
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).text_threads = vec![vec![a, b], vec![b, c]];
|
||||
let out = log(&mut s, "var t = app.activeDocument.textFrames; vc.log(t[1].story.length); vc.log(t[0].story.length);");
|
||||
let (ab, bc) = (story(&s, &[a, b]).encode_utf16().count(), story(&s, &[b, c]).encode_utf16().count());
|
||||
assert_ne!(ab, bc);
|
||||
assert_eq!(out, vec![json!(ab), json!(bc)]);
|
||||
}
|
||||
|
||||
/// A story and its range keep the exact id of the frame they were read from, also past 2^53.
|
||||
#[test]
|
||||
fn a_story_read_from_a_frame_with_a_large_id_stays_with_that_frame() {
|
||||
let mut s = new_doc();
|
||||
// The second frame's id, 2^53 + 1, is not exact as a number.
|
||||
let big = 1u64 << 53;
|
||||
s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big));
|
||||
let a = area(&mut s, 10.0, 120.0, 60.0, "One.");
|
||||
let b = area(&mut s, 150.0, 120.0, 60.0, "Two.");
|
||||
assert_eq!((a.0, b.0), (big, big + 1));
|
||||
s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": b.0})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var st = app.activeDocument.stories[0].textFrames[1].story, r = st.textRange; vc.log(r.contents);\
|
||||
st.textFrames[0].nextFrame = null; vc.log(st.textFrames.length); vc.log(st.textFrames[0].contents); vc.log(st.typename);",
|
||||
);
|
||||
// The whole story flows into the first frame, so the second is empty once the link is broken.
|
||||
assert_eq!(out, vec![json!("One.Two."), json!(1), json!(""), json!("Story")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_neighbor_links_and_breaks_frames_by_id_without_a_selection() {
|
||||
let mut s = new_doc();
|
||||
let a = area(&mut s, 10.0, 120.0, 60.0, "One.");
|
||||
let b = area(&mut s, 150.0, 120.0, 60.0, "Two.");
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let before = undo_steps(&s);
|
||||
let r = s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": b.0})).unwrap();
|
||||
assert_eq!(r, json!({"changed": true, "threads": [[a.0, b.0]]}));
|
||||
let r = s.execute("text.thread.setNeighbor", &json!({"id": b.0, "side": "previous", "neighbor": a.0})).unwrap();
|
||||
assert_eq!(r["changed"], json!(false));
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
assert!(s.active().unwrap().selection.objects.is_empty());
|
||||
let r = s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": null})).unwrap();
|
||||
assert_eq!(r, json!({"changed": true, "threads": [[a.0], [b.0]]}));
|
||||
let r = s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": null})).unwrap();
|
||||
assert_eq!(r["changed"], json!(false));
|
||||
assert_eq!(undo_steps(&s), before + 2);
|
||||
for bad in [
|
||||
json!({"id": a.0, "side": "up", "neighbor": b.0}),
|
||||
json!({"id": a.0, "side": "next"}),
|
||||
json!({"id": a.0, "side": "next", "neighbor": 999_999}),
|
||||
] {
|
||||
assert!(s.execute("text.thread.setNeighbor", &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(undo_steps(&s), before + 2);
|
||||
}
|
||||
|
||||
/// Breaking a link where a paragraph starts makes the frames after it a story whose numbered
|
||||
/// paragraphs count from 1, also when that story keeps two frames.
|
||||
#[test]
|
||||
fn a_break_at_a_paragraph_start_numbers_the_later_story_from_one() {
|
||||
let mut s = new_doc();
|
||||
let items = (1..=12).map(|i| format!("Item {i}")).collect::<Vec<_>>().join("\n");
|
||||
let ids = [area(&mut s, 10.0, 150.0, 60.0, &items), area(&mut s, 200.0, 150.0, 60.0, ""), area(&mut s, 400.0, 150.0, 200.0, "")];
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "list": "number"})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let numbers = |s: &Session, id: NodeId| {
|
||||
let Some(NodeKind::Text(t)) = s.active().unwrap().doc.node(id).map(|n| &n.kind) else { panic!("text") };
|
||||
assert!(!t.first_para_continues, "every frame starts a paragraph");
|
||||
vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).markers.iter().map(|m| m.text.clone()).collect::<Vec<_>>()
|
||||
};
|
||||
let first = numbers(&s, ids[0]);
|
||||
assert!(!first.is_empty() && !numbers(&s, ids[1]).is_empty(), "the first two frames hold items");
|
||||
assert_ne!(numbers(&s, ids[1]).first().map(String::as_str), Some("1."));
|
||||
let r = s.execute("text.thread.setNeighbor", &json!({"id": ids[0].0, "side": "next", "neighbor": null})).unwrap();
|
||||
assert_eq!(r, json!({"changed": true, "threads": [[ids[0].0], [ids[1].0, ids[2].0]]}));
|
||||
let later = [numbers(&s, ids[1]), numbers(&s, ids[2])].concat();
|
||||
let expected: Vec<String> = (1..=later.len()).map(|n| format!("{n}.")).collect();
|
||||
assert_eq!(later, expected, "the later story counts from 1");
|
||||
assert_eq!(numbers(&s, ids[0]), first);
|
||||
}
|
||||
@@ -217,4 +217,178 @@ fn set_option_sets_the_direction_and_refuses_bad_values() {
|
||||
assert_eq!(s.set_tool_option_cmd(&p).unwrap_err(), want, "{p}");
|
||||
}
|
||||
assert_eq!(s.tool_options_of("threePointArc")["direction"], json!(false));
|
||||
// `join` starts off and `tangentSnap` on; both take only true or false.
|
||||
assert_eq!(
|
||||
(s.tool_options_of("threePointArc")["join"].clone(), s.tool_options_of("threePointArc")["tangentSnap"].clone()),
|
||||
(json!(false), json!(true))
|
||||
);
|
||||
let set = s.set_tool_option_cmd(&json!({"tool": "threePointArc", "values": {"join": true, "tangentSnap": false}})).unwrap();
|
||||
assert_eq!((set["join"].clone(), set["tangentSnap"].clone()), (json!(true), json!(false)));
|
||||
for key in ["join", "tangentSnap"] {
|
||||
let e = s.set_tool_option_cmd(&json!({"tool": "threePointArc", "key": key, "value": 1})).unwrap_err();
|
||||
assert_eq!(e, format!("tool `threePointArc`: `{key}` must be true or false"));
|
||||
}
|
||||
}
|
||||
|
||||
/// An open path drawn from SVG path data, selected.
|
||||
fn open_path(s: &mut Session, d: &str) -> NodeId {
|
||||
id_of(&s.execute("path.create", &json!({ "d": d })).unwrap())
|
||||
}
|
||||
|
||||
/// The anchors of the first subpath of `id`, and whether it is closed.
|
||||
fn anchors(s: &Session, id: NodeId) -> (Vec<Point>, bool) {
|
||||
let n = node(s, id);
|
||||
let sp = &n.path_data().unwrap().subpaths[0];
|
||||
(sp.anchors.iter().map(|a| a.p).collect(), sp.closed)
|
||||
}
|
||||
|
||||
/// With `join`, an arc starting on the last anchor of an open path is added to that path: the path
|
||||
/// keeps its id and direction and now ends where the arc ends, the anchor where they meet is not
|
||||
/// doubled, and it is one undo step. An arc ending on a path's first anchor is added before it.
|
||||
#[test]
|
||||
fn join_adds_the_arc_to_the_open_path_it_starts_on() {
|
||||
let mut s = session();
|
||||
let id = open_path(&mut s, "M0 100 L100 100");
|
||||
let (undo, count) = (undo_len(&s), object_count(&s));
|
||||
let out = s.execute(C, &json!({"start": [100, 100], "end": [180, 100], "through": [140, 60], "join": true})).unwrap();
|
||||
assert_eq!((id_of(&out), out["joined"].clone(), out["radius"].as_f64()), (id, json!(true), Some(40.0)), "{out}");
|
||||
assert_eq!((undo_len(&s), object_count(&s)), (undo + 1, count));
|
||||
let (pts, closed) = anchors(&s, id);
|
||||
assert!(!closed);
|
||||
assert_eq!((pts.first().copied(), pts.last().copied()), (Some(Point::new(0.0, 100.0)), Some(Point::new(180.0, 100.0))), "{pts:?}");
|
||||
assert_eq!(pts.iter().filter(|p| **p == Point::new(100.0, 100.0)).count(), 1, "{pts:?}");
|
||||
assert!(farthest_from_path(&s, id, &[Point::new(140.0, 60.0), Point::new(50.0, 100.0)]) < 1e-9);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [id]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(anchors(&s, id).0, [Point::new(0.0, 100.0), Point::new(100.0, 100.0)]);
|
||||
// The arc ends on the first anchor of a path running right: the path still runs right, from
|
||||
// the arc's start.
|
||||
let id = open_path(&mut s, "M300 100 L400 100");
|
||||
let out = s.execute(C, &json!({"start": [220, 100], "end": [300, 100], "toward": [220, 60], "join": true})).unwrap();
|
||||
assert_eq!(id_of(&out), id);
|
||||
let (pts, _) = anchors(&s, id);
|
||||
assert_eq!((pts.first().copied(), pts.last().copied()), (Some(Point::new(220.0, 100.0)), Some(Point::new(400.0, 100.0))), "{pts:?}");
|
||||
assert!(farthest_from_path(&s, id, &[Point::new(260.0, 60.0)]) < 1e-9);
|
||||
}
|
||||
|
||||
/// With both ends on ends of two open paths, the arc joins them into one path in one undo step;
|
||||
/// with both ends on the two ends of one open path, the path closes.
|
||||
#[test]
|
||||
fn join_with_both_ends_on_open_paths_makes_one_path() {
|
||||
let mut s = session();
|
||||
let a = open_path(&mut s, "M0 100 L100 100");
|
||||
let b = open_path(&mut s, "M180 100 L280 100");
|
||||
let (undo, count) = (undo_len(&s), object_count(&s));
|
||||
let out = s.execute(C, &json!({"start": [100, 100], "end": [180, 100], "through": [140, 60], "join": true})).unwrap();
|
||||
assert_eq!(id_of(&out), a);
|
||||
assert_eq!((undo_len(&s), object_count(&s)), (undo + 1, count - 1));
|
||||
assert!(s.doc().unwrap().doc.node(b).is_none());
|
||||
let (pts, closed) = anchors(&s, a);
|
||||
assert!(!closed);
|
||||
let ends = (pts.first().copied(), pts.last().copied());
|
||||
assert!(
|
||||
ends == (Some(Point::new(0.0, 100.0)), Some(Point::new(280.0, 100.0)))
|
||||
|| ends == (Some(Point::new(280.0, 100.0)), Some(Point::new(0.0, 100.0))),
|
||||
"{pts:?}"
|
||||
);
|
||||
for p in [Point::new(100.0, 100.0), Point::new(180.0, 100.0)] {
|
||||
assert_eq!(pts.iter().filter(|q| **q == p).count(), 1, "{pts:?}");
|
||||
}
|
||||
assert!(farthest_from_path(&s, a, &[Point::new(140.0, 60.0), Point::new(230.0, 100.0)]) < 1e-9);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!((object_count(&s), anchors(&s, b).0.len()), (count, 2));
|
||||
// One path's two ends: it closes.
|
||||
let id = open_path(&mut s, "M100 300 L180 300");
|
||||
let out = s.execute(C, &json!({"start": [180, 300], "end": [100, 300], "through": [140, 340], "join": true})).unwrap();
|
||||
assert_eq!(id_of(&out), id);
|
||||
let (pts, closed) = anchors(&s, id);
|
||||
assert!(closed, "{pts:?}");
|
||||
assert_eq!(pts.iter().filter(|q| **q == Point::new(100.0, 300.0)).count(), 1, "{pts:?}");
|
||||
assert!(farthest_from_path(&s, id, &[Point::new(140.0, 340.0), Point::new(140.0, 300.0)]) < 1e-9);
|
||||
}
|
||||
|
||||
/// Of two open path ends at the arc's start, `join` takes the one in the selection, and with
|
||||
/// neither selected the one in front.
|
||||
#[test]
|
||||
fn join_prefers_the_selected_path_then_the_front_one() {
|
||||
let mut s = session();
|
||||
let back = open_path(&mut s, "M0 100 L100 100");
|
||||
let front = open_path(&mut s, "M100 200 L100 100");
|
||||
for (selected, want) in [(Some(back), back), (None, front)] {
|
||||
let ids: Vec<u64> = selected.iter().map(|id| id.0).collect();
|
||||
s.execute("select.set", &json!({ "ids": ids })).unwrap();
|
||||
let out = s.execute(C, &json!({"start": [100, 100], "end": [180, 100], "through": [140, 60], "join": true})).unwrap();
|
||||
assert_eq!(id_of(&out), want, "{selected:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
// In isolation mode, a path outside the isolated group is left alone.
|
||||
s.execute("select.set", &json!({ "ids": [back.0] })).unwrap();
|
||||
let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.isolate", &json!({ "id": group })).unwrap();
|
||||
s.execute("select.set", &json!({ "ids": [] })).unwrap();
|
||||
let out = s.execute(C, &json!({"start": [100, 100], "end": [100, 20], "through": [60, 60], "join": true})).unwrap();
|
||||
assert_eq!(id_of(&out), back, "{out}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let out = s.execute(C, &json!({"start": [100, 200], "end": [180, 200], "through": [140, 160], "join": true})).unwrap();
|
||||
assert!(out.get("joined").is_none(), "{out}");
|
||||
assert_eq!(anchors(&s, front).0.len(), 2);
|
||||
}
|
||||
|
||||
/// Without `join`, away from open path ends, on a locked path, or on a closed path's anchor, the
|
||||
/// arc is a new path; a `join` that is not true or false is an error and draws nothing.
|
||||
#[test]
|
||||
fn join_leaves_paths_it_cannot_join_alone() {
|
||||
let mut s = session();
|
||||
let line = open_path(&mut s, "M0 100 L100 100");
|
||||
let rect = open_path(&mut s, "M200 200 L300 200 L300 300 Z");
|
||||
let arc = |s: &mut Session, start: [f64; 2], end: [f64; 2], via: [f64; 2], join: Value| {
|
||||
s.execute(C, &json!({"start": start, "end": end, "through": via, "join": join}))
|
||||
};
|
||||
for (start, end, via, join) in [
|
||||
([100.0, 100.0], [180.0, 100.0], [140.0, 60.0], json!(false)),
|
||||
([100.0, 120.0], [180.0, 120.0], [140.0, 80.0], json!(true)),
|
||||
([200.0, 200.0], [120.0, 200.0], [160.0, 160.0], json!(true)),
|
||||
] {
|
||||
let count = object_count(&s);
|
||||
let out = arc(&mut s, start, end, via, join.clone()).unwrap();
|
||||
assert!(out.get("joined").is_none() && id_of(&out) != line && id_of(&out) != rect, "{join}: {out}");
|
||||
assert_eq!(object_count(&s), count + 1);
|
||||
}
|
||||
assert_eq!(anchors(&s, line).0.len(), 2);
|
||||
s.execute("select.set", &json!({"ids": [line.0]})).unwrap();
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
// On the line's other end, where none of the arcs above ends.
|
||||
let out = arc(&mut s, [0.0, 100.0], [0.0, 180.0], [40.0, 140.0], json!(true)).unwrap();
|
||||
assert!(out.get("joined").is_none(), "{out}");
|
||||
assert_eq!(anchors(&s, line).0.len(), 2);
|
||||
let count = object_count(&s);
|
||||
let e = arc(&mut s, [100.0, 300.0], [180.0, 300.0], [140.0, 260.0], json!("yes")).unwrap_err().to_string();
|
||||
assert!(e.contains("`join` must be true or false"), "{e}");
|
||||
assert_eq!(object_count(&s), count);
|
||||
}
|
||||
|
||||
/// With the tool's `join` option on, clicks near an open path's end place the arc's end on it and
|
||||
/// the arc joins the path; with it off the arc is a path of its own, and J while the ends are
|
||||
/// placed switches it on.
|
||||
#[test]
|
||||
fn the_tool_joins_the_arc_to_the_path_end_it_starts_near() {
|
||||
let mut s = session();
|
||||
let id = open_path(&mut s, "M0 100 L100 100");
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
s.select_tool("threePointArc", view()).unwrap();
|
||||
let count = object_count(&s);
|
||||
for p in [(100.0, 100.0), (180.0, 100.0), (140.0, 60.0)] {
|
||||
click(&mut s, p.0, p.1);
|
||||
}
|
||||
assert_eq!((object_count(&s), anchors(&s, id).0.len()), (count + 1, 2), "off: a path of its own");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// J after the first click, near the path's end, switches `join` on.
|
||||
click(&mut s, 99.0, 100.5);
|
||||
s.tool_key(ToolKey::Letter('j'), Mods::default(), view()).unwrap();
|
||||
click(&mut s, 180.0, 100.0);
|
||||
click(&mut s, 140.0, 60.0);
|
||||
assert_eq!(object_count(&s), count);
|
||||
let (pts, _) = anchors(&s, id);
|
||||
assert_eq!((pts.len() > 2, pts.last().copied()), (true, Some(Point::new(180.0, 100.0))), "{pts:?}");
|
||||
assert_eq!(s.tool_options_of("threePointArc")["join"], json!(true), "J keeps the option switched");
|
||||
}
|
||||
@@ -6,7 +6,8 @@
|
||||
//! of every kind with random contents) opened, placed or pasted, nor PICT pictures (damaged files,
|
||||
//! opcodes with random contents) opened or placed, nor EPS and PostScript files
|
||||
//! (damaged ones, hostile programs) read by the PostScript interpreter, nor the editing data of
|
||||
//! Illustrator EPS and `.ai` files (the layers they carry, damaged or hostile), nor Affinity documents
|
||||
//! Illustrator EPS and `.ai` files (the layers they carry, damaged or hostile), nor the widths a
|
||||
//! `.ai`'s PDF part gives its fonts' characters (hostile font dictionaries), nor Affinity documents
|
||||
//! (mutated object streams, archives and indexed PNG previews, hostile image dimensions), nor
|
||||
//! `.cdr` drawings (mutated and cut short, plain, compressed and packaged, opened and placed),
|
||||
//! nor `.cmx` files (mutated, cut short and garbage after the header, opened and placed),
|
||||
@@ -1171,6 +1172,58 @@ proptest! {
|
||||
}
|
||||
}
|
||||
|
||||
/// A font dictionary whose widths are hostile, for [`vectorcraft_pdf::Opened::page_widths`]: any
|
||||
/// subtype, encoding and first code, widths that are huge, negative or not numbers, a composite
|
||||
/// font's `W` of any shape, and the `ToUnicode` map of object 5.
|
||||
fn arb_width_font() -> impl Strategy<Value = String> {
|
||||
(
|
||||
prop::sample::select(vec!["/TrueType", "/Type1", "/Type0", "/Type3", "/MMType1", "7"]),
|
||||
prop::sample::select(vec!["/WinAnsiEncoding", "/Identity-H", "/Identity-V", "/MacRomanEncoding", "<< /Differences [65 /A] >>", "null"]),
|
||||
prop::sample::select(vec!["0", "65", "-5", "255", "256", "4294967295", "1e30", "/X"]),
|
||||
prop::collection::vec(prop::sample::select(vec!["500", "0", "-1", "1e40", "NaN", "null", "[1 2]", "/W"]), 0..12),
|
||||
prop::collection::vec(prop::sample::select(vec!["1", "[500 600]", "65", "4294967295", "300", "-1", "[]", "1e9", "0 65535 7"]), 0..10),
|
||||
prop::sample::select(vec!["/ABCDEF+Fuzz", "/Fuzz", "/ABCDEF+", "/+", "()", "/Fuzz-Identity-H"]),
|
||||
any::<bool>(),
|
||||
)
|
||||
.prop_map(|(subtype, encoding, first, widths, w, name, mapped)| {
|
||||
let map = if mapped { "/ToUnicode 5 0 R" } else { "" };
|
||||
format!(
|
||||
"<< /Type /Font /Subtype {subtype} /BaseFont {name} /Encoding {encoding} /FirstChar {first} /Widths [{}] {map} \
|
||||
/DescendantFonts [<< /Subtype /CIDFontType2 /BaseFont {name} /W [{}] >>] >>",
|
||||
widths.join(" "),
|
||||
w.join(" ")
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(config())]
|
||||
|
||||
/// The widths a page's fonts give their characters (read for a `.ai`'s text document) are read
|
||||
/// without a panic from hostile font dictionaries, `ToUnicode` maps of any text, and forms that
|
||||
/// draw themselves.
|
||||
#[test]
|
||||
fn pdf_font_widths_never_panic(
|
||||
fonts in prop::collection::vec(arb_width_font(), 1..4),
|
||||
cmap in prop::collection::vec(prop::sample::select(vec![
|
||||
"begincmap", "1 begincodespacerange", "<0000> <FFFF>", "<00> <FF>", "endcodespacerange", "2 beginbfchar", "<0001> <0041>",
|
||||
"<0002> <D800>", "<41> <FFFD>", "1 beginbfrange", "<0000> <FFFF> <0000>", "<FFFF> <0000> <0041>", "<0001> <0003> [<0041> <0042>]",
|
||||
"endbfrange", "endbfchar", "endcmap", "/Identity-H usecmap", "99999999999 beginbfchar",
|
||||
]), 0..12),
|
||||
) {
|
||||
let list: Vec<String> = fonts.iter().enumerate().map(|(i, f)| format!("/F{i} {f}")).collect();
|
||||
let map = cmap.join("\n");
|
||||
let form = format!(
|
||||
"<< /Type /XObject /Subtype /Form /BBox [0 0 1 1] /Resources << /Font << /F0 {} >> /XObject << /X0 6 0 R >> >> /Length 0 >>\nstream\n\nendstream",
|
||||
fonts[0]
|
||||
);
|
||||
let more = [format!("<< /Length {} >>\nstream\n{map}\nendstream", map.len() + 1).into_bytes(), form.into_bytes()];
|
||||
let pdf = handmade_pdf_with("", &format!("<< /Font << {} >> /XObject << /X0 6 0 R >> >>", list.join(" ")), "[0 0 100 100]", &more);
|
||||
let read = catch_quiet(|| vectorcraft_pdf::open_pdf(&pdf, None).ok().map(|o| o.page_widths()));
|
||||
prop_assert!(read.is_ok(), "{fonts:?} {cmap:?}: {read:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A dictionary value: one the reader reads, or one it skips over but can't parse (a name with a
|
||||
/// broken `#` escape, a number with a stray `-`).
|
||||
fn arb_dict_value() -> impl Strategy<Value = &'static str> {
|
||||
|
||||
@@ -107,8 +107,8 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
"Document.prototype.",
|
||||
"activeLayer activeLayer= artboards artboards= characterStyles close close= constructor convertCoordinate \
|
||||
documentColorSpace groupItems groupItems= height layers layers= name pageItems paragraphStyles parent pathItems \
|
||||
pathItems= rulerOrigin rulerOrigin= rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols \
|
||||
symbols= tags textFrames toString typename views width",
|
||||
pathItems= rulerOrigin rulerOrigin= rulerUnits saveAs saveAs= selection selection= stories swatches swatches= \
|
||||
symbols symbols= tags textFrames toString typename views width",
|
||||
),
|
||||
("Views.", "prototype"),
|
||||
("Views.prototype.", "constructor index length parent toString typename"),
|
||||
@@ -167,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"),
|
||||
@@ -180,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 \
|
||||
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",
|
||||
),
|
||||
@@ -234,6 +234,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"),
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -236,6 +236,10 @@ pub struct Structure {
|
||||
/// placed in the document, or a color linked to its swatch at its tint (see
|
||||
/// `ate::Texts::with_paints`).
|
||||
pub text_paints: HashMap<String, Paint>,
|
||||
/// The widths a `.ai`'s PDF part gives the characters of its fonts, which tell installed copies
|
||||
/// of a font apart for type whose font record keeps no version (see
|
||||
/// `ate::Texts::with_page_widths`): none until the importer sets them.
|
||||
pub page_widths: vectorcraft_pdf::PageWidths,
|
||||
/// The file's `%AI24_LargeCanvasScale` (1 when it declares none), applied or not.
|
||||
pub canvas_scale: f64,
|
||||
/// The data's symbols are at their own size, whatever its scale: VectorCraft wrote it (its
|
||||
|
||||
@@ -1481,6 +1481,7 @@ impl<'a> Reader<'a> {
|
||||
},
|
||||
styles_read,
|
||||
text_paints,
|
||||
page_widths: Default::default(),
|
||||
canvas_scale: self.canvas_scale,
|
||||
symbols_own_size: self.symbols_own_size,
|
||||
xml_ids: self.xml_ids,
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
//! a layout has its point type's anchor at its frame's point. See [`Story::place`].
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::{BezPath, CubicBez, ParamCurve, ParamCurveArclen};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
@@ -581,15 +582,20 @@ struct DocFont {
|
||||
/// Key 5, when the record keeps it: the font's version string (name ID 5), which tells installed
|
||||
/// copies of one font apart.
|
||||
version: Option<String>,
|
||||
/// [`Self::font`]'s answer, found once for every run that names the record.
|
||||
font: std::sync::OnceLock<Font>,
|
||||
/// The widths the file's page gives the font's characters, when it has them
|
||||
/// ([`Texts::with_page_widths`]): without a version, they tell the copies apart. Every record
|
||||
/// of the font shares them.
|
||||
widths: Option<Arc<vectorcraft_pdf::FontWidths>>,
|
||||
/// [`Self::font`]'s answer, found once for every run that names the record, and shared by the
|
||||
/// records of the same name and version, which give the same answer.
|
||||
font: Arc<std::sync::OnceLock<Font>>,
|
||||
}
|
||||
|
||||
impl DocFont {
|
||||
/// The font type set in this record's font takes: the installed copy it names
|
||||
/// ([`super::text::document_font`]).
|
||||
fn font(&self) -> &Font {
|
||||
self.font.get_or_init(|| super::text::document_font(&self.name, self.version.as_deref()))
|
||||
self.font.get_or_init(|| super::text::document_font(&self.name, self.version.as_deref(), self.widths.as_deref()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -639,6 +645,17 @@ impl Texts {
|
||||
Texts { paints, ..self }
|
||||
}
|
||||
|
||||
/// The text document with the widths `page` (the file's page, [`vectorcraft_pdf::PageWidths`])
|
||||
/// gives the characters of its fonts, by each record's PostScript name: a record that keeps no
|
||||
/// version is set in the installed copy of its font that sets them at those widths
|
||||
/// ([`super::text::postscript_face`]).
|
||||
pub(super) fn with_page_widths(mut self, page: &vectorcraft_pdf::PageWidths) -> Texts {
|
||||
for f in &mut self.fonts {
|
||||
f.widths = page.widths(super::text::bare_name(&f.name)).cloned();
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// The text document in the editing copy `data`, if it has one that can be read.
|
||||
pub(super) fn read(data: &[u8]) -> Option<Texts> {
|
||||
fn find(h: &[u8], n: &[u8], from: usize) -> Option<usize> {
|
||||
@@ -666,6 +683,8 @@ impl Texts {
|
||||
return None;
|
||||
}
|
||||
let doc = names::numbered(read(&bytes)?);
|
||||
// Records of one name and version share their answer.
|
||||
let mut answers: HashMap<(String, Option<String>), Arc<std::sync::OnceLock<Font>>> = HashMap::new();
|
||||
let fonts = doc
|
||||
.get("0")?
|
||||
.get("1")?
|
||||
@@ -675,11 +694,10 @@ impl Texts {
|
||||
.map(|f| {
|
||||
let record = f.get("0").and_then(|f| f.get("0"));
|
||||
let text = |k: &str| record.and_then(|r| r.get(k)).and_then(Val::str);
|
||||
DocFont {
|
||||
name: text("0").unwrap_or_default().to_string(),
|
||||
version: text("5").and_then(record_version).map(str::to_string),
|
||||
font: std::sync::OnceLock::new(),
|
||||
}
|
||||
let name = text("0").unwrap_or_default().to_string();
|
||||
let version = text("5").and_then(record_version).map(str::to_string);
|
||||
let font = answers.entry((name.clone(), version.clone())).or_default().clone();
|
||||
DocFont { name, version, widths: None, font }
|
||||
})
|
||||
.collect();
|
||||
let main = doc.get("1")?;
|
||||
@@ -1653,6 +1671,40 @@ fn art_scale(to_doc: Affine) -> f64 {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The records of a text document's font list that name one font share the widths the file's
|
||||
/// page gives it and the face they resolve to, however many there are: 20,000 records of a font
|
||||
/// whose page gives 4,096 characters hold one copy of those widths, and resolve once. A record
|
||||
/// of another version is resolved apart.
|
||||
#[test]
|
||||
fn records_of_one_font_share_its_page_widths_and_answer() {
|
||||
let n = 20_000;
|
||||
let records = "<< /0 << /0 << /0 (Sharetest-Regular) >> >> >> ".repeat(n) + "<< /0 << /0 << /0 (Sharetest-Regular) /5 (2.0) >> >> >>";
|
||||
let doc = format!("/0 << /1 << /0 [ {records} ] >> /8 << /0 [ ] >> >>\n/1 << /1 [ ] /2 << >> >>\n");
|
||||
let data =
|
||||
format!("%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n", crate::ps::ascii85(doc.as_bytes()));
|
||||
let mut cmap = String::from("begincmap\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n16 beginbfrange\n");
|
||||
for hi in 1..=16u32 {
|
||||
cmap.push_str(&format!("<{hi:02X}00> <{hi:02X}FF> <{hi:02X}00>\n"));
|
||||
}
|
||||
cmap.push_str("endbfrange\nendcmap\n");
|
||||
let extra = vectorcraft_testkit::pdf::first_extra(1);
|
||||
let font = format!(
|
||||
"/Font << /F1 << /Type /Font /Subtype /Type0 /BaseFont /ABCDEF+Sharetest-Regular /Encoding /Identity-H /ToUnicode {extra} 0 R \
|
||||
/DescendantFonts [<< /Type /Font /Subtype /CIDFontType2 /BaseFont /ABCDEF+Sharetest-Regular /W [256 4351 500] >>] >> >>"
|
||||
);
|
||||
let page = vectorcraft_testkit::pdf::PdfPage { resources: font, ..vectorcraft_testkit::pdf::PdfPage::new(100.0, 100.0, "") };
|
||||
let pdf = vectorcraft_testkit::pdf::pdf_with(&[page], &[&format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len())], None);
|
||||
let widths = vectorcraft_pdf::open_pdf(&pdf, None).unwrap().page_widths();
|
||||
let shared = widths.widths("Sharetest-Regular").unwrap();
|
||||
assert_eq!(shared.len(), 4096);
|
||||
let texts = Texts::read(data.as_bytes()).unwrap().with_page_widths(&widths);
|
||||
assert_eq!(texts.fonts.len(), n + 1);
|
||||
assert!(texts.fonts.iter().all(|f| f.widths.as_ref().is_some_and(|w| Arc::ptr_eq(w, shared))));
|
||||
let first = &texts.fonts[0].font;
|
||||
assert!(texts.fonts[..n].iter().all(|f| Arc::ptr_eq(&f.font, first)));
|
||||
assert!(texts.fonts.last().is_some_and(|f| !Arc::ptr_eq(&f.font, first)), "another version resolves apart");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn right_to_left_paragraphs_swap_left_and_right_alignment() {
|
||||
let texts = Texts {
|
||||
|
||||
@@ -178,17 +178,25 @@ impl ReadText {
|
||||
self.frames.get_or_insert_with(|| ai::text_frames(data))
|
||||
}
|
||||
|
||||
/// The text document of `data` ([`Texts::read`]), if it has one that can be read.
|
||||
fn texts(&mut self, data: &[u8]) -> Option<&Texts> {
|
||||
/// The text document of `data` ([`Texts::read`]), if it has one that can be read, with the widths
|
||||
/// `page_widths` the file's page gives its fonts ([`Texts::with_page_widths`]). They are given
|
||||
/// when it is first read, before any of its fonts is found: each is found once, with the widths
|
||||
/// it has then. Every check and build of one open passes the same widths.
|
||||
fn texts(&mut self, data: &[u8], page_widths: &vectorcraft_pdf::PageWidths) -> Option<&Texts> {
|
||||
self.forget_in_tests();
|
||||
self.texts.get_or_insert_with(|| Texts::read(data)).as_ref()
|
||||
self.texts.get_or_insert_with(|| Texts::read(data).map(|t| t.with_page_widths(page_widths))).as_ref()
|
||||
}
|
||||
|
||||
/// [`Self::texts`] with its characters painted by `paints` ([`Texts::with_paints`]).
|
||||
fn texts_with(&mut self, data: &[u8], paints: std::collections::HashMap<String, vectorcraft_color::Paint>) -> Option<&Texts> {
|
||||
fn texts_with(
|
||||
&mut self,
|
||||
data: &[u8],
|
||||
paints: std::collections::HashMap<String, vectorcraft_color::Paint>,
|
||||
page_widths: &vectorcraft_pdf::PageWidths,
|
||||
) -> Option<&Texts> {
|
||||
self.forget_in_tests();
|
||||
let texts = self.texts.take().unwrap_or_else(|| Texts::read(data)).map(|t| t.with_paints(paints));
|
||||
self.texts.insert(texts).as_ref()
|
||||
let read = self.texts.take().unwrap_or_else(|| Texts::read(data).map(|t| t.with_page_widths(page_widths)));
|
||||
self.texts.insert(read.map(|t| t.with_paints(paints))).as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -217,7 +225,7 @@ fn type_all_made(structure: &Structure, data: &[u8], text: &mut ReadText) -> boo
|
||||
for info in &mut infos {
|
||||
info.art_path = info.story.and_then(|s| frames.get(&(s, info.frame))).map(|p| PathData::from_bezpath(&(structure.to_doc * p.clone())));
|
||||
}
|
||||
let Some(texts) = text.texts(data) else { return false };
|
||||
let Some(texts) = text.texts(data, &structure.page_widths) else { return false };
|
||||
let mut read: std::collections::BTreeMap<u32, Option<Arc<Story>>> = Default::default();
|
||||
let stories: Vec<Option<Arc<Story>>> = infos
|
||||
.iter()
|
||||
@@ -338,6 +346,7 @@ pub(super) fn build_weighing(
|
||||
envelopes_drawn,
|
||||
styles_read,
|
||||
text_paints,
|
||||
page_widths,
|
||||
canvas_scale,
|
||||
symbols_own_size,
|
||||
xml_ids,
|
||||
@@ -498,7 +507,7 @@ pub(super) fn build_weighing(
|
||||
// The page's type that needs no text object of the layers: the layers' own legacy text, or
|
||||
// placed files that show it.
|
||||
let as_outlines = page_type_elsewhere(infos.is_empty(), infos.iter().all(|i| !i.shown), &mut shown, &mut hidden, &doc, &placed_elsewhere)?;
|
||||
let texts = text.texts_with(data, text_paints);
|
||||
let texts = text.texts_with(data, text_paints, &page_widths);
|
||||
// Each story is read once, however many text objects name it.
|
||||
let mut read: std::collections::BTreeMap<u32, Option<Arc<Story>>> = Default::default();
|
||||
let stories: Vec<Option<Arc<Story>>> = infos
|
||||
|
||||
@@ -149,7 +149,7 @@ pub fn layered_ai_from(
|
||||
all.push(format!("{LAYERS_UNREAD} from its editing data ({why}): they come from its PDF part"));
|
||||
all
|
||||
};
|
||||
let AiLayers { data, structure, alone, mut text } = layers;
|
||||
let AiLayers { data, structure, alone, mut text, page_widths } = layers;
|
||||
let data = match data {
|
||||
Ok(data) => data,
|
||||
Err(why) => return (visible, unread(warnings, &why), false),
|
||||
@@ -189,10 +189,17 @@ pub fn layered_ai_from(
|
||||
add_notes(&mut all, read.notes());
|
||||
(visible, all, false)
|
||||
};
|
||||
// The layers read, with the widths the PDF part gives the characters of its fonts.
|
||||
let read = || {
|
||||
ai::read_over_page(&data, false, names).map(|mut structure| {
|
||||
structure.page_widths = page_widths.clone();
|
||||
structure
|
||||
})
|
||||
};
|
||||
// The envelopes of type the page doesn't hold against layers that don't draw as it, and how many
|
||||
// envelopes of type the layers had.
|
||||
let (mut free, mut count) = (None, 0);
|
||||
let built = structure.unwrap_or_else(|| ai::read_over_page(&data, false, names).map(Box::new)).and_then(|structure| {
|
||||
let built = structure.unwrap_or_else(|| read().map(Box::new)).and_then(|structure| {
|
||||
count = structure.warped_type.envelope_count();
|
||||
build_weighing(*structure, &data, Some(&visible), Page::Artboard, outlined, trust, unit, &mut free, &mut text)
|
||||
});
|
||||
@@ -205,7 +212,7 @@ pub fn layered_ai_from(
|
||||
let live = free.is_none() && matches!(&built, Ok((done, _)) if holds_type_envelope(&done.layers));
|
||||
if !live
|
||||
&& let Some((mut done, notes)) = alone.and_then(|(pages, unit)| {
|
||||
let mut structure = ai::read_over_page(&data, false, names).ok()?;
|
||||
let mut structure = read().ok()?;
|
||||
// With none free, nothing needs settling again: every envelope keeps its drawn art.
|
||||
if let Some(free) = free.as_deref().filter(|free| !free.is_empty()) {
|
||||
structure.warped_type.open_alone(free, count);
|
||||
@@ -244,9 +251,17 @@ fn holds_type_envelope(nodes: &[Arc<Node>]) -> bool {
|
||||
/// reading it, when the file's text document makes all of its type and nothing in its layers needs
|
||||
/// the PDF part (see `build_without_page`). Nothing is compared with the PDF part. Else, as the
|
||||
/// error, what was decoded and read of the editing copy, for [`layered_ai_from`] once the PDF part
|
||||
/// is imported. `names`: the encoding of names that aren't UTF-8.
|
||||
pub fn ai_layers_alone(private: &[u8], pages: &[(f64, f64)], unit: f64, names: ai::NameEncoding) -> Result<(Document, Vec<String>), AiLayers> {
|
||||
ai_layers_alone_decoded(ai::decode_private(private), pages, unit, names)
|
||||
/// is imported. `names`: the encoding of names that aren't UTF-8. `page_widths`: the widths the
|
||||
/// PDF part gives the characters of its fonts, which tell installed copies of a font apart
|
||||
/// ([`AiLayers::with_page_widths`]).
|
||||
pub fn ai_layers_alone(
|
||||
private: &[u8],
|
||||
pages: &[(f64, f64)],
|
||||
unit: f64,
|
||||
names: ai::NameEncoding,
|
||||
page_widths: vectorcraft_pdf::PageWidths,
|
||||
) -> Result<(Document, Vec<String>), AiLayers> {
|
||||
ai_layers_alone_decoded(ai::decode_private(private), pages, unit, names, page_widths)
|
||||
}
|
||||
|
||||
/// [`ai_layers_alone`] of an editing copy already decoded (`decoded`, as [`decode_ai_private`]
|
||||
@@ -256,31 +271,33 @@ pub fn ai_layers_alone_decoded(
|
||||
pages: &[(f64, f64)],
|
||||
unit: f64,
|
||||
names: ai::NameEncoding,
|
||||
page_widths: vectorcraft_pdf::PageWidths,
|
||||
) -> Result<(Document, Vec<String>), AiLayers> {
|
||||
let data = match decoded {
|
||||
Ok(data) => data,
|
||||
Err(why) => return Err(AiLayers { data: Err(why), structure: None, alone: None, text: Box::default() }),
|
||||
Err(why) => return Err(AiLayers { data: Err(why), structure: None, alone: None, text: Box::default(), page_widths }),
|
||||
};
|
||||
if !has_layers(&data) {
|
||||
return Err(AiLayers { data: Ok(data), structure: None, alone: None, text: Box::default() });
|
||||
return Err(AiLayers { data: Ok(data), structure: None, alone: None, text: Box::default(), page_widths });
|
||||
}
|
||||
// An image past the hard limits is read as an unread box, which the PDF part's art replaces.
|
||||
let structure = match ai::read_over_page(&data, false, names) {
|
||||
let mut structure = match ai::read_over_page(&data, false, names) {
|
||||
Ok(structure) => structure,
|
||||
Err(why) => return Err(AiLayers { data: Ok(data), structure: Some(Err(why)), alone: None, text: Box::default() }),
|
||||
Err(why) => return Err(AiLayers { data: Ok(data), structure: Some(Err(why)), alone: None, text: Box::default(), page_widths }),
|
||||
};
|
||||
structure.page_widths = page_widths.clone();
|
||||
let mut text = Box::<ReadText>::default();
|
||||
// An envelope of type opens live only where the layers with it draw as the page, as the other
|
||||
// live envelopes do: the PDF part is imported to compare them with. Should none open live, the
|
||||
// layers open alone as they would have, the envelopes keeping their drawn art ([`layered_ai_from`]).
|
||||
if structure.warped_type.has_envelopes() && alone_scale(&structure, &data, pages, unit, &mut text).is_some() {
|
||||
let alone = Some((pages.to_vec(), unit));
|
||||
return Err(AiLayers { data: Ok(data), structure: Some(Ok(Box::new(structure))), alone, text });
|
||||
return Err(AiLayers { data: Ok(data), structure: Some(Ok(Box::new(structure))), alone, text, page_widths });
|
||||
}
|
||||
match build_without_page(structure, &data, pages, unit, &mut text) {
|
||||
Ok(Ok((doc, notes))) => Ok((doc, notes)),
|
||||
Ok(_) => Err(AiLayers { data: Ok(data), structure: None, alone: None, text }),
|
||||
Err(structure) => Err(AiLayers { data: Ok(data), structure: Some(Ok(structure)), alone: None, text }),
|
||||
Ok(_) => Err(AiLayers { data: Ok(data), structure: None, alone: None, text, page_widths }),
|
||||
Err(structure) => Err(AiLayers { data: Ok(data), structure: Some(Ok(structure)), alone: None, text, page_widths }),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -297,6 +314,8 @@ pub struct AiLayers {
|
||||
alone: Option<(Vec<(f64, f64)>, f64)>,
|
||||
/// The text objects' frames and the text document of the editing copy, as far as they were read.
|
||||
text: Box<ReadText>,
|
||||
/// The widths the PDF part gives the characters of its fonts ([`Self::with_page_widths`]).
|
||||
page_widths: vectorcraft_pdf::PageWidths,
|
||||
}
|
||||
|
||||
impl AiLayers {
|
||||
@@ -308,7 +327,20 @@ impl AiLayers {
|
||||
/// An editing copy already decoded (`decoded`, as [`decode_ai_private`] gives it, or why it
|
||||
/// can't be).
|
||||
pub fn decoded(decoded: Result<Vec<u8>, String>) -> Self {
|
||||
Self { data: decoded, structure: None, alone: None, text: Box::default() }
|
||||
Self { data: decoded, structure: None, alone: None, text: Box::default(), page_widths: Default::default() }
|
||||
}
|
||||
|
||||
/// The editing copy with `page_widths`, the widths the file's PDF part gives the characters of
|
||||
/// its fonts ([`vectorcraft_pdf::Opened::page_widths`]): type whose font record keeps no
|
||||
/// version is set in the installed copy of its font that sets them at those widths, where
|
||||
/// several copies answer to its name. The layers read before take them too, and a text document
|
||||
/// read before is read again with them, since its fonts are found once, with the widths they had
|
||||
/// then.
|
||||
pub fn with_page_widths(mut self, page_widths: vectorcraft_pdf::PageWidths) -> Self {
|
||||
if let Some(Ok(structure)) = &mut self.structure {
|
||||
structure.page_widths = page_widths.clone();
|
||||
}
|
||||
Self { page_widths, text: Box::default(), ..self }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -610,17 +642,21 @@ fn place_art(layer: &mut Node, pages: &[Rect], moves: &[Vec2]) {
|
||||
/// Editing data written on a large canvas comes in at its declared scale: no page holds the size.
|
||||
/// Names that aren't UTF-8 are read as Windows-1252 ([`ai_alone_with`]).
|
||||
pub fn ai_alone(private: &[u8]) -> Result<(Document, Vec<String>), String> {
|
||||
ai_alone_with(private, ai::NameEncoding::default())
|
||||
ai_alone_with(private, ai::NameEncoding::default(), Default::default())
|
||||
}
|
||||
|
||||
/// [`ai_alone`], with the names that aren't UTF-8 read in `names`.
|
||||
pub fn ai_alone_with(private: &[u8], names: ai::NameEncoding) -> Result<(Document, Vec<String>), String> {
|
||||
ai_alone_decoded(&ai::decode_private(private)?, names)
|
||||
/// [`ai_alone`], with the names that aren't UTF-8 read in `names`, and `page_widths`, the widths the
|
||||
/// file's PDF part gives the characters of its fonts when it has one that holds the art
|
||||
/// ([`AiLayers::with_page_widths`]).
|
||||
pub fn ai_alone_with(private: &[u8], names: ai::NameEncoding, page_widths: vectorcraft_pdf::PageWidths) -> Result<(Document, Vec<String>), String> {
|
||||
ai_alone_decoded(&ai::decode_private(private)?, names, page_widths)
|
||||
}
|
||||
|
||||
/// [`ai_alone_with`] of an editing copy already decoded (`data`, as [`decode_ai_private`] gives it).
|
||||
pub fn ai_alone_decoded(data: &[u8], names: ai::NameEncoding) -> Result<(Document, Vec<String>), String> {
|
||||
build_from(ai::read_in(data, true, names)?, data, None, Page::Artboard, false, false, 1.0)
|
||||
pub fn ai_alone_decoded(data: &[u8], names: ai::NameEncoding, page_widths: vectorcraft_pdf::PageWidths) -> Result<(Document, Vec<String>), String> {
|
||||
let mut structure = ai::read_in(data, true, names)?;
|
||||
structure.page_widths = page_widths;
|
||||
build_from(structure, data, None, Page::Artboard, false, false, 1.0)
|
||||
}
|
||||
|
||||
/// [`ai_alone`] for a `.ai` whose PDF part can't be read, its first page `page` (width and height)
|
||||
|
||||
@@ -3452,6 +3452,105 @@ fn type_from_the_text_document_takes_the_version_its_font_record_keeps() {
|
||||
assert_eq!(version("/0 (VertestInk-Regular) /VersionString (1.1)"), "1.1");
|
||||
}
|
||||
|
||||
/// The widths a `.ai`'s PDF part gives the characters of `text` in its font `name` (a subset of
|
||||
/// it, a TrueType font in `WinAnsiEncoding`): those `width` gives each, in thousandths of an em.
|
||||
fn page_widths(name: &str, text: &str, width: impl Fn(char) -> f64) -> vectorcraft_pdf::PageWidths {
|
||||
let widths: Vec<String> = (32u8..=126).map(char::from).map(|c| if text.contains(c) { width(c).to_string() } else { "0".into() }).collect();
|
||||
let font = format!(
|
||||
"/Font << /F1 << /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+{name} /FirstChar 32 /Widths [{}] /Encoding /WinAnsiEncoding >> >>",
|
||||
widths.join(" ")
|
||||
);
|
||||
let page = vectorcraft_testkit::pdf::PdfPage { resources: font, ..vectorcraft_testkit::pdf::PdfPage::new(100.0, 100.0, "") };
|
||||
vectorcraft_pdf::open_pdf(&vectorcraft_testkit::pdf::pdf_with(&[page], &[], None), None).unwrap().page_widths()
|
||||
}
|
||||
|
||||
/// [`page_widths`] of a composite font (`Identity-H`, a TrueType CIDFont) whose `ToUnicode` map gives
|
||||
/// CID 1 the first character of `text`, CID 2 the next and so on, `W` their widths.
|
||||
fn page_widths_cid(name: &str, text: &str, width: impl Fn(char) -> f64) -> vectorcraft_pdf::PageWidths {
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
let pairs: Vec<String> = chars.iter().enumerate().map(|(i, c)| format!("<{:04X}> <{:04X}>", i + 1, u32::from(*c))).collect();
|
||||
let cmap = format!(
|
||||
"begincmap\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n{} beginbfchar\n{}\nendbfchar\nendcmap\n",
|
||||
pairs.len(),
|
||||
pairs.join("\n")
|
||||
);
|
||||
let w: Vec<String> = chars.iter().map(|c| width(*c).to_string()).collect();
|
||||
let extra = vectorcraft_testkit::pdf::first_extra(1);
|
||||
let font = format!(
|
||||
"/Font << /F1 << /Type /Font /Subtype /Type0 /BaseFont /ABCDEF+{name}-Identity-H /Encoding /Identity-H /ToUnicode {extra} 0 R \
|
||||
/DescendantFonts [<< /Type /Font /Subtype /CIDFontType2 /BaseFont /ABCDEF+{name} /W [1 [{}]] >>] >> >>",
|
||||
w.join(" ")
|
||||
);
|
||||
let page = vectorcraft_testkit::pdf::PdfPage { resources: font, ..vectorcraft_testkit::pdf::PdfPage::new(100.0, 100.0, "") };
|
||||
let file = vectorcraft_testkit::pdf::pdf_with(&[page], &[&format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len())], None);
|
||||
vectorcraft_pdf::open_pdf(&file, None).unwrap().page_widths()
|
||||
}
|
||||
|
||||
/// The advance of `c` in installed `face`, in thousandths of an em.
|
||||
fn advance(face: &vectorcraft_text::FontFace, c: char) -> f64 {
|
||||
face.advance(face.glyph_for(c)) * 1000.0 / face.units_per_em()
|
||||
}
|
||||
|
||||
/// The version of the face that type from the text document of a `.ai` whose font record is
|
||||
/// `record` (in place of `/0 (Helvetica)`) is set in, its layers read alone with `widths`, the
|
||||
/// widths its PDF part gives the characters of its fonts.
|
||||
fn version_on_page(record: &str, widths: vectorcraft_pdf::PageWidths) -> String {
|
||||
let doc = text_document(&[("Hamburg\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]).replacen("/0 (Helvetica)", record, 1);
|
||||
let file = private(&native_with_text(&layer("Art", true, &text_object(0)), &doc));
|
||||
let names = crate::NameEncoding::default();
|
||||
let Ok((d, notes)) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, widths) else { panic!("{record}: opened with the page") };
|
||||
let texts = text_of(&d.layers[0]);
|
||||
assert_eq!(texts.len(), 1, "{record}: {notes:?}");
|
||||
vectorcraft_text::FontDb::global().style_face(&texts[0].runs[0].style).unwrap().version.clone()
|
||||
}
|
||||
|
||||
/// Two installed copies of one font can share its PostScript name, family and style, and differ
|
||||
/// in their glyphs' widths alone. Type from the text document of a `.ai` whose font record keeps no
|
||||
/// version is set in the copy that sets the characters its PDF part draws at the widths the PDF
|
||||
/// part gives them, also when the record spells the name with other punctuation. Without those
|
||||
/// widths, or when no copy sets the characters at them, it takes the copy it took before (the first
|
||||
/// loaded); a version the record keeps decides first. The widths of a simple font in
|
||||
/// `WinAnsiEncoding` and of a composite font with a `ToUnicode` map both tell the copies apart.
|
||||
#[test]
|
||||
fn type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths() {
|
||||
install(&[(true, ("Widtest Ink", "Regular", "1.0", "WidtestInk-Regular")), (false, ("Widtest Ink", "Regular", "1.1", "WidtestInk-Regular"))]);
|
||||
let copies = vectorcraft_text::FontDb::global().postscript_faces("WidtestInk-Regular");
|
||||
let copy = |version: &str| copies.iter().find(|f| f.version == version).unwrap().clone();
|
||||
let (old, new) = (copy("1.0"), copy("1.1"));
|
||||
assert!((advance(&old, 'H') - advance(&new, 'H')).abs() > 10.0, "the copies set the type at other widths");
|
||||
let on = |name: &str, face: &vectorcraft_text::FontFace| page_widths(name, "Hamburg", |c| advance(face, c));
|
||||
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", Default::default()), "1.0");
|
||||
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", on("WidtestInk-Regular", &new)), "1.1");
|
||||
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", on("WidtestInk-Regular", &old)), "1.0");
|
||||
// Widths a file rounds are within 1/1000 em of the advances; farther off, they aren't the copy's.
|
||||
let off = |by: f64| page_widths("WidtestInk-Regular", "Hamburg", |c| advance(&new, c) + by);
|
||||
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", off(0.9)), "1.1");
|
||||
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", off(-0.9)), "1.1");
|
||||
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", off(2.0)), "1.0");
|
||||
// A record whose name differs from the copies' in punctuation alone, as its PDF part's font.
|
||||
assert_eq!(version_on_page("/0 (Widtest-Ink-Regular)", on("Widtest-Ink-Regular", &new)), "1.1");
|
||||
// Widths of another font, or no copy setting the characters at the PDF part's widths.
|
||||
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", on("OtherInk-Regular", &new)), "1.0");
|
||||
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", page_widths("WidtestInk-Regular", "Hamburg", |_| 1000.0)), "1.0");
|
||||
// A version the record keeps picks the copy, and one that isn't installed gives the copy it gave.
|
||||
assert_eq!(version_on_page("/0 (WidtestInk-Regular) /5 (1.0)", on("WidtestInk-Regular", &new)), "1.0");
|
||||
assert_eq!(version_on_page("/0 (WidtestInk-Regular) /5 (9.9)", on("WidtestInk-Regular", &new)), "1.0");
|
||||
// The widths of a composite font.
|
||||
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", page_widths_cid("WidtestInk-Regular", "Hamburg", |c| advance(&new, c))), "1.1");
|
||||
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", page_widths_cid("WidtestInk-Regular", "Hamburg", |c| advance(&old, c))), "1.0");
|
||||
// A font installed once is set in that copy whatever the widths.
|
||||
install(&[(true, ("Onewtest Ink", "Regular", "1.0", "OnewtestInk-Regular"))]);
|
||||
assert_eq!(version_on_page("/0 (OnewtestInk-Regular)", on("OnewtestInk-Regular", &new)), "1.0");
|
||||
// Of several copies that set the characters at the widths, the first in the order the faces
|
||||
// are found (the first loaded).
|
||||
install(&[
|
||||
(true, ("Firstwtest Ink", "Regular", "1.0", "FirstwtestInk-Regular")),
|
||||
(false, ("Firstwtest Ink", "Regular", "1.1", "FirstwtestInk-Regular")),
|
||||
(false, ("Firstwtest Ink", "Regular", "1.2", "FirstwtestInk-Regular")),
|
||||
]);
|
||||
assert_eq!(version_on_page("/0 (FirstwtestInk-Regular)", on("FirstwtestInk-Regular", &new)), "1.1");
|
||||
}
|
||||
|
||||
/// A story with no runs, and a run or paragraph that names no style, is set in `[Normal Character
|
||||
/// Style]` and `[Normal Paragraph Style]` before the text document's base attributes. A Large
|
||||
/// Canvas copy (1:10) writes the styles at the art's scale (1.2 for 12 points, 0.6 for a 6-point
|
||||
@@ -6490,7 +6589,7 @@ fn an_envelope_of_type_waits_on_the_page_of_layers_that_would_open_alone() {
|
||||
let art = format!("u\n{}U\n{}", text_object(1), type_envelope(&arc_keys(0.3), &drawn));
|
||||
let file = private(&native_with_text(&layer("Art", true, &art), &doc));
|
||||
let names = crate::NameEncoding::default();
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
|
||||
// A PDF part the layers don't draw as.
|
||||
let (d, notes, read) = crate::layered_ai_from(layers, pdf_part(80.0, 80.0), vec![], false, false, 1.0, names);
|
||||
assert!(read, "{notes:?}");
|
||||
@@ -6499,7 +6598,7 @@ fn an_envelope_of_type_waits_on_the_page_of_layers_that_would_open_alone() {
|
||||
assert_eq!(loose, [("Note".to_string(), true), ("FLUX".to_string(), false)], "{notes:?}");
|
||||
assert!(notes.iter().any(|n| n == crate::import::ai::ENVELOPE_TYPE_DRAWN), "{notes:?}");
|
||||
// A PDF part that draws as those layers, with the drawn art: the envelope opens live.
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
|
||||
let (d, notes, read) = crate::layered_ai_from(layers, d, vec![], false, false, 1.0, names);
|
||||
assert!(read, "{notes:?}");
|
||||
let (envelopes, loose) = envelopes_and_type(&d);
|
||||
@@ -6527,7 +6626,7 @@ fn layers_that_open_alone_read_their_text_once() {
|
||||
let doc = unsplit_text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Mid\r", 2, (8191.5, 8191.5), (0.0, 0.0), -10.0)]);
|
||||
let art = layer("Art", true, &format!("{}\n{}{}", square(10, 10), text_object(0), text_object(1)));
|
||||
let file = private(&native_with_text(&art, &doc));
|
||||
let open = || crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, crate::NameEncoding::default()).ok();
|
||||
let open = || crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, crate::NameEncoding::default(), Default::default()).ok();
|
||||
let (opened, texts, frames) = text_reads(false, open);
|
||||
let Some((d, notes)) = opened else { panic!("didn't open without the page") };
|
||||
assert_eq!((texts, frames), (1, 1), "{notes:?}");
|
||||
@@ -6546,7 +6645,7 @@ fn layers_whose_text_document_cannot_be_read_read_it_once_with_the_page() {
|
||||
let file = private(&native_with_text(&art, "not a text document"));
|
||||
let names = crate::NameEncoding::default();
|
||||
let open = || {
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
|
||||
crate::layered_ai_from(layers, pdf_part(10.0, 86.0), vec![], false, false, 1.0, names)
|
||||
};
|
||||
let (opened, texts, frames) = text_reads(false, open);
|
||||
@@ -6573,7 +6672,7 @@ fn an_envelope_of_type_waiting_on_the_page_reads_the_text_once() {
|
||||
let file = private(&native_with_text(&layer("Art", true, &art), &doc));
|
||||
let names = crate::NameEncoding::default();
|
||||
let open = |page: Document| {
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
|
||||
crate::layered_ai_from(layers, page, vec![], false, false, 1.0, names)
|
||||
};
|
||||
// A PDF part the layers don't draw as: they open alone, after a build with the page and one without.
|
||||
@@ -6657,7 +6756,7 @@ fn trusted_layers_that_draw_apart_from_the_page_leave_an_envelope_of_type_its_dr
|
||||
let art = format!("u\n{}U\n{}", text_object(1), type_envelope(&arc_keys(0.3), &drawn));
|
||||
let file = private(&native_with_text(&layer("Art", true, &art), &doc));
|
||||
let names = crate::NameEncoding::default();
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
|
||||
let (d, notes, read) = crate::layered_ai_from(layers, pdf_part(80.0, 80.0), vec![], false, true, 1.0, names);
|
||||
assert!(read, "{notes:?}");
|
||||
let (envelopes, loose) = envelopes_and_type(&d);
|
||||
@@ -6751,7 +6850,7 @@ fn layers_that_would_open_alone_keep_an_envelope_of_type_live_where_other_art_di
|
||||
let file = private(&native_with_text(&layer("Art", true, &art), &doc));
|
||||
let names = crate::NameEncoding::default();
|
||||
let open = |page: Document| {
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
|
||||
crate::layered_ai_from(layers, page, vec![], false, false, 1.0, names)
|
||||
};
|
||||
// The layers alone, with the envelope's drawn art: what the page draws.
|
||||
@@ -6794,7 +6893,7 @@ fn trusted_layers_that_would_open_alone_open_alone_with_an_envelope_of_type_the_
|
||||
let file = private(&native_with_text(&layer("Art", true, &art), &doc));
|
||||
let names = crate::NameEncoding::default();
|
||||
let open = |page: Document, trust: bool| {
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
|
||||
crate::layered_ai_from(layers, page, vec![], false, trust, 1.0, names)
|
||||
};
|
||||
let (mut page, _, _) = open(pdf_part(80.0, 80.0), false);
|
||||
@@ -6833,7 +6932,7 @@ fn layers_that_would_open_alone_keep_live_only_the_envelopes_of_type_the_page_do
|
||||
let file = private(&native_with_text(&layer("Art", true, &art), &doc));
|
||||
let names = crate::NameEncoding::default();
|
||||
let open = |page: Document| {
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
|
||||
crate::layered_ai_from(layers, page, vec![], false, false, 1.0, names)
|
||||
};
|
||||
// The layers alone, with the drawn art of both envelopes, but the first's: the page draws
|
||||
|
||||
@@ -44,7 +44,7 @@ fn style_word(w: &str) -> String {
|
||||
|
||||
/// A font's PostScript name without a subset prefix (`ABCDEF+`) or the `*1` of a re-encoded copy
|
||||
/// (`ABCDEF+RollerBabyBV*1` is `RollerBabyBV`).
|
||||
fn bare_name(name: &str) -> &str {
|
||||
pub(super) fn bare_name(name: &str) -> &str {
|
||||
let name = match name.split_once('+') {
|
||||
Some((prefix, rest)) if prefix.len() == 6 && prefix.bytes().all(|b| b.is_ascii_uppercase()) => rest,
|
||||
_ => name,
|
||||
@@ -56,14 +56,15 @@ fn bare_name(name: &str) -> &str {
|
||||
}
|
||||
|
||||
/// The font of type that a text document's font record names: by `name`, its PostScript name, and
|
||||
/// `version`, the version string (name ID 5) the record keeps, if any. An installed face of that
|
||||
/// name gives its font ([`named_font`]). Without one, `name` is split ([`family_style`]) and the
|
||||
/// family spelled as an available family is ([`FontDb::find_family`]: `MicrosoftYaHei` is
|
||||
/// `version`, the version string (name ID 5) the record keeps, if any; `widths`, the widths the
|
||||
/// file's page gives the font's characters, if it has them ([`postscript_face`]). An installed face
|
||||
/// of that name gives its font ([`named_font`]). Without one, `name` is split ([`family_style`])
|
||||
/// and the family spelled as an available family is ([`FontDb::find_family`]: `MicrosoftYaHei` is
|
||||
/// Microsoft YaHei). → (family, style, version).
|
||||
///
|
||||
/// [`FontDb::find_family`]: vectorcraft_text::FontDb::find_family
|
||||
pub(crate) fn document_font(name: &str, version: Option<&str>) -> (String, String, Option<String>) {
|
||||
named_font(name, version).unwrap_or_else(|| {
|
||||
pub(crate) fn document_font(name: &str, version: Option<&str>, widths: Option<&vectorcraft_pdf::FontWidths>) -> (String, String, Option<String>) {
|
||||
named_font(name, version, widths).unwrap_or_else(|| {
|
||||
let (family, style) = family_style(name);
|
||||
let family = vectorcraft_text::FontDb::global().find_family(&family).unwrap_or(family);
|
||||
(family, style, None)
|
||||
@@ -71,37 +72,69 @@ pub(crate) fn document_font(name: &str, version: Option<&str>) -> (String, Strin
|
||||
}
|
||||
|
||||
/// The font of type set in the installed face of PostScript name `name` (a subset prefix and a
|
||||
/// re-encoded copy's `*1` aside) in `version` ([`postscript_face`]): that face's own family and
|
||||
/// style, and its version when the family and style alone resolve to another installed copy of
|
||||
/// the font. A library can keep two copies under one family and style that differ in their
|
||||
/// PostScript names or their versions, and draw the same text at different widths. → (family,
|
||||
/// style, version); `None` when no installed face has the name.
|
||||
pub(crate) fn named_font(name: &str, version: Option<&str>) -> Option<(String, String, Option<String>)> {
|
||||
let face = postscript_face(bare_name(name), version)?;
|
||||
/// re-encoded copy's `*1` aside) in `version`, or that sets the characters at `widths`
|
||||
/// ([`postscript_face`]): that face's own family and style, and its version when the family and
|
||||
/// style alone resolve to another installed copy of the font. A library can keep two copies under
|
||||
/// one family and style that differ in their PostScript names or their versions, and draw the same
|
||||
/// text at different widths. → (family, style, version); `None` when no installed face has the name.
|
||||
pub(crate) fn named_font(
|
||||
name: &str,
|
||||
version: Option<&str>,
|
||||
widths: Option<&vectorcraft_pdf::FontWidths>,
|
||||
) -> Option<(String, String, Option<String>)> {
|
||||
let face = postscript_face(bare_name(name), version, widths)?;
|
||||
// As the PDF import names a version: only one that the family and style don't resolve to.
|
||||
let default = vectorcraft_text::FontDb::global().face(&face.family, &face.style);
|
||||
let version = default.filter(|d| d.version != face.version).map(|_| face.version.clone());
|
||||
Some((face.family.clone(), face.style.clone(), version))
|
||||
}
|
||||
|
||||
/// How far an installed face's advance may be from the width a page gives a character, in
|
||||
/// thousandths of an em, for the face to set it at that width: files write widths rounded.
|
||||
const PAGE_WIDTH_SLACK: f64 = 1.0;
|
||||
|
||||
/// The most characters of a page's font [`sets_page_widths`] compares.
|
||||
const MAX_WIDTHS_COMPARED: usize = 512;
|
||||
|
||||
/// Does installed `face` set the characters of `widths` (a page's, [`vectorcraft_pdf::FontWidths`])
|
||||
/// at their widths, each within [`PAGE_WIDTH_SLACK`]? The first [`MAX_WIDTHS_COMPARED`] characters
|
||||
/// in code-point order are compared; a character the face has no glyph for isn't set at its width.
|
||||
fn sets_page_widths(face: &vectorcraft_text::FontFace, widths: &vectorcraft_pdf::FontWidths) -> bool {
|
||||
let k = 1000.0 / face.units_per_em();
|
||||
widths.iter().take(MAX_WIDTHS_COMPARED).all(|(c, w)| {
|
||||
let gid = face.glyph_for(*c);
|
||||
gid != 0 && (face.advance(gid) * k - f64::from(*w)).abs() <= PAGE_WIDTH_SLACK
|
||||
})
|
||||
}
|
||||
|
||||
/// The installed face of PostScript name `name` (without a subset prefix), among the installed
|
||||
/// faces that answer to it ([`FontDb::postscript_faces`]): those of exactly that name when there
|
||||
/// are any (PostScript names are case-sensitive, so `SampleSans` isn't the face named
|
||||
/// `SAMPLESANS`, and `SampleSerif-Bold` isn't `SampleSerifBold`), and of those the one in
|
||||
/// `version` when it is installed, else the first. `None` when no installed face has the name.
|
||||
/// `version` when it is installed. Without a version, copies whose names, family and style are all
|
||||
/// one can still set the type at other widths: of those, the first that sets the characters of
|
||||
/// `widths` (the file's page's, when it has them) at their widths ([`sets_page_widths`], which
|
||||
/// compares the first 512 characters). Else the first. `None` when no installed face has the name.
|
||||
///
|
||||
/// [`FontDb::postscript_faces`]: vectorcraft_text::FontDb::postscript_faces
|
||||
pub(crate) fn postscript_face(name: &str, version: Option<&str>) -> Option<Arc<vectorcraft_text::FontFace>> {
|
||||
pub(crate) fn postscript_face(
|
||||
name: &str,
|
||||
version: Option<&str>,
|
||||
widths: Option<&vectorcraft_pdf::FontWidths>,
|
||||
) -> Option<Arc<vectorcraft_text::FontFace>> {
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let found = db.find_postscript(name)?;
|
||||
if found.postscript_name() == name && version.is_none_or(|v| v == found.version) {
|
||||
let widths = widths.filter(|_| version.is_none());
|
||||
let on_page = |f: &vectorcraft_text::FontFace| widths.is_none_or(|w| sets_page_widths(f, w));
|
||||
if found.postscript_name() == name && version.is_none_or(|v| v == found.version) && on_page(&found) {
|
||||
return Some(found);
|
||||
}
|
||||
let faces = db.postscript_faces(name);
|
||||
let named: Vec<_> = faces.iter().filter(|f| f.postscript_name() == name).cloned().collect();
|
||||
let pool = if named.is_empty() { faces } else { named };
|
||||
let in_version = version.and_then(|v| pool.iter().find(|f| f.version == v).cloned());
|
||||
Some(in_version.or_else(|| pool.into_iter().next()).unwrap_or(found))
|
||||
let by_widths = || pool.iter().find(|f| on_page(f)).cloned();
|
||||
Some(in_version.or_else(by_widths).or_else(|| pool.into_iter().next()).unwrap_or(found))
|
||||
}
|
||||
|
||||
/// A font's family and style from its PostScript name, without a subset prefix (`ABCDEF+`) or the
|
||||
@@ -620,7 +653,7 @@ impl Interp<'_> {
|
||||
}
|
||||
// The installed face of that PostScript name, as type from a text document takes it; else
|
||||
// the available family's own spelling: `MicrosoftYaHei` is Microsoft YaHei, not "Microsoft Ya Hei".
|
||||
let (font_family, font_style, font_version) = document_font(&name, None);
|
||||
let (font_family, font_style, font_version) = document_font(&name, None, None);
|
||||
let fill = if self.g.paint.is_none() { Paint::solid(vectorcraft_color::Color::BLACK) } else { self.g.paint.clone() };
|
||||
let style = CharStyle { font_family, font_style, font_version, size, fill, stroke: Paint::None, ..CharStyle::default() };
|
||||
let mut t = TextObject::point(Point::ZERO, text, style);
|
||||
|
||||
@@ -15,12 +15,13 @@
|
||||
//! every buffer's bytes are checked against the heap before they are allocated. Every element
|
||||
//! a method visits takes a unit of fuel, and a sort's comparisons take one each.
|
||||
//!
|
||||
//! The language has no iterators yet, so constructing from an object reads an array or an object
|
||||
//! with a `length`, by index, and `%TypedArray%.from` reads those or a string, by code point. A
|
||||
//! constructor given a primitive string reads it as a length.
|
||||
//! Constructing from an object that is not a buffer or a typed array, and `%TypedArray%.from`,
|
||||
//! read a source with an `@@iterator` method through its iterator (a string by code point), and
|
||||
//! any other source as an array-like object, by index. `%TypedArray%.prototype[@@iterator]` is
|
||||
//! `values`. A constructor given a primitive string reads it as a length.
|
||||
|
||||
use super::collections::{for_each_item, getter, length_of, new_iter, new_proto};
|
||||
use super::{arg, array, data, method, native, require_callable, to_integer};
|
||||
use super::collections::{getter, length_of, new_iter, new_proto};
|
||||
use super::{arg, array, data, method, native, new_array, require_callable, to_integer};
|
||||
use crate::heap::{Class, Elem, HIDDEN, IterKind, IterSource, NativeFn, NativeKind, OBJECT_BYTES, ObjId, Object, VIEW_BYTES, View, key};
|
||||
use crate::interp::{Abrupt, Desc, ErrorType, Interp, JsResult};
|
||||
use crate::value::{Value, array_index, number_to_str, string_to_number, to_uint32};
|
||||
@@ -28,9 +29,6 @@ use crate::value::{Value, array_index, number_to_str, string_to_number, to_uint3
|
||||
/// The longest buffer, in bytes.
|
||||
const MAX_BUFFER: u64 = u32::MAX as u64;
|
||||
|
||||
/// The bytes each item a method gathers before it writes them is charged.
|
||||
const ITEM_BYTES: usize = 16;
|
||||
|
||||
pub(super) fn install(interp: &mut Interp) -> JsResult<()> {
|
||||
install_array_buffer(interp)?;
|
||||
install_data_view(interp)?;
|
||||
@@ -124,6 +122,11 @@ fn install_typed_arrays(interp: &mut Interp) -> JsResult<()> {
|
||||
for (name, f, length) in methods {
|
||||
method(interp, proto, name, f, length)?;
|
||||
}
|
||||
// `%TypedArray%.prototype[@@iterator]` is `values` (section 22.2.3.30).
|
||||
if let Some(iterator) = interp.well_known(|w| &w.iterator) {
|
||||
let values = interp.get_from(proto, &key("values"), &Value::Object(proto))?;
|
||||
interp.define_sym(proto, iterator, crate::heap::Prop::Data { value: values, flags: HIDDEN })?;
|
||||
}
|
||||
// `%TypedArray%.prototype.toString` is `Array.prototype.toString` (section 22.2.3.28).
|
||||
let array_proto = interp.intrinsics.array_proto;
|
||||
let to_string = interp.get_from(array_proto, &key("toString"), &Value::Object(array_proto))?;
|
||||
@@ -645,21 +648,59 @@ fn typed_ctor(interp: &mut Interp, args: &[Value], constructing: bool, elem: Ele
|
||||
}
|
||||
return Ok(Value::Object(ta));
|
||||
}
|
||||
let len = length_of(interp, o)?;
|
||||
let ta = new_typed(interp, elem, len)?;
|
||||
interp.rooted(&[Value::Object(ta)], |interp| fill_from(interp, ta, &first, len))?;
|
||||
Ok(Value::Object(ta))
|
||||
// Any other object is read as TypedArrayFrom reads it (section 22.2.1.4).
|
||||
typed_array_from(interp, &first, None, |interp, len| new_typed(interp, elem, len))
|
||||
}
|
||||
|
||||
/// Writes the elements `0` to `len - 1` of the array-like object `src` to the typed array `ta`,
|
||||
/// each converted with ToNumber.
|
||||
fn fill_from(interp: &mut Interp, ta: ObjId, src: &Value, len: u64) -> JsResult<()> {
|
||||
let Value::Object(o) = src else { return Ok(()) };
|
||||
/// TypedArrayFrom (section 22.2.2.1.1): a typed array with the values of `items`, made by `make`
|
||||
/// once their number is known, each value mapped with `map` (the function and its `this`) when
|
||||
/// one is given and converted with ToNumber. An `items` with an `@@iterator` method is read
|
||||
/// through its iterator to the end before the typed array is made. Any other value is read as
|
||||
/// an array-like object, each element read, mapped and written before the next is read.
|
||||
fn typed_array_from(
|
||||
interp: &mut Interp,
|
||||
items: &Value,
|
||||
map: Option<(&Value, &Value)>,
|
||||
make: impl FnOnce(&mut Interp, u64) -> JsResult<ObjId>,
|
||||
) -> JsResult<Value> {
|
||||
let using_iterator = match interp.well_known(|w| &w.iterator) {
|
||||
Some(iterator) => interp.get_value_sym(items, &iterator)?,
|
||||
None => Value::Undefined,
|
||||
};
|
||||
let src = if using_iterator.is_nullish() {
|
||||
interp.to_object(items)?
|
||||
} else {
|
||||
let rec = interp.get_iterator_with(items, &using_iterator)?;
|
||||
interp.rooted(&[Value::Object(rec)], |interp| {
|
||||
let list = new_array(interp, 0)?;
|
||||
interp.rooted(&[Value::Object(list)], |interp| interp.append_values(rec, list))?;
|
||||
Ok(list)
|
||||
})?
|
||||
};
|
||||
let src_value = Value::Object(src);
|
||||
interp.rooted(std::slice::from_ref(&src_value), |interp| {
|
||||
let len = length_of(interp, src)?;
|
||||
let ta = make(interp, len)?;
|
||||
interp.rooted(&[Value::Object(ta)], |interp| fill_from(interp, ta, src, len, map))?;
|
||||
Ok(Value::Object(ta))
|
||||
})
|
||||
}
|
||||
|
||||
/// Writes the elements `0` to `len - 1` of the object `src` to the typed array `ta`, each mapped
|
||||
/// with `map` when one is given and converted with ToNumber. Each element is read just before it
|
||||
/// is mapped and written.
|
||||
fn fill_from(interp: &mut Interp, ta: ObjId, src: ObjId, len: u64, map: Option<(&Value, &Value)>) -> JsResult<()> {
|
||||
let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?;
|
||||
let src_value = Value::Object(src);
|
||||
for i in 0..len {
|
||||
interp.use_fuel()?;
|
||||
#[allow(clippy::cast_precision_loss)]
|
||||
let v = interp.get_from(*o, &super::key_of(i as f64), src)?;
|
||||
let item = interp.get_from(src, &super::key_of(i as f64), &src_value)?;
|
||||
#[allow(clippy::cast_precision_loss)]
|
||||
let v = match map {
|
||||
Some((f, this_arg)) => interp.call(f, this_arg, &[item, Value::Number(i as f64)])?,
|
||||
None => item,
|
||||
};
|
||||
let n = interp.to_number(&v)?;
|
||||
write(interp, &view, usize::try_from(i).unwrap_or(usize::MAX), n);
|
||||
}
|
||||
@@ -741,54 +782,11 @@ fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRe
|
||||
require_callable(interp, &map_fn, "the map function")?;
|
||||
}
|
||||
let this_arg = arg(args, 2);
|
||||
let source = arg(args, 0);
|
||||
if !matches!(source, Value::String(_)) {
|
||||
// An array-like source: each element is read, mapped and written before the next is read.
|
||||
let src = interp.to_object(&source)?;
|
||||
let src_value = Value::Object(src);
|
||||
let len = length_of(interp, src)?;
|
||||
let map = mapping.then_some((&map_fn, &this_arg));
|
||||
typed_array_from(interp, &arg(args, 0), map, |interp, len| {
|
||||
let elem = ctor_elem(interp, &this, "from")?;
|
||||
let ta = interp.rooted(std::slice::from_ref(&src_value), |interp| new_typed(interp, elem, len))?;
|
||||
let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?;
|
||||
return interp.rooted(&[Value::Object(ta), src_value.clone()], |interp| {
|
||||
for i in 0..len {
|
||||
interp.use_fuel()?;
|
||||
#[allow(clippy::cast_precision_loss)]
|
||||
let item = interp.get_from(src, &super::key_of(i as f64), &src_value)?;
|
||||
#[allow(clippy::cast_precision_loss)]
|
||||
let v = if mapping { interp.call(&map_fn, &this_arg, &[item, Value::Number(i as f64)])? } else { item };
|
||||
let n = interp.to_number(&v)?;
|
||||
write(interp, &view, usize::try_from(i).unwrap_or(usize::MAX), n);
|
||||
}
|
||||
Ok(Value::Object(ta))
|
||||
});
|
||||
}
|
||||
// A string is read by code point first, as an iterable source is, and then mapped.
|
||||
let mark = interp.temp_roots.len();
|
||||
let mut held = crate::interp::HeldBytes::new(interp);
|
||||
let gathered = for_each_item(interp, &source, false, |interp, item| {
|
||||
held.add(interp, ITEM_BYTES)?;
|
||||
interp.temp_roots.push(item);
|
||||
Ok(())
|
||||
});
|
||||
let result = gathered.and_then(|()| {
|
||||
let items: Vec<Value> = interp.temp_roots.get(mark..).map(<[Value]>::to_vec).unwrap_or_default();
|
||||
let elem = ctor_elem(interp, &this, "from")?;
|
||||
let ta = new_typed(interp, elem, items.len() as u64)?;
|
||||
interp.temp_roots.push(Value::Object(ta));
|
||||
let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?;
|
||||
for (i, item) in items.into_iter().enumerate() {
|
||||
interp.use_fuel()?;
|
||||
#[allow(clippy::cast_precision_loss)]
|
||||
let v = if mapping { interp.call(&map_fn, &this_arg, &[item, Value::Number(i as f64)])? } else { item };
|
||||
let n = interp.to_number(&v)?;
|
||||
write(interp, &view, i, n);
|
||||
}
|
||||
Ok(Value::Object(ta))
|
||||
});
|
||||
interp.temp_roots.truncate(mark);
|
||||
drop(held);
|
||||
result
|
||||
new_typed(interp, elem, len)
|
||||
})
|
||||
}
|
||||
|
||||
/// `%TypedArray%.of(...items)` (section 22.2.2.2).
|
||||
|
||||
@@ -8,18 +8,20 @@
|
||||
//! entries hold their key weakly: the collector removes an entry once its key is reachable only
|
||||
//! through it ([`crate::heap::Heap::collect`]), and they have no size and cannot be listed.
|
||||
//!
|
||||
//! The language has no iterators yet, so the constructors read their argument by index: an
|
||||
//! array or an object with a `length`, or a string by code point. Every entry added is checked
|
||||
//! against the heap limit before it is added, and every entry visited takes a unit of fuel.
|
||||
//! The constructors read their argument through its `@@iterator` method (GetIterator, section
|
||||
//! 7.4.1), and close the iterator when adding an entry throws (IteratorClose, section 7.4.6).
|
||||
//! `Map.prototype[@@iterator]` is `entries`, `Set.prototype[@@iterator]` is `values`, and the
|
||||
//! iterators inherit from `%IteratorPrototype%`. Every entry added is checked against the heap
|
||||
//! limit before it is added, and every entry visited takes a unit of fuel.
|
||||
|
||||
use super::{arg, constructor, create_at, key_of, method, native, new_array, require_callable};
|
||||
use super::{arg, constructor, create_at, method, native, new_array, require_callable};
|
||||
use crate::heap::{
|
||||
COLL_ENTRY_BYTES, CONFIGURABLE, Class, Coll, CollKey, IterKind, IterSource, IterState, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object,
|
||||
PROP_BYTES, Prop, VIEW_BYTES, WEAK_ENTRY_BYTES, WeakColl, key, string_bytes,
|
||||
};
|
||||
use crate::interp::{Abrupt, Interp, JsResult};
|
||||
use crate::string_builtins::flat_charged;
|
||||
use crate::value::{Str, Value};
|
||||
use crate::value::Value;
|
||||
|
||||
/// The ECMAScript 2015 intrinsics the built-ins make their objects with, whatever a script does
|
||||
/// to the globals.
|
||||
@@ -137,7 +139,14 @@ pub(super) fn install(interp: &mut Interp) -> JsResult<()> {
|
||||
getter(interp, set_proto, "get size", set_size)?;
|
||||
// `Set.prototype.keys` is the same function object as `values` (section 23.2.3.8).
|
||||
let values = interp.get_from(set_proto, &key("values"), &Value::Object(set_proto))?;
|
||||
interp.define(set_proto, key("keys"), Prop::Data { value: values, flags: crate::heap::HIDDEN })?;
|
||||
interp.define(set_proto, key("keys"), Prop::Data { value: values.clone(), flags: crate::heap::HIDDEN })?;
|
||||
// `Map.prototype[@@iterator]` is `entries` and `Set.prototype[@@iterator]` is `values`
|
||||
// (sections 23.1.3.12 and 23.2.3.11).
|
||||
if let Some(iterator) = interp.well_known(|w| &w.iterator) {
|
||||
let entries = interp.get_from(map_proto, &key("entries"), &Value::Object(map_proto))?;
|
||||
interp.define_sym(map_proto, iterator.clone(), Prop::Data { value: entries, flags: crate::heap::HIDDEN })?;
|
||||
interp.define_sym(set_proto, iterator, Prop::Data { value: values, flags: crate::heap::HIDDEN })?;
|
||||
}
|
||||
|
||||
let weak_map_proto = new_proto(interp, object_proto);
|
||||
interp.intrinsics.es2015.weak_map_proto = weak_map_proto;
|
||||
@@ -158,8 +167,12 @@ pub(super) fn install(interp: &mut Interp) -> JsResult<()> {
|
||||
method(interp, weak_set_proto, name, f, length)?;
|
||||
}
|
||||
|
||||
// The iterators' prototypes inherit from `%IteratorPrototype%` (sections 23.1.5.2, 23.2.5.2
|
||||
// and 22.1.5.2), whose `@@iterator` gives the iterator itself.
|
||||
let iterator_proto =
|
||||
interp.symbols.objects.and_then(|o| interp.heap.object(o.array_iterator_proto).and_then(|p| p.proto)).unwrap_or(object_proto);
|
||||
for source in [IterSource::Map, IterSource::Set, IterSource::Array] {
|
||||
let proto = new_proto(interp, object_proto);
|
||||
let proto = new_proto(interp, iterator_proto);
|
||||
let next: NativeFn = match source {
|
||||
IterSource::Map => map_iterator_next,
|
||||
IterSource::Set => set_iterator_next,
|
||||
@@ -209,56 +222,10 @@ pub(crate) fn length_of(interp: &mut Interp, o: ObjId) -> JsResult<u64> {
|
||||
Ok(if n <= 0.0 { 0 } else { n.min(9_007_199_254_740_991.0) as u64 })
|
||||
}
|
||||
|
||||
/// Calls `f` with each item of `list`, read by index: an object's elements up to its `length`,
|
||||
/// or a string's code points. Any other value is a `TypeError`, and so is an object without a
|
||||
/// `length` when `need_length` is true. Each item takes a unit of fuel.
|
||||
pub(crate) fn for_each_item(
|
||||
interp: &mut Interp,
|
||||
list: &Value,
|
||||
need_length: bool,
|
||||
mut f: impl FnMut(&mut Interp, Value) -> JsResult<()>,
|
||||
) -> JsResult<()> {
|
||||
match list {
|
||||
Value::Object(o) => {
|
||||
if need_length && !interp.has_property(*o, &key("length"))? {
|
||||
return Err(interp.type_error("the value is not an array, a string or an object with a length"));
|
||||
}
|
||||
let len = length_of(interp, *o)?;
|
||||
let mut i = 0u64;
|
||||
while i < len {
|
||||
interp.use_fuel()?;
|
||||
#[allow(clippy::cast_precision_loss)]
|
||||
let item = interp.get_from(*o, &key_of(i as f64), list)?;
|
||||
f(interp, item)?;
|
||||
i += 1;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Value::String(s) => {
|
||||
let units = flat_charged(interp, s)?;
|
||||
let mut i = 0;
|
||||
while i < units.len() {
|
||||
interp.use_fuel()?;
|
||||
let width = match (units.get(i), units.get(i + 1)) {
|
||||
(Some(hi), Some(lo)) if (0xD800..0xDC00).contains(hi) && (0xDC00..0xE000).contains(lo) => 2,
|
||||
_ => 1,
|
||||
};
|
||||
let piece = units.get(i..i + width).unwrap_or_default().to_vec();
|
||||
let bytes = string_bytes(piece.len());
|
||||
interp.reserve_heap(bytes)?;
|
||||
interp.heap.bytes = interp.heap.bytes.saturating_add(bytes);
|
||||
f(interp, Value::String(Str::from_units(piece)))?;
|
||||
i += width;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(interp.type_error("the value is not an array, a string or an object with a length")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds the items of `list` to the new collection `target` with its `adder` method, as the
|
||||
/// constructors do (sections 23.1.1.1, 23.2.1.1, 23.3.1.1 and 23.4.1.1); `pairs` reads each item
|
||||
/// as a `[key, value]` entry.
|
||||
/// Adds the values the iterator of `list` gives to the new collection `target` with its `adder`
|
||||
/// method, as the constructors do (sections 23.1.1.1, 23.2.1.1, 23.3.1.1 and 23.4.1.1); `pairs`
|
||||
/// reads each value as a `[key, value]` entry, which must be an object. When reading an entry
|
||||
/// or adding it throws, the iterator is closed.
|
||||
fn fill(interp: &mut Interp, target: ObjId, list: &Value, adder: &str, pairs: bool) -> JsResult<()> {
|
||||
if list.is_nullish() {
|
||||
return Ok(());
|
||||
@@ -268,7 +235,8 @@ fn fill(interp: &mut Interp, target: ObjId, list: &Value, adder: &str, pairs: bo
|
||||
let add = interp.get_from(target, &key(adder), &this)?;
|
||||
require_callable(interp, &add, adder)?;
|
||||
interp.rooted(std::slice::from_ref(&add), |interp| {
|
||||
for_each_item(interp, list, true, |interp, item| {
|
||||
let rec = interp.get_iterator(list)?;
|
||||
interp.for_each_value(rec, |interp, item| {
|
||||
if !pairs {
|
||||
return interp.call(&add, &this, &[item]).map(drop);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -59,7 +59,12 @@ impl Interp {
|
||||
Some(_) => Value::Undefined,
|
||||
None => return self.walk_record(v),
|
||||
};
|
||||
if !self.is_callable(&method) {
|
||||
self.get_iterator_with(v, &method)
|
||||
}
|
||||
|
||||
/// GetIterator (section 7.4.1) with `method`, the `@@iterator` method already read from `v`.
|
||||
pub(crate) fn get_iterator_with(&mut self, v: &Value, method: &Value) -> JsResult<ObjId> {
|
||||
if !self.is_callable(method) {
|
||||
let what = match v {
|
||||
Value::Undefined => "undefined",
|
||||
Value::Null => "null",
|
||||
@@ -67,7 +72,7 @@ impl Interp {
|
||||
};
|
||||
return Err(self.type_error(&format!("{what} is not iterable")));
|
||||
}
|
||||
let iterator = self.call(&method, v, &[])?;
|
||||
let iterator = self.call(method, v, &[])?;
|
||||
if !matches!(iterator, Value::Object(_)) {
|
||||
return Err(self.type_error("the iterator is not an object"));
|
||||
}
|
||||
@@ -187,6 +192,41 @@ impl Interp {
|
||||
})
|
||||
}
|
||||
|
||||
/// Calls `f` with each value the iterator of `rec` gives, until it is done. When `f` throws,
|
||||
/// the iterator is closed ([`Interp::iter_close_after_throw`]) and the exception is thrown
|
||||
/// again; when a step throws, the iterator is not closed. `rec` and each value are kept
|
||||
/// reachable while `f` runs.
|
||||
pub(crate) fn for_each_value(&mut self, rec: ObjId, mut f: impl FnMut(&mut Self, Value) -> JsResult<()>) -> JsResult<()> {
|
||||
self.rooted(&[Value::Object(rec)], |i| {
|
||||
while let Some(v) = i.iter_next(rec)? {
|
||||
match i.rooted(std::slice::from_ref(&v), |i| f(i, v.clone())) {
|
||||
Ok(()) => {}
|
||||
Err(Abrupt::Throw(reason)) => return Err(i.iter_close_after_throw(rec, reason)),
|
||||
Err(other) => return Err(other),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// IteratorClose (section 7.4.6) with the exception `reason`: closes the iterator of `rec`
|
||||
/// unless it is done, and gives back `reason` to throw, with the position it was thrown from.
|
||||
/// What closing it throws is dropped, the lookup of `return` included (ECMA-262 2023 section
|
||||
/// 7.4.8, steps 4 to 6); running out of fuel, heap or time is not.
|
||||
pub(crate) fn iter_close_after_throw(&mut self, rec: ObjId, reason: Value) -> Abrupt {
|
||||
let site = self.throw_site.clone();
|
||||
let mark = self.thrown_mark;
|
||||
match self.rooted(std::slice::from_ref(&reason), |i| i.iter_close(rec)) {
|
||||
Ok(()) | Err(Abrupt::Throw(_)) => {
|
||||
self.throw_site = site;
|
||||
self.thrown_mark = mark;
|
||||
self.passing = reason.clone();
|
||||
Abrupt::Throw(reason)
|
||||
}
|
||||
Err(other) => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// `value` → `record`.
|
||||
pub(crate) fn op_get_iterator(&mut self) -> JsResult<()> {
|
||||
let v = self.peek(0)?;
|
||||
@@ -227,8 +267,9 @@ impl Interp {
|
||||
self.append_values(rec, a)
|
||||
}
|
||||
|
||||
/// Appends the values the iterator of `rec` gives to the array `a`; both are on the stack.
|
||||
fn append_values(&mut self, rec: ObjId, a: ObjId) -> JsResult<()> {
|
||||
/// Appends the values the iterator of `rec` gives to the array `a`; both are on the stack or
|
||||
/// otherwise kept reachable.
|
||||
pub(crate) fn append_values(&mut self, rec: ObjId, a: ObjId) -> JsResult<()> {
|
||||
while let Some(v) = self.iter_next(rec)? {
|
||||
let Class::Array { length, .. } = &self.object(a)?.class else { return internal("not an array") };
|
||||
let i = *length;
|
||||
|
||||
@@ -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)]
|
||||
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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::{
|
||||
|
||||
@@ -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) },
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -1020,19 +1020,26 @@ pub(crate) fn vertical_metrics(f: &Dict<'_>, embedded: bool) -> Option<Vertical>
|
||||
|
||||
/// Each CID a `W` or `W2` array (`per` numbers a CID) gives values for, and its values: `c [v…]`
|
||||
/// gives CIDs from c on their values in turn, `c_first c_last v…` the same values to each of the
|
||||
/// range. At most [`MAX_CIDS`] CIDs are read.
|
||||
fn cid_ranges(a: &Array<'_>, per: usize, mut each: impl FnMut(u32, &[f64])) {
|
||||
/// range. At most [`MAX_CIDS`] CIDs are read, and a list's values only as far as they take; `per`
|
||||
/// is 1 or 3.
|
||||
pub(crate) fn cid_ranges(a: &Array<'_>, per: usize, mut each: impl FnMut(u32, &[f64])) {
|
||||
let mut it = a.flex_iter();
|
||||
let mut read = 0;
|
||||
loop {
|
||||
if let Some((first, list)) = it.next::<(u32, Array<'_>)>() {
|
||||
let values: Vec<f64> = list.iter::<f64>().collect();
|
||||
for (cid, v) in (first..=u32::MAX).zip(values.chunks_exact(per)) {
|
||||
// Read as they are given, no more than the CIDs read take.
|
||||
let mut values = list.iter::<f64>();
|
||||
let mut v = [0.0; 3];
|
||||
for cid in first..=u32::MAX {
|
||||
let Some(group) = v.get_mut(..per) else { return };
|
||||
if group.iter_mut().any(|slot| values.next().map(|x| *slot = x).is_none()) {
|
||||
break;
|
||||
}
|
||||
read += 1;
|
||||
if read > MAX_CIDS {
|
||||
return;
|
||||
}
|
||||
each(cid, v);
|
||||
each(cid, group);
|
||||
}
|
||||
} else if per == 1
|
||||
&& let Some((first, last, w)) = it.next::<(u32, u32, f64)>()
|
||||
@@ -1060,11 +1067,20 @@ fn cid_ranges(a: &Array<'_>, per: usize, mut each: impl FnMut(u32, &[f64])) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A font's PostScript name without its subset's six-letter tag (`ABCDEF+Name` is `Name`, ISO
|
||||
/// 32000-1 §9.6.4).
|
||||
pub(crate) fn without_subset_tag(name: &str) -> &str {
|
||||
match name.split_once('+') {
|
||||
Some((tag, rest)) if tag.len() == 6 && tag.bytes().all(|b| b.is_ascii_uppercase()) => rest,
|
||||
_ => name,
|
||||
}
|
||||
}
|
||||
|
||||
/// The PostScript name of font `f`: its `BaseFont`. A composite (Type 0) font's `BaseFont` is its
|
||||
/// CIDFont's name, a hyphen and its CMap's (`Name-Identity-H`, ISO 32000-1 §9.7.6.1), so its
|
||||
/// descendant CIDFont's `BaseFont` is taken, the font program's own name (§9.7.4.1); without one,
|
||||
/// the `BaseFont` without the CMap's name on its end.
|
||||
fn font_name(f: &Dict<'_>) -> Option<String> {
|
||||
pub(crate) fn font_name(f: &Dict<'_>) -> Option<String> {
|
||||
if f.get::<Name<'_>>(b"Subtype").is_some_and(|s| s.as_ref() == b"Type3") {
|
||||
if let Some(base) = f.get::<Name<'_>>(b"BaseFont") {
|
||||
return Some(String::from_utf8_lossy(base.as_ref()).into_owned());
|
||||
|
||||
@@ -1570,11 +1570,7 @@ impl Families {
|
||||
/// The family and style of a font with base (PostScript) name `name`, or of weight `weight`
|
||||
/// and slant `italic` when the name has no style; whether the family is available.
|
||||
pub fn resolve(&self, name: &str, weight: Option<u32>, italic: bool) -> (String, String, bool) {
|
||||
// A subset's six-letter tag.
|
||||
let name = match name.split_once('+') {
|
||||
Some((tag, rest)) if tag.len() == 6 && tag.chars().all(|c| c.is_ascii_uppercase()) => rest,
|
||||
_ => name,
|
||||
};
|
||||
let name = crate::import_scan::without_subset_tag(name);
|
||||
// An installed face of that exact PostScript name: its own family and style.
|
||||
if let Some((family, style)) = vectorcraft_text::FontDb::global().by_postscript_name(name) {
|
||||
return (family, style, true);
|
||||
|
||||
@@ -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::{
|
||||
|
||||
@@ -0,0 +1,814 @@
|
||||
//! The widths a PDF's pages give the characters of the fonts they set type in, read from the font
|
||||
//! dictionaries alone (no page is drawn): a simple font's `Widths` from its `FirstChar`, or a
|
||||
//! composite font's descendant's `W`, each code's character from the font's `ToUnicode` map, or for
|
||||
//! a simple font without one whose `Encoding` is `WinAnsiEncoding`, from that encoding (ISO 32000-1
|
||||
//! §9.6.2, §9.6.6, §9.7.4.3, §9.10.3, Annex D.2).
|
||||
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::pdf::interpret::hayro_cmap::{BfString, CMap};
|
||||
use craft::pdf::syntax::object::{Array, Dict, Name, ObjRef, ObjectIdentifier, Stream};
|
||||
use craft::pdf::syntax::page::Resources;
|
||||
|
||||
use crate::import::replacement;
|
||||
use crate::import_scan::{cid_ranges, font_name, without_subset_tag};
|
||||
|
||||
/// The most fonts read.
|
||||
const MAX_FONTS: usize = 256;
|
||||
/// The most form XObjects looked into, and how deep they may nest.
|
||||
const MAX_FORMS: usize = 4096;
|
||||
const MAX_FORM_DEPTH: u32 = 16;
|
||||
/// The most entries of font and XObject resource dictionaries looked at, all pages and forms of the
|
||||
/// file together (one budget for the whole file, not one a page).
|
||||
const MAX_KEYS: usize = 1 << 16;
|
||||
/// The most bytes of width arrays (`Widths`, `W`) read, all fonts together; an array that fonts
|
||||
/// share by reference is read once. A subset's array is a few kilobytes.
|
||||
const MAX_WIDTH_TEXT: usize = 4 << 20;
|
||||
/// The most characters of a font kept.
|
||||
const MAX_CHARS: usize = 4096;
|
||||
/// The largest `ToUnicode` map read, decoded: a subset's map names a few hundred codes. A longer one
|
||||
/// is left unread.
|
||||
const MAX_TO_UNICODE: usize = 256 << 10;
|
||||
/// The most bytes of `ToUnicode` maps decoded, all fonts together.
|
||||
const MAX_TO_UNICODE_TOTAL: usize = 4 << 20;
|
||||
/// The longest string a `ToUnicode` map read may hold, decoded, in bytes: a destination is a
|
||||
/// character or a short run of them (a ligature's), and each lookup of a code in a range copies its
|
||||
/// range's whole destination. A map with a longer one is left unread.
|
||||
const MAX_DESTINATION: usize = 128;
|
||||
/// The most codes of a composite font whose characters are looked up (its first, in `W` order):
|
||||
/// [`MAX_CHARS`] bounds the characters kept, not the codes looked at to find them.
|
||||
const MAX_LOOKUPS: usize = 4 * MAX_CHARS;
|
||||
/// How far apart two widths a file gives one character of one font may be and still be one width,
|
||||
/// in thousandths of an em: files write widths rounded.
|
||||
const SAME_WIDTH: f32 = 1.0;
|
||||
|
||||
/// The widths a page gives the characters of one font, in thousandths of an em, by character.
|
||||
pub type FontWidths = BTreeMap<char, f32>;
|
||||
|
||||
/// The advance widths, in thousandths of an em, that a PDF's pages give the characters of the fonts
|
||||
/// they set type in, by each font's PostScript name (its `BaseFont` without a subset prefix): what
|
||||
/// the copy of the font the file was set in draws them at. A `.ai`'s PDF part has them for the type
|
||||
/// its text document holds, so they tell installed copies of one font apart. A font whose subsets
|
||||
/// give one character two widths gives none. Cloning it, or a font's widths, shares them.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct PageWidths {
|
||||
fonts: Arc<HashMap<String, Arc<FontWidths>>>,
|
||||
}
|
||||
|
||||
impl PageWidths {
|
||||
/// Each character the pages set in the font of PostScript name `name` (exactly, without a
|
||||
/// subset prefix) and its width (at most 4096 characters): `None` when the pages set none in
|
||||
/// that font, or its subsets give a character two widths.
|
||||
pub fn widths(&self, name: &str) -> Option<&Arc<FontWidths>> {
|
||||
self.fonts.get(name)
|
||||
}
|
||||
}
|
||||
|
||||
/// Which dictionary `d` is, to look at it once: where its text lies in the file as read. One
|
||||
/// dictionary that pages or forms share is read from the same place each time (one in an object
|
||||
/// stream lies in that stream's decoded data, which the reader keeps); telling it by its contents
|
||||
/// would hash it again for each of them.
|
||||
fn dict_key(d: &Dict<'_>) -> (usize, usize) {
|
||||
let text = d.data();
|
||||
(text.as_ptr() as usize, text.len())
|
||||
}
|
||||
|
||||
/// Each CID a composite font's `W` gives a width, and that width.
|
||||
type CidWidths = Rc<[(u32, f32)]>;
|
||||
|
||||
/// What [`page_widths`] has read so far.
|
||||
#[derive(Default)]
|
||||
struct Walk {
|
||||
/// Each font's characters and widths; `None` when two subsets disagree.
|
||||
fonts: HashMap<String, Option<FontWidths>>,
|
||||
/// The narrowest and widest width given each character of each font so far.
|
||||
bounds: HashMap<String, BTreeMap<char, (f32, f32)>>,
|
||||
/// The font dictionaries, form XObjects and resource dictionaries already looked at.
|
||||
seen_fonts: HashSet<(usize, usize)>,
|
||||
seen_forms: HashSet<ObjectIdentifier>,
|
||||
walked: HashSet<(usize, usize)>,
|
||||
/// The `ToUnicode` maps parsed, by their stream: `None` for one that can't be read.
|
||||
maps: HashMap<ObjectIdentifier, Option<Rc<CMap>>>,
|
||||
/// The width arrays that fonts name by reference, read: a simple font's `Widths` (its first 256
|
||||
/// numbers) and a composite font's `W` (each CID and its width).
|
||||
simple_widths: HashMap<ObjRef, Option<Rc<[f32]>>>,
|
||||
cid_widths: HashMap<ObjRef, Option<CidWidths>>,
|
||||
/// How many entries of resource dictionaries have been looked at.
|
||||
looked: usize,
|
||||
/// How many bytes of `ToUnicode` maps have been decoded.
|
||||
decoded: usize,
|
||||
/// How many width arrays have been read, and how many bytes of them.
|
||||
arrays_read: usize,
|
||||
width_text: usize,
|
||||
}
|
||||
|
||||
impl Walk {
|
||||
/// Note `widths`, characters of the font of PostScript name `name` and their widths. All the
|
||||
/// widths given one character, by this and the other subsets, must be the same: no two more
|
||||
/// than [`SAME_WIDTH`] apart.
|
||||
fn add(&mut self, name: String, widths: Vec<(char, f32)>) {
|
||||
let slot = self.fonts.entry(name.clone()).or_insert_with(|| Some(BTreeMap::new()));
|
||||
let Some(have) = slot else { return };
|
||||
let bounds = self.bounds.entry(name).or_default();
|
||||
for (c, w) in widths {
|
||||
if let Some((lo, hi)) = bounds.get_mut(&c) {
|
||||
(*lo, *hi) = (lo.min(w), hi.max(w));
|
||||
if *hi - *lo > SAME_WIDTH {
|
||||
*slot = None;
|
||||
return;
|
||||
}
|
||||
} else if have.len() < MAX_CHARS {
|
||||
have.insert(c, w);
|
||||
bounds.insert(c, (w, w));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Look at one more entry of a resource dictionary: `false` once [`MAX_KEYS`] have been.
|
||||
fn look(&mut self) -> bool {
|
||||
self.looked += 1;
|
||||
self.looked <= MAX_KEYS
|
||||
}
|
||||
|
||||
/// The `ToUnicode` map `s`, parsed once however many fonts name it: `None` when it decodes to
|
||||
/// more than [`MAX_TO_UNICODE`] bytes, when the maps decoded so far reach
|
||||
/// [`MAX_TO_UNICODE_TOTAL`], when it holds a string longer than [`MAX_DESTINATION`], or when it
|
||||
/// can't be read. A map is charged what was decoded of it,
|
||||
/// at most the limit: a stream written plain comes back whole without being decoded.
|
||||
fn character_map(&mut self, s: &Stream<'_>) -> Option<Rc<CMap>> {
|
||||
let id = s.obj_id();
|
||||
if !self.maps.contains_key(&id) {
|
||||
let left = MAX_TO_UNICODE_TOTAL.saturating_sub(self.decoded).min(MAX_TO_UNICODE + 1);
|
||||
let data = s.decoded_within(left).ok();
|
||||
self.decoded += data.as_ref().map_or(left, |d| d.len().min(left));
|
||||
let map = data
|
||||
.filter(|d| d.len() < left && d.len() <= MAX_TO_UNICODE && !d.starts_with(b"bcmap") && longest_string(d) <= MAX_DESTINATION)
|
||||
.and_then(|d| CMap::parse(&d, |_| None));
|
||||
self.maps.insert(id, map.map(Rc::new));
|
||||
}
|
||||
self.maps.get(&id)?.clone()
|
||||
}
|
||||
|
||||
/// Count `array`'s text against [`MAX_WIDTH_TEXT`]: `None` once the width arrays read reach it.
|
||||
fn width_array<'a>(&mut self, array: Option<Array<'a>>) -> Option<Array<'a>> {
|
||||
let array = array.filter(|_| self.width_text < MAX_WIDTH_TEXT)?;
|
||||
self.arrays_read += 1;
|
||||
self.width_text += array.data().len();
|
||||
Some(array)
|
||||
}
|
||||
|
||||
/// The first 256 numbers of simple font `f`'s `Widths`, read once for all the fonts that name
|
||||
/// the same array.
|
||||
fn simple_widths(&mut self, f: &Dict<'_>) -> Option<Rc<[f32]>> {
|
||||
let read = |w: &mut Self| w.width_array(f.get::<Array<'_>>(b"Widths")).map(|a| a.iter::<f32>().take(256).collect::<Rc<[f32]>>());
|
||||
let Some(r) = f.get_ref(b"Widths") else { return read(self) };
|
||||
if let Some(have) = self.simple_widths.get(&r) {
|
||||
return have.clone();
|
||||
}
|
||||
let got = read(self);
|
||||
self.simple_widths.insert(r, got.clone());
|
||||
got
|
||||
}
|
||||
|
||||
/// Each CID that composite font descendant `d`'s `W` gives a width, and the width, read once for all
|
||||
/// the fonts that name the same array.
|
||||
fn cid_widths(&mut self, d: &Dict<'_>) -> Option<CidWidths> {
|
||||
let read = |w: &mut Self| {
|
||||
let a = w.width_array(d.get::<Array<'_>>(b"W"))?;
|
||||
let mut out = Vec::new();
|
||||
cid_ranges(&a, 1, |cid, v| {
|
||||
if let [w0] = v {
|
||||
out.push((cid, *w0 as f32));
|
||||
}
|
||||
});
|
||||
Some(out.into())
|
||||
};
|
||||
let Some(r) = d.get_ref(b"W") else { return read(self) };
|
||||
if let Some(have) = self.cid_widths.get(&r) {
|
||||
return have.clone();
|
||||
}
|
||||
let got = read(self);
|
||||
self.cid_widths.insert(r, got.clone());
|
||||
got
|
||||
}
|
||||
}
|
||||
|
||||
/// [`PageWidths`] of the fonts of `pages` (each page's resources) and of the forms they draw.
|
||||
pub(crate) fn page_widths<'a>(pages: impl IntoIterator<Item = &'a Resources<'a>>) -> PageWidths {
|
||||
let walk = walk(pages);
|
||||
let fonts = walk.fonts.into_iter().filter_map(|(name, w)| Some((name, Arc::new(w.filter(|w| !w.is_empty())?)))).collect();
|
||||
PageWidths { fonts: Arc::new(fonts) }
|
||||
}
|
||||
|
||||
/// Read the fonts of `pages` and of the forms they draw. Each resource dictionary is walked once,
|
||||
/// though pages and forms share it; a form without resources of its own takes those of what draws
|
||||
/// it, which are walked already. At most [`MAX_KEYS`] entries are looked at.
|
||||
fn walk<'a>(pages: impl IntoIterator<Item = &'a Resources<'a>>) -> Walk {
|
||||
let mut w = Walk::default();
|
||||
let mut stack: Vec<(Resources<'a>, u32)> = pages.into_iter().map(|r| (r.clone(), 0)).collect();
|
||||
while let Some((res, depth)) = stack.pop() {
|
||||
if w.walked.insert(dict_key(&res.fonts)) {
|
||||
for key in res.fonts.keys() {
|
||||
if w.seen_fonts.len() >= MAX_FONTS || !w.look() {
|
||||
break;
|
||||
}
|
||||
let Some(f) = res.fonts.get::<Dict<'_>>(key.as_ref()) else { continue };
|
||||
if w.seen_fonts.insert(dict_key(&f))
|
||||
&& let Some((name, widths)) = font_widths(&f, &mut w)
|
||||
{
|
||||
w.add(name, widths);
|
||||
}
|
||||
}
|
||||
}
|
||||
if depth >= MAX_FORM_DEPTH || !w.walked.insert(dict_key(&res.x_objects)) {
|
||||
continue;
|
||||
}
|
||||
for key in res.x_objects.keys() {
|
||||
if w.seen_forms.len() >= MAX_FORMS || !w.look() {
|
||||
break;
|
||||
}
|
||||
let Some(s) = res.x_objects.get::<Stream<'_>>(key.as_ref()) else { continue };
|
||||
let d = s.dict();
|
||||
let form = d.get::<Name<'_>>(b"Subtype").is_some_and(|t| t.as_ref() == b"Form");
|
||||
if let (true, Some(own)) = (form, d.get::<Dict<'_>>(b"Resources"))
|
||||
&& w.seen_forms.insert(s.obj_id())
|
||||
{
|
||||
stack.push((Resources::from_scope(Some(own), res.clone()), depth + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
w
|
||||
}
|
||||
|
||||
/// The PostScript name of font `f` (its `BaseFont` without a subset prefix) and the width of each
|
||||
/// character it names, at most [`MAX_CHARS`] (of a composite font, among its first [`MAX_LOOKUPS`]
|
||||
/// codes with a width). A code's character comes from the font's `ToUnicode`
|
||||
/// map or, for a simple font without one whose `Encoding` is `WinAnsiEncoding`, from that encoding;
|
||||
/// a composite font's codes are its CIDs, so only under an `Identity-H` or `Identity-V` CMap. A
|
||||
/// width of 0 is a code the subset doesn't use, and is left out. `None` for a Type 3 font (its
|
||||
/// widths are in its own glyph space) and a font whose codes' characters can't be told.
|
||||
fn font_widths(f: &Dict<'_>, walk: &mut Walk) -> Option<(String, Vec<(char, f32)>)> {
|
||||
let subtype = f.get::<Name<'_>>(b"Subtype")?;
|
||||
if subtype.as_ref() == b"Type3" {
|
||||
return None;
|
||||
}
|
||||
let name = without_subset_tag(&font_name(f)?).to_string();
|
||||
let composite = subtype.as_ref() == b"Type0";
|
||||
let encoding = f.get::<Name<'_>>(b"Encoding");
|
||||
// Only a font without a `ToUnicode` map falls back to its encoding: one whose map can't be
|
||||
// read gives none.
|
||||
let to_unicode = match f.get::<Stream<'_>>(b"ToUnicode") {
|
||||
Some(s) => Some(walk.character_map(&s)?),
|
||||
None if f.contains_key(b"ToUnicode") => return None,
|
||||
None => None,
|
||||
};
|
||||
let win_ansi = !composite && encoding.as_ref().is_some_and(|e| e.as_ref() == b"WinAnsiEncoding");
|
||||
if to_unicode.is_none() && !win_ansi {
|
||||
return None;
|
||||
}
|
||||
let char_of = |code: u32| match &to_unicode {
|
||||
Some(map) => match map.lookup_bf_string(code).filter(|u| !replacement(u)) {
|
||||
Some(BfString::Char(c)) => Some(c),
|
||||
_ => None,
|
||||
},
|
||||
None => win_ansi_char(code),
|
||||
};
|
||||
let width = |w: f32| (w.is_finite() && w > 0.0 && w < 1e5).then_some(w);
|
||||
let mut widths = Vec::new();
|
||||
if composite {
|
||||
if !encoding.is_some_and(|e| matches!(e.as_ref(), b"Identity-H" | b"Identity-V")) {
|
||||
return None;
|
||||
}
|
||||
let d = f.get::<Array<'_>>(b"DescendantFonts").and_then(|a| a.iter::<Dict<'_>>().next())?;
|
||||
let mut looked = 0;
|
||||
for (cid, w) in walk.cid_widths(&d)?.iter() {
|
||||
if widths.len() >= MAX_CHARS || looked >= MAX_LOOKUPS {
|
||||
break;
|
||||
}
|
||||
let Some(w) = width(*w) else { continue };
|
||||
looked += 1;
|
||||
if let Some(c) = char_of(*cid) {
|
||||
widths.push((c, w));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let first = f.get::<u32>(b"FirstChar")?;
|
||||
// A simple font's codes are bytes.
|
||||
for (code, w) in (first..256).zip(walk.simple_widths(f)?.iter()) {
|
||||
let Some(w) = width(*w) else { continue };
|
||||
if let Some(c) = char_of(code) {
|
||||
widths.push((c, w));
|
||||
}
|
||||
}
|
||||
}
|
||||
Some((name, widths))
|
||||
}
|
||||
|
||||
/// The decoded length, in bytes, of the longest string in CMap text `data`: a hex string's digits
|
||||
/// halved, or a literal string's bytes (escapes counted as written, so at least its length). A `<<`
|
||||
/// opens a dictionary, not a string, and a `%` outside a string starts a comment. An ASCII85
|
||||
/// string (`<~`), which no `ToUnicode` map writes and whose `z` stands for four bytes, counts as
|
||||
/// longer than any.
|
||||
fn longest_string(data: &[u8]) -> usize {
|
||||
let mut longest = 0;
|
||||
let mut i = 0;
|
||||
while let Some(&b) = data.get(i) {
|
||||
i += 1;
|
||||
let len = match b {
|
||||
b'%' => {
|
||||
while data.get(i).is_some_and(|b| !matches!(b, b'\n' | b'\r')) {
|
||||
i += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
b'<' if data.get(i) == Some(&b'~') => return usize::MAX,
|
||||
b'<' if data.get(i) == Some(&b'<') => {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
b'<' => {
|
||||
let mut digits = 0;
|
||||
while let Some(&b) = data.get(i) {
|
||||
i += 1;
|
||||
if b == b'>' {
|
||||
break;
|
||||
}
|
||||
digits += usize::from(b.is_ascii_hexdigit());
|
||||
}
|
||||
digits.div_ceil(2)
|
||||
}
|
||||
b'(' => {
|
||||
let (mut depth, mut len) = (1usize, 0);
|
||||
while let Some(&b) = data.get(i) {
|
||||
i += 1;
|
||||
match b {
|
||||
b'\\' => i += 1,
|
||||
b'(' => depth += 1,
|
||||
b')' => depth -= 1,
|
||||
_ => {}
|
||||
}
|
||||
if depth == 0 {
|
||||
break;
|
||||
}
|
||||
len += 1;
|
||||
}
|
||||
len
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
longest = longest.max(len);
|
||||
}
|
||||
longest
|
||||
}
|
||||
|
||||
/// The character of code `code` in `WinAnsiEncoding` (ISO 32000-1 Annex D.2), which is Windows-1252
|
||||
/// but for the codes it leaves unused: `None` for those, for the controls, and for 160 and 173, which
|
||||
/// it gives the space and the hyphen a second time.
|
||||
fn win_ansi_char(code: u32) -> Option<char> {
|
||||
/// Codes 128 to 159; `\0` where the encoding has no character.
|
||||
const HIGH: [char; 32] = [
|
||||
'\u{20AC}', '\0', '\u{201A}', '\u{192}', '\u{201E}', '\u{2026}', '\u{2020}', '\u{2021}', '\u{2C6}', '\u{2030}', '\u{160}', '\u{2039}',
|
||||
'\u{152}', '\0', '\u{17D}', '\0', '\0', '\u{2018}', '\u{2019}', '\u{201C}', '\u{201D}', '\u{2022}', '\u{2013}', '\u{2014}', '\u{2DC}',
|
||||
'\u{2122}', '\u{161}', '\u{203A}', '\u{153}', '\0', '\u{17E}', '\u{178}',
|
||||
];
|
||||
match code {
|
||||
0x20..=0x7E | 0xA1..=0xAC | 0xAE..=0xFF => char::from_u32(code),
|
||||
0x80..=0x9F => HIGH.get(usize::try_from(code - 0x80).ok()?).copied().filter(|c| *c != '\0'),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with};
|
||||
|
||||
/// A simple font named `name`, in `encoding`, whose widths from code `first` on are `widths`.
|
||||
fn simple(subtype: &str, name: &str, encoding: &str, first: u32, widths: &str) -> String {
|
||||
format!("<< /Type /Font /Subtype /{subtype} /BaseFont /{name} /Encoding /{encoding} /FirstChar {first} /Widths [{widths}] >>")
|
||||
}
|
||||
|
||||
/// The pages' fonts are read from their resources and from the forms they draw, a subset's
|
||||
/// prefix aside: a simple font's characters from `WinAnsiEncoding` (a code 0 wide is left out)
|
||||
/// or its `ToUnicode` map, a composite font's from its `ToUnicode` map, by CID. The subsets of one
|
||||
/// font come together; a font whose subsets give a character two widths, a font in another
|
||||
/// encoding without a `ToUnicode` map, and a Type 3 font give none.
|
||||
#[test]
|
||||
fn the_pages_give_each_font_the_widths_of_its_characters() {
|
||||
let extra = first_extra(2);
|
||||
let fonts = [
|
||||
simple("TrueType", "ABCDEF+Sample-Regular", "WinAnsiEncoding", 65, "600 0 520.5"),
|
||||
simple("Type1", "GHIJKL+Sample-Regular", "WinAnsiEncoding", 128, "700"),
|
||||
format!(
|
||||
"<< /Type /Font /Subtype /Type0 /BaseFont /MNOPQR+Wide-Bold-Identity-H /Encoding /Identity-H /ToUnicode {extra} 0 R \
|
||||
/DescendantFonts [<< /Type /Font /Subtype /CIDFontType2 /BaseFont /MNOPQR+Wide-Bold /W [3 [250 610]] >>] >>"
|
||||
),
|
||||
simple("Type1", "Roman-Mac", "MacRomanEncoding", 65, "500"),
|
||||
format!(
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Mapped /Encoding /MacRomanEncoding /FirstChar 3 /Widths [333] /ToUnicode {extra} 0 R >>"
|
||||
),
|
||||
"<< /Type /Font /Subtype /Type3 /BaseFont /Drawn /Encoding /WinAnsiEncoding /FirstChar 65 /Widths [1] /FontMatrix [1 0 0 1 0 0] >>"
|
||||
.to_string(),
|
||||
simple("TrueType", "STUVWX+Clash", "WinAnsiEncoding", 65, "640"),
|
||||
];
|
||||
let resources = |fonts: &[String], more: &str| {
|
||||
let list: Vec<String> = fonts.iter().enumerate().map(|(i, f)| format!("/F{i} {f}")).collect();
|
||||
format!("/Font << {} >> {more}", list.join(" "))
|
||||
};
|
||||
let first = PdfPage { resources: resources(&fonts, &format!("/XObject << /Fm0 {} 0 R >>", extra + 1)), ..PdfPage::new(100.0, 100.0, "") };
|
||||
let second = PdfPage {
|
||||
resources: resources(&[simple("TrueType", "YZABCD+Clash", "WinAnsiEncoding", 65, "600")], ""),
|
||||
..PdfPage::new(100.0, 100.0, "")
|
||||
};
|
||||
let cmap =
|
||||
"begincmap\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n2 beginbfchar\n<0003> <0020>\n<0004> <03A9>\nendbfchar\nendcmap\n";
|
||||
let form_font = simple("TrueType", "EFGHIJ+Formed", "WinAnsiEncoding", 97, "480");
|
||||
let file = pdf_with(
|
||||
&[first, second],
|
||||
&[
|
||||
&format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len()),
|
||||
&format!(
|
||||
"<< /Type /XObject /Subtype /Form /BBox [0 0 10 10] /Resources << /Font << /F0 {form_font} >> >> /Length 0 >>\nstream\n\nendstream"
|
||||
),
|
||||
],
|
||||
None,
|
||||
);
|
||||
let widths = crate::open_pdf(&file, None).unwrap().page_widths();
|
||||
let got = |name: &str| widths.widths(name).map(|w| w.iter().map(|(c, w)| (*c, *w)).collect::<Vec<_>>());
|
||||
assert_eq!(got("Sample-Regular"), Some(vec![('A', 600.0), ('C', 520.5), ('€', 700.0)]));
|
||||
assert_eq!(got("Wide-Bold"), Some(vec![(' ', 250.0), ('Ω', 610.0)]));
|
||||
assert_eq!(got("Mapped"), Some(vec![(' ', 333.0)]));
|
||||
assert_eq!(got("Formed"), Some(vec![('a', 480.0)]));
|
||||
for none in ["ABCDEF+Sample-Regular", "Roman-Mac", "Drawn", "Clash", "Missing"] {
|
||||
assert_eq!(got(none), None, "{none}");
|
||||
}
|
||||
}
|
||||
|
||||
/// [`super::walk`] of the pages of `file`.
|
||||
fn walked(file: &[u8]) -> super::Walk {
|
||||
let o = crate::open_pdf(file, None).unwrap();
|
||||
let pages = o.pdf.pages();
|
||||
super::walk(pages.iter().map(|p| p.resources()))
|
||||
}
|
||||
|
||||
/// Each resource dictionary is walked once: forms without resources of their own (which take
|
||||
/// those of what draws them), forms that share one, and pages that share one look at each
|
||||
/// entry once, so a file of thousands of them reads in time in proportion to it.
|
||||
#[test]
|
||||
fn shared_resources_are_walked_once() {
|
||||
let n = 4000;
|
||||
let extra = first_extra(1);
|
||||
let font = simple("TrueType", "Shared", "WinAnsiEncoding", 65, "500");
|
||||
// Forms without resources, then forms that share one resource dictionary (the last object).
|
||||
let shared = extra + 2 * n;
|
||||
let forms: Vec<String> = (0..2 * n)
|
||||
.map(|i| {
|
||||
let own = if i < n { String::new() } else { format!("/Resources {shared} 0 R ") };
|
||||
format!("<< /Type /XObject /Subtype /Form /BBox [0 0 1 {i}] {own}/Length 0 >>\nstream\n\nendstream")
|
||||
})
|
||||
.chain(std::iter::once(format!("<< /Font << /F0 {} >> >>", simple("TrueType", "Formed", "WinAnsiEncoding", 66, "600"))))
|
||||
.collect();
|
||||
let names: Vec<String> = (0..2 * n).map(|i| format!("/X{i} {} 0 R", extra + i)).collect();
|
||||
let page = PdfPage { resources: format!("/Font << /F0 {font} >> /XObject << {} >>", names.join(" ")), ..PdfPage::new(100.0, 100.0, "") };
|
||||
let refs: Vec<&str> = forms.iter().map(String::as_str).collect();
|
||||
let w = walked(&pdf_with(&[page], &refs, None));
|
||||
assert!(w.fonts.contains_key("Shared") && w.fonts.contains_key("Formed"));
|
||||
// The page's font and forms, and the shared dictionary's font.
|
||||
assert!(w.looked <= 1 + 2 * n + 1, "{} entries looked at", w.looked);
|
||||
// A thousand pages that share one font dictionary of 4000 entries.
|
||||
let pages_n = 1000;
|
||||
let extra = first_extra(pages_n);
|
||||
let entries: Vec<String> = (0..n).map(|i| format!("/F{i} {} 0 R", extra + 1 + i % 50)).collect();
|
||||
let objects: Vec<String> = std::iter::once(format!("<< {} >>", entries.join(" ")))
|
||||
.chain((0..50).map(|i| simple("TrueType", &format!("S{i}"), "WinAnsiEncoding", 65, "500")))
|
||||
.collect();
|
||||
let pages: Vec<PdfPage> =
|
||||
(0..pages_n).map(|_| PdfPage { resources: format!("/Font {extra} 0 R"), ..PdfPage::new(100.0, 100.0, "") }).collect();
|
||||
let refs: Vec<&str> = objects.iter().map(String::as_str).collect();
|
||||
let w = walked(&pdf_with(&pages, &refs, None));
|
||||
assert_eq!(w.fonts.len(), 50);
|
||||
assert!(w.looked <= n, "{} entries looked at", w.looked);
|
||||
}
|
||||
|
||||
/// Past [`super::MAX_FONTS`] fonts no more entries are looked at.
|
||||
#[test]
|
||||
fn fonts_past_the_most_read_are_not_looked_at() {
|
||||
let fonts: Vec<String> =
|
||||
(0..super::MAX_FONTS + 100).map(|i| format!("/F{i} {}", simple("TrueType", &format!("N{i}"), "WinAnsiEncoding", 65, "500"))).collect();
|
||||
let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") };
|
||||
let w = walked(&pdf_with(&[page], &[], None));
|
||||
assert_eq!(w.fonts.len(), super::MAX_FONTS);
|
||||
assert!(w.looked <= super::MAX_FONTS + 1, "{} entries looked at", w.looked);
|
||||
}
|
||||
|
||||
/// Past [`super::MAX_KEYS`] entries of resource dictionaries, none are looked at: a font
|
||||
/// dictionary of more entries than that, all naming one font, is looked at that far.
|
||||
#[test]
|
||||
fn entries_past_the_most_looked_at_are_left() {
|
||||
let extra = first_extra(1);
|
||||
let entries: Vec<String> = (0..super::MAX_KEYS + 1000).map(|i| format!("/F{i} {extra} 0 R")).collect();
|
||||
let page = PdfPage { resources: format!("/Font << {} >>", entries.join(" ")), ..PdfPage::new(100.0, 100.0, "") };
|
||||
let w = walked(&pdf_with(&[page], &[&simple("TrueType", "Many", "WinAnsiEncoding", 65, "500")], None));
|
||||
assert_eq!(w.fonts.len(), 1);
|
||||
assert!(w.looked <= super::MAX_KEYS + 1, "{} entries looked at", w.looked);
|
||||
}
|
||||
|
||||
/// A width array that fonts share by reference is read once for all of them: 128 composite
|
||||
/// fonts naming one `W` and 128 simple fonts naming one `Widths`, each of 100,000 numbers.
|
||||
#[test]
|
||||
fn a_width_array_fonts_share_is_read_once() {
|
||||
let numbers = 100_000;
|
||||
let big: String = std::iter::repeat_n("500 ", numbers).collect();
|
||||
let extra = first_extra(1);
|
||||
let cmap = "begincmap\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n1 beginbfrange\n<0000> <00FF> <0041>\nendbfrange\nendcmap\n";
|
||||
let fonts: Vec<String> = (0..256)
|
||||
.map(|i| {
|
||||
if i % 2 == 0 {
|
||||
format!(
|
||||
"/F{i} << /Type /Font /Subtype /Type0 /BaseFont /W{i} /Encoding /Identity-H /ToUnicode {} 0 R \
|
||||
/DescendantFonts [<< /Subtype /CIDFontType2 /W {extra} 0 R >>] >>",
|
||||
extra + 1
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"/F{i} << /Type /Font /Subtype /TrueType /BaseFont /S{i} /Encoding /WinAnsiEncoding /FirstChar 65 /Widths {} 0 R >>",
|
||||
extra + 2
|
||||
)
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") };
|
||||
let file = pdf_with(
|
||||
&[page],
|
||||
&[&format!("[0 [{big}]]"), &format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len()), &format!("[{big}]")],
|
||||
None,
|
||||
);
|
||||
let w = walked(&file);
|
||||
assert_eq!(w.arrays_read, 2);
|
||||
assert!(w.width_text <= 2 * (big.len() + 10), "{} bytes of width arrays read", w.width_text);
|
||||
assert_eq!(w.fonts.len(), 256);
|
||||
assert!(w.fonts.values().all(|f| f.as_ref().is_some_and(|f| f.get(&'A') == Some(&500.0))));
|
||||
}
|
||||
|
||||
/// Past [`super::MAX_WIDTH_TEXT`] bytes of width arrays no more are read: of six fonts each with
|
||||
/// an array of a million bytes, the sixth gives no widths.
|
||||
#[test]
|
||||
fn width_arrays_past_the_most_read_are_left() {
|
||||
let big: String = std::iter::repeat_n("500 ", 250_000).collect();
|
||||
let extra = first_extra(1);
|
||||
let fonts: Vec<String> = (0..6)
|
||||
.map(|i| {
|
||||
format!(
|
||||
"/F{i} << /Type /Font /Subtype /TrueType /BaseFont /M{i} /Encoding /WinAnsiEncoding /FirstChar 65 /Widths {} 0 R >>",
|
||||
extra + i
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") };
|
||||
let arrays: Vec<String> = (0..6).map(|_| format!("[{big}]")).collect();
|
||||
let refs: Vec<&str> = arrays.iter().map(String::as_str).collect();
|
||||
let w = walked(&pdf_with(&[page], &refs, None));
|
||||
assert_eq!(w.arrays_read, 5);
|
||||
assert_eq!(w.fonts.values().filter(|f| f.as_ref().is_some_and(|f| !f.is_empty())).count(), 5);
|
||||
}
|
||||
|
||||
/// Widths that drift past [`super::SAME_WIDTH`] over several subsets are two widths, though
|
||||
/// each lies within it of the one read before: subsets giving `A` 600, 600.8 and 601.6 give the
|
||||
/// font none, as do subsets giving `B` 501.5, 500.6 and 500. Two within it still give one. Each
|
||||
/// subset is on a page of its own, so they are read in turn (a font dictionary's entries come in
|
||||
/// no set order).
|
||||
#[test]
|
||||
fn widths_that_drift_apart_over_several_subsets_give_none() {
|
||||
let tags = ["AAAAAA", "BBBBBB", "CCCCCC"];
|
||||
let pages: Vec<PdfPage> = (0..3)
|
||||
.map(|i| {
|
||||
let mut fonts = vec![
|
||||
format!("/D {}", simple("TrueType", &format!("{}+Drift", tags[i]), "WinAnsiEncoding", 65, ["600", "600.8", "601.6"][i])),
|
||||
format!("/B {}", simple("TrueType", &format!("{}+Back", tags[i]), "WinAnsiEncoding", 65, ["0 501.5", "0 500.6", "0 500"][i])),
|
||||
];
|
||||
if i < 2 {
|
||||
fonts.push(format!("/S {}", simple("TrueType", &format!("{}+Steady", tags[i]), "WinAnsiEncoding", 65, ["600", "600.8"][i])));
|
||||
}
|
||||
PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") }
|
||||
})
|
||||
.collect();
|
||||
let widths = crate::open_pdf(&pdf_with(&pages, &[], None), None).unwrap().page_widths();
|
||||
assert!(widths.widths("Drift").is_none());
|
||||
assert!(widths.widths("Back").is_none());
|
||||
assert!(widths.widths("Steady").is_some_and(|w| w.contains_key(&'A')));
|
||||
}
|
||||
|
||||
/// Only a simple font without a `ToUnicode` map takes its characters from `WinAnsiEncoding`:
|
||||
/// one whose map is left unread (longer than [`super::MAX_TO_UNICODE`]) or isn't a stream gives
|
||||
/// no widths.
|
||||
#[test]
|
||||
fn a_to_unicode_map_that_cant_be_read_gives_no_widths() {
|
||||
let mut big = String::from("begincmap\n1 begincodespacerange\n<00> <FF>\nendcodespacerange\n");
|
||||
while big.len() <= super::MAX_TO_UNICODE {
|
||||
big.push_str("1 beginbfchar\n<41> <0042>\nendbfchar\n");
|
||||
}
|
||||
big.push_str("endcmap\n");
|
||||
let extra = first_extra(1);
|
||||
let font = |name: &str, to_unicode: &str| {
|
||||
format!("<< /Type /Font /Subtype /TrueType /BaseFont /{name} /Encoding /WinAnsiEncoding /FirstChar 65 /Widths [600]{to_unicode} >>")
|
||||
};
|
||||
let page = PdfPage {
|
||||
resources: format!(
|
||||
"/Font << /F0 {} /F1 {} /F2 {} >>",
|
||||
font("Unread", &format!(" /ToUnicode {extra} 0 R")),
|
||||
font("Named", " /ToUnicode /Identity-H"),
|
||||
font("Plain", "")
|
||||
),
|
||||
..PdfPage::new(100.0, 100.0, "")
|
||||
};
|
||||
let file = pdf_with(&[page], &[&format!("<< /Length {} >>\nstream\n{big}endstream", big.len())], None);
|
||||
let widths = crate::open_pdf(&file, None).unwrap().page_widths();
|
||||
assert!(widths.widths("Unread").is_none());
|
||||
assert!(widths.widths("Named").is_none());
|
||||
assert_eq!(widths.widths("Plain").map(|w| w.get(&'A').copied()), Some(Some(600.0)));
|
||||
}
|
||||
|
||||
/// A `ToUnicode` map with a destination longer than [`super::MAX_DESTINATION`] is left unread,
|
||||
/// though the whole map is under [`super::MAX_TO_UNICODE`]: each lookup of a code in its range
|
||||
/// would copy the whole destination. A hex destination of 60,000 characters, a literal one of
|
||||
/// 600, and ASCII85 ones (`z` stands for four bytes, and one can hide the rest of its line
|
||||
/// behind a `%` the pre-scan would take for a comment) are all left unread. A map with a long
|
||||
/// name in a dictionary (`<<`) and a comment with an unclosed `(`, more than the limit before
|
||||
/// the map's end, is still read.
|
||||
#[test]
|
||||
fn a_to_unicode_map_with_a_long_destination_is_left_unread() {
|
||||
let head = "begincmap\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n1 beginbfchar\n<0001> <0041>\nendbfchar\n";
|
||||
let range = |dst: &str| format!("{head}1 beginbfrange\n<0100> <01FF> {dst}\nendbfrange\nendcmap\n");
|
||||
let hex = range(&format!("<{}>", "0042".repeat(60_000)));
|
||||
let literal = range(&format!("({})", "B".repeat(600)));
|
||||
let zeros = range(&format!("<~{}~>", "z".repeat(1_000)));
|
||||
let hidden = format!("{head}<~>%~> 1 beginbfrange <0100> <01FF> <{}> endbfrange\nendcmap\n", "0042".repeat(300));
|
||||
let padding = "1 beginbfchar\n<0002> <0042>\nendbfchar\n".repeat(10);
|
||||
let short = format!(
|
||||
"/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 /{} 1 >> def\n% (an unclosed comment\n{head}{padding}endcmap\n",
|
||||
"A".repeat(600)
|
||||
);
|
||||
assert!(hex.len() < super::MAX_TO_UNICODE);
|
||||
let extra = first_extra(1);
|
||||
let names = ["Hex", "Literal", "Zeros", "Hidden", "Short"];
|
||||
let fonts: Vec<String> = names
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, name)| {
|
||||
format!(
|
||||
"/{name} << /Type /Font /Subtype /Type0 /BaseFont /{name} /Encoding /Identity-H /ToUnicode {} 0 R \
|
||||
/DescendantFonts [<< /Subtype /CIDFontType2 /W [1 [500] 256 511 500] >>] >>",
|
||||
extra + i
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") };
|
||||
let maps: Vec<String> =
|
||||
[hex, literal, zeros, hidden, short].iter().map(|m| format!("<< /Length {} >>\nstream\n{m}endstream", m.len())).collect();
|
||||
let refs: Vec<&str> = maps.iter().map(String::as_str).collect();
|
||||
let file = pdf_with(&[page], &refs, None);
|
||||
let widths = crate::open_pdf(&file, None).unwrap().page_widths();
|
||||
for unread in ["Hex", "Literal", "Zeros", "Hidden"] {
|
||||
assert!(widths.widths(unread).is_none(), "{unread}");
|
||||
}
|
||||
let short = widths.widths("Short").map(|w| w.iter().map(|(c, w)| (*c, *w)).collect::<Vec<_>>());
|
||||
assert_eq!(short, Some(vec![('A', 500.0)]));
|
||||
}
|
||||
|
||||
/// Past [`super::MAX_LOOKUPS`] codes of a composite font, no more are looked up, though few of
|
||||
/// them gave a character: of two fonts whose `W` gives all 65,536 CIDs a width, the one whose
|
||||
/// map gives CID 1 a character gives its width, and the one whose map only gives CID 20,000 one
|
||||
/// gives none.
|
||||
#[test]
|
||||
fn codes_past_the_most_looked_up_are_left() {
|
||||
let cmap = |code: &str| {
|
||||
format!("begincmap\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n1 beginbfchar\n<{code}> <0041>\nendbfchar\nendcmap\n")
|
||||
};
|
||||
const { assert!(20_000 > super::MAX_LOOKUPS) };
|
||||
let extra = first_extra(1);
|
||||
let font = |name: &str, map: usize| {
|
||||
format!(
|
||||
"/{name} << /Type /Font /Subtype /Type0 /BaseFont /{name} /Encoding /Identity-H /ToUnicode {} 0 R \
|
||||
/DescendantFonts [<< /Subtype /CIDFontType2 /W {} 0 R >>] >>",
|
||||
extra + map,
|
||||
extra + 2
|
||||
)
|
||||
};
|
||||
let page = PdfPage { resources: format!("/Font << {} {} >>", font("Near", 0), font("Far", 1)), ..PdfPage::new(100.0, 100.0, "") };
|
||||
let maps: Vec<String> =
|
||||
["0001", "4E20"].iter().map(|c| cmap(c)).map(|m| format!("<< /Length {} >>\nstream\n{m}endstream", m.len())).collect();
|
||||
let file = pdf_with(&[page], &[&maps[0], &maps[1], "[0 65535 500]"], None);
|
||||
let widths = crate::open_pdf(&file, None).unwrap().page_widths();
|
||||
assert_eq!(widths.widths("Near").map(|w| w.get(&'A').copied()), Some(Some(500.0)));
|
||||
assert!(widths.widths("Far").is_none());
|
||||
}
|
||||
|
||||
/// [`crate::import_scan::cid_ranges`] gives each CID of a `W` its values, a list's in turn (an
|
||||
/// incomplete last group left out) and a range's to each, and reads no more of a long list than
|
||||
/// the CIDs it takes.
|
||||
#[test]
|
||||
fn cid_ranges_give_each_cid_its_values() {
|
||||
let extra = first_extra(1);
|
||||
let long: String = std::iter::repeat_n("7 ", 70_000).collect();
|
||||
let arrays = ["[1 [10 20 30] 100 102 7]".to_string(), "[1 [1 2 3 4 5 6 7]]".to_string(), format!("[0 [{long}]]")];
|
||||
let page = PdfPage {
|
||||
resources: format!("/Properties << /A {extra} 0 R /B {} 0 R /C {} 0 R >>", extra + 1, extra + 2),
|
||||
..PdfPage::new(10.0, 10.0, "")
|
||||
};
|
||||
let refs: Vec<&str> = arrays.iter().map(String::as_str).collect();
|
||||
let file = pdf_with(&[page], &refs, None);
|
||||
let o = crate::open_pdf(&file, None).unwrap();
|
||||
let pages = o.pdf.pages();
|
||||
let props = &pages.iter().next().unwrap().resources().properties;
|
||||
let ranges = |key: &str, per: usize| {
|
||||
let mut out = vec![];
|
||||
crate::import_scan::cid_ranges(&props.get::<craft::pdf::syntax::object::Array<'_>>(key).unwrap(), per, |cid, v| {
|
||||
out.push((cid, v.to_vec()))
|
||||
});
|
||||
out
|
||||
};
|
||||
let one = |v: &[(u32, f64)]| v.iter().map(|(c, w)| (*c, vec![*w])).collect::<Vec<_>>();
|
||||
assert_eq!(ranges("A", 1), one(&[(1, 10.0), (2, 20.0), (3, 30.0), (100, 7.0), (101, 7.0), (102, 7.0)]));
|
||||
assert_eq!(ranges("B", 3), [(1, vec![1.0, 2.0, 3.0]), (2, vec![4.0, 5.0, 6.0])]);
|
||||
assert_eq!(ranges("C", 1).len(), 65_536);
|
||||
}
|
||||
|
||||
/// A `ToUnicode` map written plain and longer than the limits is charged no more than a
|
||||
/// decoded one could be: the small maps of the other fonts are still read.
|
||||
#[test]
|
||||
fn a_long_plain_map_leaves_the_others_read() {
|
||||
let mut big = String::from("begincmap\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n");
|
||||
while big.len() <= super::MAX_TO_UNICODE_TOTAL + 1000 {
|
||||
big.push_str("1 beginbfchar\n<0001> <0041>\nendbfchar\n");
|
||||
}
|
||||
big.push_str("endcmap\n");
|
||||
let small = "begincmap\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n1 beginbfchar\n<0001> <0042>\nendbfchar\nendcmap\n";
|
||||
let extra = first_extra(1);
|
||||
let cid = |name: &str, map: usize| {
|
||||
format!(
|
||||
"<< /Type /Font /Subtype /Type0 /BaseFont /{name} /Encoding /Identity-H /ToUnicode {} 0 R /DescendantFonts [<< /Subtype /CIDFontType2 /W [1 [500]] >>] >>",
|
||||
extra + map
|
||||
)
|
||||
};
|
||||
let n = 40;
|
||||
let fonts: Vec<String> =
|
||||
std::iter::once(format!("/A {}", cid("Big", 0))).chain((0..n).map(|i| format!("/F{i} {}", cid(&format!("Small{i}"), 1 + i)))).collect();
|
||||
let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") };
|
||||
let objects: Vec<String> = std::iter::once(format!("<< /Length {} >>\nstream\n{big}endstream", big.len()))
|
||||
.chain((0..n).map(|_| format!("<< /Length {} >>\nstream\n{small}endstream", small.len())))
|
||||
.collect();
|
||||
let refs: Vec<&str> = objects.iter().map(String::as_str).collect();
|
||||
let w = walked(&pdf_with(&[page], &refs, None));
|
||||
assert!(w.fonts.get("Big").is_some_and(Option::is_none) || !w.fonts.contains_key("Big"));
|
||||
assert_eq!((0..n).filter(|i| w.fonts.get(&format!("Small{i}")).is_some_and(|f| f.as_ref().is_some_and(|m| !m.is_empty()))).count(), n);
|
||||
assert!(w.decoded <= super::MAX_TO_UNICODE + 1 + n * small.len(), "{} bytes charged", w.decoded);
|
||||
}
|
||||
|
||||
/// A `ToUnicode` map is parsed once however many fonts name it, and one longer than
|
||||
/// [`super::MAX_TO_UNICODE`] decoded is left unread, whether its stream is written plain or
|
||||
/// compressed: its fonts give no widths.
|
||||
#[test]
|
||||
fn a_to_unicode_map_is_read_once_and_only_up_to_its_limit() {
|
||||
use std::io::Write as _;
|
||||
let small =
|
||||
"begincmap\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n1 beginbfchar\n<0001> <0041>\nendbfchar\nendcmap\n".to_string();
|
||||
let mut big = String::from("begincmap\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n");
|
||||
while big.len() <= super::MAX_TO_UNICODE {
|
||||
big.push_str("1 beginbfchar\n<0001> <0041>\nendbfchar\n");
|
||||
}
|
||||
big.push_str("endcmap\n");
|
||||
let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
|
||||
z.write_all(big.as_bytes()).unwrap();
|
||||
let hex: String = z.finish().unwrap().iter().map(|b| format!("{b:02X}")).collect();
|
||||
let extra = first_extra(1);
|
||||
let cid = |name: &str, map: usize| {
|
||||
format!(
|
||||
"<< /Type /Font /Subtype /Type0 /BaseFont /{name} /Encoding /Identity-H /ToUnicode {} 0 R \
|
||||
/DescendantFonts [<< /Subtype /CIDFontType2 /W [1 [500]] >>] >>",
|
||||
extra + map
|
||||
)
|
||||
};
|
||||
let fonts: Vec<String> = (0..64).map(|i| format!("/F{i} {}", cid(&format!("U{i}"), i % 3))).collect();
|
||||
let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") };
|
||||
let file = pdf_with(
|
||||
&[page],
|
||||
&[
|
||||
&format!("<< /Length {} >>\nstream\n{small}endstream", small.len()),
|
||||
&format!("<< /Length {} >>\nstream\n{big}endstream", big.len()),
|
||||
&format!("<< /Length {} /Filter [/ASCIIHexDecode /FlateDecode] >>\nstream\n{hex}>\nendstream", hex.len() + 1),
|
||||
],
|
||||
None,
|
||||
);
|
||||
let w = walked(&file);
|
||||
assert_eq!(w.maps.len(), 3, "each map parsed once");
|
||||
// Each long one charged up to just past the limit.
|
||||
assert!(w.decoded <= small.len() + 2 * (super::MAX_TO_UNICODE + 1), "{} bytes charged", w.decoded);
|
||||
assert_eq!(w.maps.values().filter(|m| m.is_some()).count(), 1, "the long ones left unread");
|
||||
let widths = crate::open_pdf(&file, None).unwrap().page_widths();
|
||||
assert_eq!(widths.widths("U0").map(|w| w.iter().map(|(c, w)| (*c, *w)).collect::<Vec<_>>()), Some(vec![('A', 500.0)]));
|
||||
assert!(widths.widths("U1").is_none() && widths.widths("U2").is_none());
|
||||
// Every font of the name shares one map of its widths.
|
||||
assert!(std::sync::Arc::ptr_eq(widths.widths("U0").unwrap(), widths.clone().widths("U0").unwrap()));
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
@@ -843,12 +843,13 @@ pub(crate) fn with_own_raster_reach(symbols: &SymbolBoxes, n: &Node, b: Rect) ->
|
||||
b.inflate(o, o)
|
||||
}
|
||||
|
||||
/// `n`'s own box, type's grown to hold its glyphs ([`glyphs_box`]) and a blend's to hold its
|
||||
/// spine-placed keys and steps: what it draws when its object effects leave it as it is
|
||||
/// (Revolve builds no art from type).
|
||||
/// `n`'s own box, type's grown to hold its glyphs ([`glyphs_box`]), a blend's to hold its
|
||||
/// spine-placed keys and steps and a radial or mirror repeat's to hold its placed copies: what it
|
||||
/// draws when its object effects leave it as it is (Revolve builds no art from type).
|
||||
fn own_box(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
let b = match &n.kind {
|
||||
NodeKind::Blend { .. } => vectorcraft_geom::union_opt(n.reach_bounds_with(symbols), placed_live_effect_bounds(symbols, n)),
|
||||
NodeKind::Repeat(_) => vectorcraft_geom::union_opt(n.visual_bounds_with(symbols), placed_live_effect_bounds(symbols, n)),
|
||||
_ => n.visual_bounds_with(symbols),
|
||||
}?;
|
||||
Some(match &n.kind {
|
||||
@@ -860,7 +861,8 @@ fn own_box(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
/// A radial or mirror repeat's copies or a spine-aligned blend's steps, measured after they are
|
||||
/// rotated or reflected. Geometry effects run on the placed shapes, so their reach on the source
|
||||
/// need not cover what they paint.
|
||||
/// Without effects, the renderer keeps the quick bounds without evaluating the copies or steps.
|
||||
/// Without effects inside it, the renderer keeps the quick bounds without evaluating the copies or
|
||||
/// steps; `n`'s own effects run on the placed whole and are measured by the caller.
|
||||
fn placed_live_effect_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
match &n.kind {
|
||||
NodeKind::Blend { spec, .. } if spec.orientation == vectorcraft_doc::BlendOrientation::AlignToPath => {}
|
||||
@@ -869,12 +871,13 @@ fn placed_live_effect_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
}
|
||||
let mut has_effects = false;
|
||||
n.walk(&mut |c| {
|
||||
has_effects |= has_fx(c)
|
||||
|| has_object_fx(c)
|
||||
|| match &c.kind {
|
||||
NodeKind::SymbolInstance { symbol, .. } => symbols.has_effects(symbol),
|
||||
_ => false,
|
||||
};
|
||||
has_effects |= !std::ptr::eq(c, n)
|
||||
&& (has_fx(c)
|
||||
|| has_object_fx(c)
|
||||
|| match &c.kind {
|
||||
NodeKind::SymbolInstance { symbol, .. } => symbols.has_effects(symbol),
|
||||
_ => false,
|
||||
});
|
||||
});
|
||||
if !has_effects {
|
||||
return None;
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -8,6 +8,11 @@
|
||||
//! the second end along the line from that end to the point, and Shift keeps the line at 45°
|
||||
//! steps). `direction` is set in the tool's Tool Options and kept with the preferences; `]` (with
|
||||
//! or without Shift) switches it while the ends are placed. Every point snaps to Smart Guides.
|
||||
//! With the `join` option on (Tool Options, or J while the ends are placed), an end placed within
|
||||
//! reach of an end of an open path lands on it, and the arc is joined to that path. With
|
||||
//! `tangentSnap` on (the default), in direction mode, when the direction line starts at an end of
|
||||
//! an open path, the third point snaps onto the line along which the arc carries on the path, the
|
||||
//! same way or turned back, and the tool shows that line dashed.
|
||||
//! Until the third point is placed, the tool shows the arc as a dashed outline with its ends, its
|
||||
//! center as a small cross, the direction line in direction mode and, with Measurement Labels on,
|
||||
//! the radius by the pointer. Where no arc fits (the third point lies on the line through the
|
||||
@@ -17,9 +22,9 @@
|
||||
//! the ends; a second click on the first end (a double-click) places nothing.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::MAX_COORD;
|
||||
use vectorcraft_doc::{MAX_COORD, NodeKind};
|
||||
use vectorcraft_geom::shapes::CircularArc;
|
||||
use vectorcraft_geom::{PathData, Point, Vec2};
|
||||
use vectorcraft_geom::{PathData, Point, SubPath, Vec2};
|
||||
|
||||
use crate::guides::{DrawSnap, Leave};
|
||||
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
|
||||
@@ -34,6 +39,12 @@ const CROSS_PX: f64 = 4.0;
|
||||
const REACH_PX: f64 = 3.0;
|
||||
/// The label the tool shows by the pointer where no arc fits.
|
||||
pub const TOO_LARGE: &str = "Arc too large";
|
||||
/// How near (screen points) an end of an open path an end of the arc counts as on it, the Pen's
|
||||
/// reach for the path ends it joins.
|
||||
const END_PX: f64 = 5.0;
|
||||
/// How near (screen points) the line along which the arc carries on an open path the third point
|
||||
/// snaps onto it.
|
||||
const TANGENT_PX: f64 = 5.0;
|
||||
|
||||
/// The press in progress.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
@@ -47,16 +58,82 @@ enum Press {
|
||||
Third,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
/// An end of an open path under an end of the arc: where it is, and the direction a path carrying
|
||||
/// on from it heads in (none for a path of one anchor).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
struct OpenEnd {
|
||||
at: Point,
|
||||
out: Option<Vec2>,
|
||||
}
|
||||
|
||||
/// The end of an open subpath of an editable path (not a guide) within reach of `p`.
|
||||
fn open_end(cx: &ToolContext, p: Point) -> Option<OpenEnd> {
|
||||
let tol = cx.tol(END_PX).max(cx.point_tol());
|
||||
let editable = cx.doc.editable();
|
||||
// The nearest end; among ends equally near, as `shape.threePointArc`'s `join` picks among the
|
||||
// ends at a point: one in the selection first, then the last in paint order, and of one
|
||||
// subpath's two ends its last anchor.
|
||||
let mut best: Option<(OpenEnd, f64, bool)> = None;
|
||||
cx.doc.walk(|n| {
|
||||
let NodeKind::Path { path, guide: false, .. } = &n.kind else { return };
|
||||
if !editable(n.id) {
|
||||
return;
|
||||
}
|
||||
// In isolation mode, only art inside the isolated node.
|
||||
let chain = cx.doc.ancestry(n.id).unwrap_or_default();
|
||||
if cx.isolation.is_some_and(|s| !chain.contains(&s)) {
|
||||
return;
|
||||
}
|
||||
let chosen = chain.iter().any(|id| cx.selection.objects.contains(id));
|
||||
for sp in path.subpaths.iter().filter(|sp| !sp.closed) {
|
||||
let ends = [false, true].map(|at_first| end_of(sp, at_first));
|
||||
let near = match ends {
|
||||
[Some(last), Some(first)] => Some(if last.at.distance(p) <= first.at.distance(p) { last } else { first }),
|
||||
[last, first] => last.or(first),
|
||||
};
|
||||
let Some(e) = near else { continue };
|
||||
let d = e.at.distance(p);
|
||||
if d <= tol && best.is_none_or(|(_, bd, was)| d < bd || (d == bd && (chosen || !was))) {
|
||||
best = Some((e, d, chosen));
|
||||
}
|
||||
}
|
||||
});
|
||||
best.map(|(e, _, _)| e)
|
||||
}
|
||||
|
||||
/// The end of the open subpath `sp` (its first anchor when `at_first`), with the direction a path
|
||||
/// carrying on from it heads in.
|
||||
fn end_of(sp: &SubPath, at_first: bool) -> Option<OpenEnd> {
|
||||
let n = sp.anchors.len();
|
||||
let (end, next) =
|
||||
if at_first { (sp.anchors.first()?, sp.anchors.get(1)) } else { (sp.anchors.last()?, n.checked_sub(2).and_then(|i| sp.anchors.get(i))) };
|
||||
// The path reaches the end along the first of its control points that is off the end.
|
||||
let mut back = vec![if at_first { end.h_out } else { end.h_in }];
|
||||
if let Some(q) = next {
|
||||
back.extend([if at_first { q.h_in } else { q.h_out }, q.p]);
|
||||
}
|
||||
let out = back.into_iter().map(|q| end.p - q).find(|v| v.hypot() > 0.0).map(|v| v / v.hypot());
|
||||
Some(OpenEnd { at: end.p, out })
|
||||
}
|
||||
|
||||
pub struct ThreePointArcTool {
|
||||
snap: DrawSnap,
|
||||
/// The third point gives the arc's direction at an end instead of a point it passes through.
|
||||
direction: bool,
|
||||
/// An end of the arc on an end of an open path joins the arc to that path.
|
||||
join: bool,
|
||||
/// In direction mode, the third point snaps to where the arc carries on the open path its
|
||||
/// direction line starts at, the same way or turned back.
|
||||
tangent_snap: bool,
|
||||
start: Option<Point>,
|
||||
end: Option<Point>,
|
||||
/// The open path ends found under the first and the second end as each was placed.
|
||||
open: [Option<OpenEnd>; 2],
|
||||
press: Option<Press>,
|
||||
/// Where the pointer is, snapped: the point the next press or release places.
|
||||
pointer: Option<Point>,
|
||||
/// The line the third point snapped to: the end it runs through and its direction.
|
||||
tangent: Option<(Point, Vec2)>,
|
||||
/// Alt was held at the last pointer event: in direction mode, the direction is at the second end.
|
||||
at_end: bool,
|
||||
/// Where the pointer was at its last event, pressed or hovering, before snapping, and the keys
|
||||
@@ -64,6 +141,25 @@ pub struct ThreePointArcTool {
|
||||
raw: Option<(Point, Mods)>,
|
||||
}
|
||||
|
||||
impl Default for ThreePointArcTool {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
snap: DrawSnap::default(),
|
||||
direction: false,
|
||||
join: false,
|
||||
tangent_snap: true,
|
||||
start: None,
|
||||
end: None,
|
||||
open: [None; 2],
|
||||
press: None,
|
||||
pointer: None,
|
||||
tangent: None,
|
||||
at_end: false,
|
||||
raw: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The arc from `start` to `end` shaped by `third`, as `shape.threePointArc` draws it: through
|
||||
/// `third`, or with `direction`, heading toward `third` from `start` (or, with `at_end`, arriving
|
||||
/// at `end` along the line from `end` to `third`). None where no arc fits or the arc would reach
|
||||
@@ -81,14 +177,18 @@ pub fn arc_of(start: Point, end: Point, third: Point, direction: bool, at_end: b
|
||||
on_canvas.then_some((arc, path))
|
||||
}
|
||||
|
||||
/// The command the tool runs for the arc from `start` to `end` shaped by `third`.
|
||||
fn command(start: Point, end: Point, third: Point, direction: bool, at_end: bool) -> (String, Value) {
|
||||
/// The command the tool runs for the arc from `start` to `end` shaped by `third`, joined to the
|
||||
/// open paths at its ends with `join`.
|
||||
fn command(start: Point, end: Point, third: Point, direction: bool, at_end: bool, join: bool) -> (String, Value) {
|
||||
let pair = |p: Point| json!([p.x, p.y]);
|
||||
let params = if direction {
|
||||
let mut params = if direction {
|
||||
json!({ "start": pair(start), "end": pair(end), "toward": pair(third), "at": if at_end { "end" } else { "start" } })
|
||||
} else {
|
||||
json!({ "start": pair(start), "end": pair(end), "through": pair(third) })
|
||||
};
|
||||
if join {
|
||||
params["join"] = json!(true);
|
||||
}
|
||||
("shape.threePointArc".into(), params)
|
||||
}
|
||||
|
||||
@@ -96,11 +196,37 @@ impl ThreePointArcTool {
|
||||
fn clear(&mut self) {
|
||||
self.start = None;
|
||||
self.end = None;
|
||||
self.open = [None; 2];
|
||||
self.press = None;
|
||||
self.pointer = None;
|
||||
self.tangent = None;
|
||||
self.snap.clear();
|
||||
}
|
||||
|
||||
/// The end `which` (0 the first, 1 the second) placed at `p`: the open path end under it is
|
||||
/// noted, and with `join` on the end lands on it.
|
||||
fn place(&mut self, cx: &ToolContext, which: usize, p: Point) -> Point {
|
||||
let found = open_end(cx, p);
|
||||
if let Some(slot) = self.open.get_mut(which) {
|
||||
*slot = found;
|
||||
}
|
||||
match found {
|
||||
Some(e) if self.join => e.at,
|
||||
_ => p,
|
||||
}
|
||||
}
|
||||
|
||||
/// The second end let go at `b`, with the first at `a`: placed, unless landing on an open path
|
||||
/// end puts it on the first end, which leaves it to another try.
|
||||
fn place_end(&mut self, cx: &ToolContext, a: Point, b: Point) {
|
||||
let at = self.place(cx, 1, b);
|
||||
if at.distance(a) > cx.tol(REACH_PX) {
|
||||
self.end = Some(at);
|
||||
} else {
|
||||
self.open[1] = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// How the point being placed keeps to the points before it: the second end to the first, and
|
||||
/// in direction mode the third point to the end its direction line starts from.
|
||||
fn leave(&self, cx: &ToolContext, mods: Mods) -> Option<Leave> {
|
||||
@@ -111,6 +237,28 @@ impl ThreePointArcTool {
|
||||
}
|
||||
}
|
||||
|
||||
/// The third point at `q`, snapped: in direction mode with `tangentSnap` on, near the line
|
||||
/// along which the arc carries on the open path its direction line starts at, it moves onto
|
||||
/// that line. Shift keeps the line at 45° steps instead.
|
||||
fn third(&mut self, cx: &ToolContext, q: Point, mods: Mods) -> Point {
|
||||
self.tangent = None;
|
||||
let (Some(a), Some(b)) = (self.start, self.end) else { return q };
|
||||
if !self.direction || !self.tangent_snap || mods.shift {
|
||||
return q;
|
||||
}
|
||||
let (o, end) = if self.at_end { (b, self.open[1]) } else { (a, self.open[0]) };
|
||||
// The direction line starts on the path's end itself, so the arc carries the path on.
|
||||
let Some(OpenEnd { at, out: Some(t) }) = end.filter(|e| e.at == o) else { return q };
|
||||
let k = (q - at).dot(t);
|
||||
let foot = at + t * k;
|
||||
if k != 0.0 && q.distance(foot) <= cx.tol(TANGENT_PX) {
|
||||
self.tangent = Some((at, t));
|
||||
foot
|
||||
} else {
|
||||
q
|
||||
}
|
||||
}
|
||||
|
||||
/// The pressed pointer moved to `ev`, or Shift or Alt changed: the point being placed follows
|
||||
/// it. A change of keys alone does not make the press a drag.
|
||||
fn follow(&mut self, cx: &ToolContext, ev: &PointerEvent) {
|
||||
@@ -122,10 +270,15 @@ impl ThreePointArcTool {
|
||||
let leave = Leave::segment(cx, *at, ev.mods.shift);
|
||||
self.pointer = Some(self.snap.drag(cx, ev.pos, Some(&leave)));
|
||||
}
|
||||
Some(Press::End | Press::Third) => {
|
||||
Some(Press::End) => {
|
||||
let leave = self.leave(cx, ev.mods);
|
||||
self.pointer = Some(self.snap.drag(cx, ev.pos, leave.as_ref()));
|
||||
}
|
||||
Some(Press::Third) => {
|
||||
let leave = self.leave(cx, ev.mods);
|
||||
let q = self.snap.drag(cx, ev.pos, leave.as_ref());
|
||||
self.pointer = Some(self.third(cx, q, ev.mods));
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
@@ -153,7 +306,8 @@ impl Tool for ThreePointArcTool {
|
||||
PointerKind::Move => {
|
||||
self.raw = Some((ev.pos, ev.mods));
|
||||
let leave = self.leave(cx, ev.mods);
|
||||
self.pointer = Some(self.snap.hover(cx, ev.pos, &[], leave.as_ref()));
|
||||
let q = self.snap.hover(cx, ev.pos, &[], leave.as_ref());
|
||||
self.pointer = Some(self.third(cx, q, ev.mods));
|
||||
vec![]
|
||||
}
|
||||
PointerKind::Down => {
|
||||
@@ -161,7 +315,8 @@ impl Tool for ThreePointArcTool {
|
||||
let leave = self.leave(cx, ev.mods);
|
||||
match (self.start, self.end) {
|
||||
(None, _) => {
|
||||
let at = self.snap.press(cx, ev.pos, &[], None);
|
||||
let snapped = self.snap.press(cx, ev.pos, &[], None);
|
||||
let at = self.place(cx, 0, snapped);
|
||||
self.start = Some(at);
|
||||
self.press = Some(Press::Start { at, from: ev.pos, dragged: false });
|
||||
self.pointer = Some(at);
|
||||
@@ -177,7 +332,8 @@ impl Tool for ThreePointArcTool {
|
||||
self.pointer = Some(at);
|
||||
}
|
||||
(Some(_), Some(_)) => {
|
||||
self.pointer = Some(self.snap.press(cx, ev.pos, &[], leave.as_ref()));
|
||||
let q = self.snap.press(cx, ev.pos, &[], leave.as_ref());
|
||||
self.pointer = Some(self.third(cx, q, ev.mods));
|
||||
self.press = Some(Press::Third);
|
||||
}
|
||||
}
|
||||
@@ -195,8 +351,8 @@ impl Tool for ThreePointArcTool {
|
||||
self.follow(cx, ev);
|
||||
}
|
||||
match (self.press.take(), self.start, self.pointer) {
|
||||
(Some(Press::Start { at, dragged: true, .. }), _, Some(b)) if b.distance(at) >= cx.tol(DRAG_PX) => self.end = Some(b),
|
||||
(Some(Press::End), Some(a), Some(b)) if b.distance(a) > cx.tol(REACH_PX) => self.end = Some(b),
|
||||
(Some(Press::Start { at, dragged: true, .. }), _, Some(b)) if b.distance(at) >= cx.tol(DRAG_PX) => self.place_end(cx, at, b),
|
||||
(Some(Press::End), Some(a), Some(b)) if b.distance(a) > cx.tol(REACH_PX) => self.place_end(cx, a, b),
|
||||
(Some(Press::Third), Some(a), Some(c)) => {
|
||||
let Some(b) = self.end else { return vec![] };
|
||||
// Where no arc fits, nothing is drawn and the ends stay for another try.
|
||||
@@ -204,7 +360,7 @@ impl Tool for ThreePointArcTool {
|
||||
self.snap.clear();
|
||||
return vec![];
|
||||
}
|
||||
let (name, params) = command(a, b, c, self.direction, self.at_end);
|
||||
let (name, params) = command(a, b, c, self.direction, self.at_end, self.join);
|
||||
self.clear();
|
||||
return vec![Action::Exec(name, params)];
|
||||
}
|
||||
@@ -229,18 +385,40 @@ impl Tool for ThreePointArcTool {
|
||||
(Some(_), Some((p, mods))) => self.follow(cx, &PointerEvent::new(PointerKind::Drag, p.x, p.y).with_mods(mods)),
|
||||
(None, Some((p, mods))) if self.end.is_some() && self.pointer.is_some() => {
|
||||
let leave = self.leave(cx, mods);
|
||||
self.pointer = Some(self.snap.hover(cx, p, &[], leave.as_ref()));
|
||||
let q = self.snap.hover(cx, p, &[], leave.as_ref());
|
||||
self.pointer = Some(self.third(cx, q, mods));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
ToolKey::Letter('j') if self.start.is_some() => {
|
||||
self.join = !self.join;
|
||||
// Switched on: the ends placed on open path ends land on them, unless that would
|
||||
// put one end on the other.
|
||||
if self.join {
|
||||
let reach = cx.tol(REACH_PX);
|
||||
if let Some(e) = self.open[0]
|
||||
&& self.end.is_none_or(|b| b.distance(e.at) > reach)
|
||||
{
|
||||
self.start = Some(e.at);
|
||||
if let Some(Press::Start { at, .. }) = &mut self.press {
|
||||
*at = e.at;
|
||||
}
|
||||
}
|
||||
if let (Some(a), Some(_), Some(e)) = (self.start, self.end, self.open[1])
|
||||
&& a.distance(e.at) > reach
|
||||
{
|
||||
self.end = Some(e.at);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
vec![]
|
||||
}
|
||||
|
||||
fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool {
|
||||
matches!(key, ToolKey::Escape | ToolKey::BracketRight) && self.start.is_some()
|
||||
matches!(key, ToolKey::Escape | ToolKey::BracketRight | ToolKey::Letter('j')) && self.start.is_some()
|
||||
}
|
||||
|
||||
/// An end placed: Escape drops it.
|
||||
@@ -266,6 +444,7 @@ impl Tool for ThreePointArcTool {
|
||||
fn hover_ended(&mut self, _cx: &ToolContext) {
|
||||
if self.press.is_none() {
|
||||
self.pointer = None;
|
||||
self.tangent = None;
|
||||
self.snap.clear();
|
||||
}
|
||||
}
|
||||
@@ -285,6 +464,11 @@ impl Tool for ThreePointArcTool {
|
||||
if self.direction {
|
||||
o.push(Overlay::Line { a: if self.at_end { b } else { a }, b: p, color, dashed: false });
|
||||
}
|
||||
// The line the third point snapped to, as far past its end as the pointer is.
|
||||
if let Some((at, t)) = self.tangent {
|
||||
let reach = t * p.distance(at);
|
||||
o.push(Overlay::Line { a: at - reach, b: at + reach, color, dashed: true });
|
||||
}
|
||||
match self.arc() {
|
||||
Some((arc, path)) => {
|
||||
o.push(Overlay::Path { path: path.to_bezpath(), color, width: 1.0, dashed: true });
|
||||
@@ -313,21 +497,23 @@ impl Tool for ThreePointArcTool {
|
||||
}
|
||||
|
||||
fn options(&self) -> Value {
|
||||
json!({ "direction": self.direction })
|
||||
json!({ "direction": self.direction, "join": self.join, "tangentSnap": self.tangent_snap })
|
||||
}
|
||||
|
||||
fn set_option(&mut self, key: &str, value: &Value) {
|
||||
if key == "direction"
|
||||
&& let Some(on) = value.as_bool()
|
||||
{
|
||||
self.direction = on;
|
||||
let Some(on) = value.as_bool() else { return };
|
||||
match key {
|
||||
"direction" => self.direction = on,
|
||||
"join" => self.join = on,
|
||||
"tangentSnap" => self.tangent_snap = on,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn check_option(&self, key: &str, v: &Value) -> Result<(), String> {
|
||||
use crate::option_check as c;
|
||||
match key {
|
||||
"direction" => c::boolean(key, v),
|
||||
"direction" | "join" | "tangentSnap" => c::boolean(key, v),
|
||||
_ => Err(c::unknown(key)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -42,13 +42,24 @@ pub(crate) struct AddonDialogs {
|
||||
struct Open {
|
||||
id: DialogId,
|
||||
spec: &'static Spec,
|
||||
document: Option<u64>,
|
||||
/// The opening document's uid and revert count: File › Revert keeps the uid but replaces the drawing.
|
||||
document: Option<(u64, u64)>,
|
||||
}
|
||||
|
||||
impl Open {
|
||||
fn on_document(self, app: &VectorcraftApp) -> bool {
|
||||
self.document == app.session.active().map(|state| state.uid)
|
||||
self.document == active_document(app)
|
||||
}
|
||||
|
||||
/// Whether the active document is the opening one, reverted since the dialog opened.
|
||||
fn reverted(self, app: &VectorcraftApp) -> bool {
|
||||
matches!((self.document, active_document(app)), (Some((uid, reverts)), Some((now, again))) if uid == now && reverts != again)
|
||||
}
|
||||
}
|
||||
|
||||
/// The active document's uid and revert count.
|
||||
fn active_document(app: &VectorcraftApp) -> Option<(u64, u64)> {
|
||||
app.session.active().map(|state| (state.uid, state.reverts))
|
||||
}
|
||||
|
||||
/// Closes the open add-on dialog without an answer and rolls its preview back.
|
||||
@@ -81,7 +92,7 @@ pub(crate) fn open(
|
||||
close_open(app);
|
||||
let id = dialog.id();
|
||||
host.with(|h| h.open(dialog));
|
||||
app.addon_dialogs.open = Some(Open { id, spec, document: app.session.active().map(|state| state.uid) });
|
||||
app.addon_dialogs.open = Some(Open { id, spec, document: active_document(app) });
|
||||
Ok(json!({ "dialog": spec.command }))
|
||||
}
|
||||
|
||||
@@ -141,8 +152,10 @@ fn pump_commit(app: &mut VectorcraftApp) {
|
||||
app.addon_dialogs.open = None;
|
||||
let preview = mem::take(&mut app.addon_dialogs.preview);
|
||||
// The dialog is closed already, so a refusal can only go to the status line.
|
||||
if !on_document {
|
||||
app.status(tl!("The add-on settings apply only to the drawing where the dialog opened.").to_owned());
|
||||
if open.reverted(app) {
|
||||
app.status("The document was reverted. Reopen this dialog to continue.");
|
||||
} else if !on_document {
|
||||
app.status("The add-on settings apply only to the drawing where the dialog opened.");
|
||||
} else if let Err(error) = preview.commit(app, spec.command, (spec.params)(&result.fields)) {
|
||||
app.status(error);
|
||||
}
|
||||
|
||||
@@ -340,6 +340,40 @@ fn an_add_on_confirmation_does_not_edit_another_drawing_before_the_pump() {
|
||||
assert_eq!((x0(&app, 1), undo_len(&app)), (100.0, source_undo));
|
||||
}
|
||||
|
||||
/// Saves the two rectangles of [`two_rects`] to a file in the returned directory, so File › Revert has a copy to restore.
|
||||
fn two_saved_rects(tag: &str) -> (VectorcraftApp, vectorcraft_testkit::TempDir) {
|
||||
let mut app = two_rects();
|
||||
let dir = vectorcraft_testkit::TempDir::new(tag);
|
||||
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
|
||||
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
|
||||
app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap();
|
||||
(app, dir)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_add_on_draft_from_before_file_revert_leaves_the_restored_drawing_alone() {
|
||||
let (mut app, _dir) = two_saved_rects("addon-revert");
|
||||
open_item(&mut app, "Arrange Tools", "Arrange in Grid…");
|
||||
let id = dialog_id(&app);
|
||||
set(&app, id, "layout", json!("row"));
|
||||
set(&app, id, "preview", json!(true));
|
||||
frame(&mut app);
|
||||
assert_eq!(x0(&app, 1), 30.0, "previewed before the revert");
|
||||
|
||||
app.run("file.revert", json!({"confirmed": true})).unwrap();
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
let restored = app.session.doc().unwrap().doc.clone();
|
||||
let undo = undo_len(&app);
|
||||
frame(&mut app);
|
||||
assert_eq!(app.session.doc().unwrap().doc, restored, "the draft does not preview on the restored drawing");
|
||||
assert!(!app.session.in_interaction());
|
||||
assert!(confirm(&app, id));
|
||||
frame(&mut app);
|
||||
assert_eq!(app.session.doc().unwrap().doc, restored, "OK leaves the restored drawing unchanged");
|
||||
assert_eq!(undo_len(&app), undo, "OK records no undo step");
|
||||
assert_eq!(app.ui.status, "The document was reverted. Reopen this dialog to continue.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_add_on_cancel_leaves_the_other_drawings_interaction_running() {
|
||||
let mut app = two_drawings();
|
||||
|
||||
@@ -562,13 +562,13 @@ fn toolbar(ui: &mut Ui, words: &FoldPreviewWords, doc: &vectorcraft_engine::doc:
|
||||
.collect();
|
||||
Row::new().wrap(true).show(ui, |ui, _| {
|
||||
let current = set.view().map_or("", |v| v.1);
|
||||
if let Some(&id) = Select::new(words.view.clone(), Bind::given(current), &views).show(ui).value()
|
||||
if let Some(&id) = Select::new(words.view.clone(), Bind::given(current), &views).show(ui).events.committed()
|
||||
&& let Some(&(_, _, x, y)) = VIEWS.iter().find(|v| v.1 == id)
|
||||
{
|
||||
(set.rotate_x, set.rotate_y, set.pan) = (x, y, [0.0; 2]);
|
||||
}
|
||||
let inside = Select::new(words.inside.clone(), Bind::given(set.inside.clone()), &insides).placeholder(set.inside.clone()).show(ui);
|
||||
if let Some(name) = inside.value() {
|
||||
if let Some(name) = inside.events.committed() {
|
||||
set.inside.clone_from(name);
|
||||
}
|
||||
Checkbox::new(Bind::bound(&mut set.show_fold_lines)).label(words.show_fold_lines.clone()).show(ui);
|
||||
|
||||
@@ -565,3 +565,37 @@ fn the_status_line_reports_open_joints_crossing_panels_and_other_blanks() {
|
||||
// With no fold there is the one line that says why.
|
||||
assert_eq!(status(0, None, false).len(), 1);
|
||||
}
|
||||
|
||||
/// View and Inside: an entry highlighted with the arrow keys changes no setting, Escape leaves the settings as they
|
||||
/// were, and Enter applies the entry.
|
||||
#[test]
|
||||
fn a_highlighted_view_or_inside_applies_only_once_it_is_chosen() {
|
||||
use craft::ui::contract::Role;
|
||||
|
||||
use crate::tests::panel_harness::Panel;
|
||||
|
||||
crate::i18n::set_current(crate::i18n::Lang::EN);
|
||||
let (mut app, _) = app();
|
||||
app.run("ui.foldPreview", json!({"view": "front", "inside": ""})).unwrap();
|
||||
let mut panel = Panel::new(app, show);
|
||||
panel.room(vec2(520.0, 440.0));
|
||||
let settings = |panel: &Panel| panel.app().ui.fold_preview.clone();
|
||||
for name in ["View", "Inside"] {
|
||||
let before = settings(&panel);
|
||||
panel.click_role(name, Role::COMBO_BOX);
|
||||
panel.key(Key::ArrowDown, Modifiers::NONE);
|
||||
panel.frame();
|
||||
assert_eq!(settings(&panel), before, "a highlighted {name} entry changes no setting");
|
||||
panel.key(Key::Escape, Modifiers::NONE);
|
||||
panel.frame();
|
||||
assert_eq!(settings(&panel), before, "Escape leaves the {name} setting as it was");
|
||||
panel.click_role(name, Role::COMBO_BOX);
|
||||
panel.key(Key::ArrowDown, Modifiers::NONE);
|
||||
panel.key(Key::Enter, Modifiers::NONE);
|
||||
panel.frame();
|
||||
assert_ne!(settings(&panel), before, "Enter applies the {name} entry");
|
||||
}
|
||||
let set = settings(&panel);
|
||||
assert_eq!((set.rotate_x, set.rotate_y), (0.0, 180.0), "the entry after Front is Back");
|
||||
assert!(!set.inside.is_empty(), "the entry after White is a swatch");
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -18,6 +18,12 @@ use vectorcraft_tools::{Mods, PenPose, PointerEvent, PointerKind, ToolKey as Eng
|
||||
use super::{Ui, VectorcraftApp};
|
||||
use crate::cursors::tool_cursor;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`SessionTool`] asked the session for the tool's cursor on this thread.
|
||||
pub(crate) static CURSOR_ASKS: Cell<usize> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The tools that change only the view: they neither autoscroll nor take the document's presses under a modal.
|
||||
const VIEW_TOOLS: [&str; 3] = ["hand", "zoom", "rotateView"];
|
||||
|
||||
@@ -548,10 +554,31 @@ impl CanvasTool for SessionTool<'_> {
|
||||
// The document's overlays are shown by `overlays::show` after the host, in one list.
|
||||
}
|
||||
|
||||
/// While the view moves under the pointer, the cursor the tool last gave for the same tool and keys stays: asking
|
||||
/// the tool again would hit-test the art under the pointer in every frame of a pan or zoom (#2452).
|
||||
fn cursor(&self, cx: &ToolContext<'_>) -> Cursor {
|
||||
let Some(space) = cx.space() else { return tool_cursor(vectorcraft_tools::Cursor::Arrow) };
|
||||
let at = cx.pointer.map_or(Point::ZERO, |p| space.view.to_doc(p.pos));
|
||||
let c = self.app().session.cursor(at, tool_mods(cx.mods, cx.held(Key::Space)), self.view);
|
||||
let mods = tool_mods(cx.mods, cx.held(Key::Space));
|
||||
let mut app = self.app();
|
||||
let wait =
|
||||
super::cursor::hover_wait(&mut app.canvas.view_moved, super::ViewKey::of(&space.view), craft::ui::runtime::frame::clock(&self.ctx));
|
||||
let id = app.session.tool_id();
|
||||
let kept = app.canvas.hover_cursor.filter(|&(was, with, _)| wait.is_some() && (was, with) == (id, mods)).map(|(.., c)| c);
|
||||
let c = match kept {
|
||||
Some(c) => c,
|
||||
None => {
|
||||
#[cfg(test)]
|
||||
CURSOR_ASKS.with(|n| n.set(n.get() + 1));
|
||||
let c = app.session.cursor(at, mods, self.view);
|
||||
app.canvas.hover_cursor = Some((id, mods, c));
|
||||
c
|
||||
}
|
||||
};
|
||||
// Once the view has been still long enough, the next pass asks the tool again.
|
||||
if let Some(secs) = wait {
|
||||
self.ctx.request_repaint_after_secs(secs as f32);
|
||||
}
|
||||
// PLAN: assumed the engine's own precise step is dropped (canvas-w25); the canvas's Caps Lock/preference state arrives as `cx.precise()`.
|
||||
tool_cursor(if cx.precise() { c.precise() } else { c })
|
||||
}
|
||||
|
||||
@@ -3,8 +3,9 @@
|
||||
//! Tilt, Bearing or Rotation with its Variation, over live previews of the nib and of a stroke
|
||||
//! (light, heavy, light pressure). Bristle Brush Options: Name (a new bristle brush name that is too
|
||||
//! long is refused at OK), Shape and the bristle sliders. Scatter, Art and Pattern Brush Options: see
|
||||
//! [`super::brush_art_options`]. OK runs `brush.options` (strokes painted with the brush update);
|
||||
//! a name another brush has, or a new bristle brush name that is too long, keeps the dialog open.
|
||||
//! [`super::brush_art_options`]. A changed OK runs `brush.options` (strokes painted with the brush update);
|
||||
//! accepting unchanged settings closes without an Undo step.
|
||||
//! A name another brush has, or a new bristle brush name that is too long, keeps the dialog open.
|
||||
//!
|
||||
//! Fields: `__brush` (the brush's name), `__type` (`calligraphic` | `bristle` | `scatter` | `art` |
|
||||
//! `pattern`), `name`.
|
||||
@@ -183,6 +184,7 @@ fn open_dialog(app: &mut VectorcraftApp, f: &Map<String, Value>, object_keys: Op
|
||||
initial.set(OPENED, FieldValue::Json(Value::Object(opened)));
|
||||
initial.set(KEYS, FieldValue::Json(json!(keys)));
|
||||
}
|
||||
let unchanged = (!object && !flag(&initial, CREATE)).then(|| (string(&initial, "name"), string(&initial, "__brush"), params(&initial)));
|
||||
// The canvas of the current window: the Key Color dropper samples there while the dialog is open.
|
||||
let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id);
|
||||
let dialog = HostedParamDialog::new(&ctx, KIND, initial, move |fields| {
|
||||
@@ -202,6 +204,15 @@ fn open_dialog(app: &mut VectorcraftApp, f: &Map<String, Value>, object_keys: Op
|
||||
None if !object => return Err(tl!("Return to the original drawing to edit its brush").into()),
|
||||
_ => {}
|
||||
}
|
||||
if let Some((opened_name, brush, opened_params)) = &unchanged {
|
||||
let name = string(&result.fields, "name");
|
||||
// The command ignores an empty name and trims a supplied rename.
|
||||
let same_name = name == *opened_name || name.trim().is_empty() || name.trim() == brush;
|
||||
if same_name && params(&result.fields) == *opened_params {
|
||||
// A deleted brush still reports its normal error instead of accepting a stale dialog.
|
||||
return app.run("brush.get", json!({"name": brush})).map(|_| ());
|
||||
}
|
||||
}
|
||||
ok(app, result)
|
||||
})
|
||||
.ok_or("no window")?,
|
||||
|
||||
@@ -9,6 +9,102 @@ fn app() -> VectorcraftApp {
|
||||
app
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unchanged_normal_brush_approval_keeps_the_document_and_undo_history_exact() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
|
||||
for name in ["6 pt. Flat", "Bristle Round", "Confetti", "Arrow", "Diamonds"] {
|
||||
let mut app = app();
|
||||
let params = if name == "Arrow" { json!({"width": 100.25}) } else { json!({}) };
|
||||
// Establish a saved library before testing a normal approval of an existing brush.
|
||||
app.run("brush.options", json!({"name": name, "params": params})).unwrap();
|
||||
let brush = app.run("brush.get", json!({"name": name})).unwrap();
|
||||
let document = app.session.active().unwrap().doc.clone();
|
||||
let revision = app.session.active().unwrap().revision;
|
||||
let undo = app.session.active().unwrap().history.undo.len();
|
||||
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
|
||||
panel.room(vec2(1200.0, 1200.0));
|
||||
panel.app().run("ui.brushOptions", json!({"name": name})).unwrap();
|
||||
panel.frame();
|
||||
panel.click("OK");
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
assert!(!is_open(&panel.app()), "the unchanged {name} dialog closes normally");
|
||||
assert_eq!(panel.app().run("brush.get", json!({"name": name})).unwrap(), brush);
|
||||
let app = panel.app();
|
||||
let st = app.session.active().unwrap();
|
||||
assert_eq!(st.doc, document, "unchanged {name} approval preserves the entire stored library");
|
||||
assert_eq!(st.revision, revision);
|
||||
assert_eq!(st.history.undo.len(), undo, "unchanged {name} approval adds no Undo step");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brush_automation_approval_skips_noop_but_saves_changed_options_in_one_step() {
|
||||
let mut app = app();
|
||||
app.run("brush.options", json!({"name": "Arrow", "params": {"width": 100.25}})).unwrap();
|
||||
let original = app.session.active().unwrap().doc.clone();
|
||||
let revision = app.session.active().unwrap().revision;
|
||||
let undo = app.session.active().unwrap().history.undo.len();
|
||||
open(&mut app, "Arrow");
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(app.session.active().unwrap().doc, original);
|
||||
assert_eq!(app.session.active().unwrap().revision, revision);
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
|
||||
for name in [" Arrow ", ""] {
|
||||
open(&mut app, "Arrow");
|
||||
set(&mut app, json!({"name": name}));
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(app.session.active().unwrap().doc, original, "a command-equivalent name does not rewrite the brush");
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
|
||||
}
|
||||
open(&mut app, "Arrow");
|
||||
set(&mut app, json!({"width": 110.25}));
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(app.run("brush.get", json!({"name": "Arrow"})).unwrap()["width"], json!(110.25));
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1);
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(app.session.active().unwrap().doc, original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normal_brush_rename_still_saves_and_a_deleted_brush_still_refuses_approval() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
use craft::ui::contract::Role;
|
||||
use egui::{Key, Modifiers};
|
||||
|
||||
let mut app = app();
|
||||
app.run("brush.options", json!({"name": "Arrow", "params": {}})).unwrap();
|
||||
let original = app.session.active().unwrap().doc.clone();
|
||||
let undo = app.session.active().unwrap().history.undo.len();
|
||||
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
|
||||
panel.room(vec2(1200.0, 1200.0));
|
||||
panel.app().run("ui.brushOptions", json!({"name": "Arrow"})).unwrap();
|
||||
panel.frame();
|
||||
panel.click_role("Name", Role::TEXT_INPUT);
|
||||
panel.key(Key::A, Modifiers::COMMAND);
|
||||
panel.type_text("Renamed Arrow");
|
||||
panel.key(Key::Tab, Modifiers::NONE);
|
||||
panel.click("OK");
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
assert!(!is_open(&panel.app()));
|
||||
assert!(panel.app().run("brush.get", json!({"name": "Renamed Arrow"})).is_ok());
|
||||
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1);
|
||||
panel.app().run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(panel.app().session.active().unwrap().doc, original);
|
||||
|
||||
open(&mut panel.app(), "Arrow");
|
||||
panel.app().run("brush.delete", json!({"name": "Arrow"})).unwrap();
|
||||
let deleted = panel.app().session.active().unwrap().doc.clone();
|
||||
let undo = panel.app().session.active().unwrap().history.undo.len();
|
||||
assert!(confirm(&mut panel.app()).unwrap_err().contains("no brush named"));
|
||||
assert!(is_open(&panel.app()), "the stale unchanged dialog reports its normal error");
|
||||
assert_eq!(panel.app().session.active().unwrap().doc, deleted);
|
||||
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo);
|
||||
cancel(&mut panel.app());
|
||||
}
|
||||
|
||||
fn ctx(app: &VectorcraftApp) -> egui::Context {
|
||||
app.ui_ctx.clone().expect("the test app has a context")
|
||||
}
|
||||
|
||||
@@ -313,6 +313,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn gallery_cutout_setting_uses_its_localized_label() {
|
||||
// The Japanese pass measures Cutout in one frame and clicks it in a later one.
|
||||
crate::testing::wait_for_cjk_fonts();
|
||||
let viewport = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0));
|
||||
let mut shown_labels = Vec::new();
|
||||
for (language, expected) in [("en", "Levels"), ("de", "Stufen"), ("ja", "レベル数")] {
|
||||
|
||||
@@ -77,6 +77,8 @@ fn compact_objects_on_path_options_pivot_rotate_reset_and_save() {
|
||||
}
|
||||
|
||||
const PIVOT_NAMES: [&str; 9] = ["Top Left", "Top", "Top Right", "Left", "Center", "Right", "Bottom Left", "Bottom", "Bottom Right"];
|
||||
// The Japanese pass measures the controls once and clicks them frames later.
|
||||
crate::testing::wait_for_cjk_fonts();
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0));
|
||||
let mut untranslated = Vec::new();
|
||||
for lang in ["en", "de", "fr", "ja"] {
|
||||
|
||||
@@ -371,11 +371,12 @@ fn row(ui: &mut egui::Ui, name: &Label, salt: &str, mut body: impl FnMut(&mut eg
|
||||
Field::new(name.clone()).id_salt(salt).show(ui, |ui, _| body(ui));
|
||||
}
|
||||
|
||||
/// A select of `entries` named `name` (an English label), over `value`; `set` takes a pick.
|
||||
/// A select of `entries` named `name` (an English label), over `value`; `set` takes the entry chosen, not one only
|
||||
/// highlighted.
|
||||
fn choose<T: craft::behavior::Value>(ui: &mut egui::Ui, name: &str, salt: &str, entries: &[Entry<T>], value: T, mut set: impl FnMut(T)) {
|
||||
let label = word(name);
|
||||
row(ui, &label, salt, |ui| {
|
||||
if let Some(picked) = Select::new(label.clone(), Bind::given(value.clone()), entries).show(ui).value().cloned() {
|
||||
if let Some(picked) = Select::new(label.clone(), Bind::given(value.clone()), entries).show(ui).events.committed().cloned() {
|
||||
set(picked);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -223,7 +223,7 @@ fn resolution_row() -> Param {
|
||||
let entries: Vec<Entry<usize>> = RESOLUTION_LABELS.iter().enumerate().map(|(i, label)| Entry::new(i, tl!(*label))).collect();
|
||||
let (mut picked, mut typed) = (None, None);
|
||||
let shown = Row::new().show(ui, |ui, _| {
|
||||
picked = Select::new(tl!("Resolution:"), Bind::given(preset.unwrap_or(other)), &entries).show(ui).value().copied();
|
||||
picked = Select::new(tl!("Resolution:"), Bind::given(preset.unwrap_or(other)), &entries).show(ui).events.committed().copied();
|
||||
if preset.is_none() {
|
||||
let field = NumberField::new(tl!("Resolution:"), Bind::given(Some(ppi)))
|
||||
.range(1.0..=4608.0)
|
||||
@@ -274,7 +274,7 @@ fn color_choice(
|
||||
let color = (at == ids.len()).then(|| Srgba::from(Rgba::from_hex(¤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;
|
||||
}
|
||||
|
||||
@@ -130,14 +130,15 @@ fn set_value(fields: &mut DialogFields, key: &str, value: &Value) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A select over `titles`: the index picked this pass. `at` is the shown entry (none shows a placeholder).
|
||||
/// A select over `titles`: the index chosen this pass, not one only highlighted. `at` is the shown entry (none shows a
|
||||
/// placeholder).
|
||||
fn pick(ui: &mut egui::Ui, label: &str, titles: &[String], at: Option<usize>, default: Option<usize>) -> Option<usize> {
|
||||
let entries: Vec<Entry<usize>> = titles.iter().enumerate().map(|(i, t)| Entry::new(i, t.clone())).collect();
|
||||
let mut bind = Bind::given(at.unwrap_or(usize::MAX));
|
||||
if let Some(d) = default {
|
||||
bind = bind.reset(d);
|
||||
}
|
||||
Select::new(label.to_owned(), bind, &entries).id_salt(label).show(ui).value().copied()
|
||||
Select::new(label.to_owned(), bind, &entries).id_salt(label).show(ui).events.committed().copied()
|
||||
}
|
||||
|
||||
/// A select row of JSON `options` (value, title) for `key`.
|
||||
|
||||
@@ -224,6 +224,47 @@ fn png_options_name_the_pixel_size_in_the_accessibility_tree() {
|
||||
assert_eq!(sizes(&mut app), ["120 × 80 px"]);
|
||||
}
|
||||
|
||||
/// PNG Options' Resolution and Background Color, and PNG-8 Options' Matte: an entry highlighted with the arrow keys
|
||||
/// changes no field, Escape closes the list with the dialog open and its fields as they were, and Enter applies the
|
||||
/// entry.
|
||||
#[test]
|
||||
fn a_highlighted_raster_option_applies_only_once_it_is_chosen() {
|
||||
use craft::ui::contract::Role;
|
||||
use egui::{Key, Modifiers};
|
||||
use vectorcraft_engine::cmd::fileio::FORMATS;
|
||||
|
||||
use crate::tests::panel_harness::Panel;
|
||||
|
||||
for (id, name) in [("png", "Resolution:"), ("png", "Background Color:"), ("png8", "Matte:")] {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Services::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
|
||||
panel.room(egui::vec2(1280.0, 1100.0));
|
||||
let format = FORMATS.iter().find(|f| f.id == id).unwrap();
|
||||
super::png_options::open(&mut panel.app(), format, json!({"format": id, "path": format!("/out/a.{id}")}));
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
let fields =
|
||||
|panel: &Panel| on_top(&panel.app(), |h, _, at| h.open_dialogs().into_iter().find(|d| d.id == at).and_then(|d| d.fields)).flatten();
|
||||
let before = fields(&panel);
|
||||
assert!(before.is_some(), "{id} options are open");
|
||||
panel.click_role(name, Role::COMBO_BOX);
|
||||
panel.key(Key::ArrowDown, Modifiers::NONE);
|
||||
panel.frame();
|
||||
assert_eq!(fields(&panel), before, "a highlighted {name} entry changes no field");
|
||||
panel.key(Key::Escape, Modifiers::NONE);
|
||||
panel.frame();
|
||||
assert_eq!(fields(&panel), before, "Escape closes the {name} list with the fields as they were");
|
||||
panel.click_role(name, Role::COMBO_BOX);
|
||||
panel.key(Key::ArrowDown, Modifiers::NONE);
|
||||
panel.key(Key::Enter, Modifiers::NONE);
|
||||
panel.frame();
|
||||
let after = fields(&panel);
|
||||
assert!(after.is_some(), "Enter in the {name} list keeps the dialog open");
|
||||
assert_ne!(after, before, "Enter applies the {name} entry");
|
||||
}
|
||||
}
|
||||
|
||||
/// The role and name of each node of the window's accessibility tree, in a frame drawn once the dialogs have settled.
|
||||
fn access_names(app: &mut VectorcraftApp) -> Vec<(egui::accesskit::Role, String)> {
|
||||
super::tests::settle(app);
|
||||
|
||||
@@ -223,6 +223,42 @@ fn enter(app: &mut VectorcraftApp) {
|
||||
frame(app);
|
||||
}
|
||||
|
||||
/// Define Grid's Type, Units and Scale: an entry highlighted with the arrow keys changes no field, Escape closes the
|
||||
/// list with the dialog open and its fields as they were, and Enter applies the entry.
|
||||
#[test]
|
||||
fn a_highlighted_define_grid_choice_applies_only_once_it_is_chosen() {
|
||||
use craft::ui::contract::Role;
|
||||
use egui::{Key, Modifiers};
|
||||
|
||||
use crate::tests::panel_harness::Panel;
|
||||
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 800, "height": 600})).unwrap();
|
||||
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
|
||||
panel.room(egui::vec2(1280.0, 1100.0));
|
||||
panel.app().run("ui.perspectiveGridDialog", json!({})).unwrap();
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
let fields = |panel: &Panel| host(&panel.app(), |h| h.open_dialogs().pop().and_then(|d| d.fields));
|
||||
for name in ["Type:", "Units:", "Scale:"] {
|
||||
let before = fields(&panel);
|
||||
panel.click_role(name, Role::COMBO_BOX);
|
||||
panel.key(Key::ArrowDown, Modifiers::NONE);
|
||||
panel.frame();
|
||||
assert_eq!(fields(&panel), before, "a highlighted {name} entry changes no field");
|
||||
panel.key(Key::Escape, Modifiers::NONE);
|
||||
panel.frame();
|
||||
assert_eq!(kind(&panel.app()).as_deref(), Some(super::perspective_grid::KIND), "Escape closes the list, not the dialog");
|
||||
assert_eq!(fields(&panel), before, "Escape leaves the fields as they were");
|
||||
panel.click_role(name, Role::COMBO_BOX);
|
||||
panel.key(Key::ArrowDown, Modifiers::NONE);
|
||||
panel.key(Key::Enter, Modifiers::NONE);
|
||||
panel.frame();
|
||||
assert_eq!(kind(&panel.app()).as_deref(), Some(super::perspective_grid::KIND), "Enter in the list keeps the dialog open");
|
||||
assert_ne!(fields(&panel), before, "Enter applies the {name} entry");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enter_is_ok_in_define_grid_and_save_grid_as_preset() {
|
||||
let mut app = app();
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -357,15 +357,11 @@ impl Component for Cells {
|
||||
|
||||
/// The marks of node row `n`'s selection square in the panel over `tree`: whether it shows the
|
||||
/// full-sized square (the row is selected, or it is a layer or sublayer whose visible, unlocked art
|
||||
/// is all selected), and whether it shows the small one (it holds selected art otherwise).
|
||||
/// is all selected), and whether it shows the small one (it holds selected art otherwise). It reads
|
||||
/// the nodes that hold selected art from the rows, which list them once per revision.
|
||||
pub(super) fn square_marks(tree: &DocLayers<'_>, n: &Node) -> (bool, bool) {
|
||||
let full = tree.is_selected(n.id) || tree.is_full(n.id);
|
||||
let holds = !full && {
|
||||
let mut any = false;
|
||||
n.walk(&mut |c| any |= c.id != n.id && tree.is_selected(c.id));
|
||||
any
|
||||
};
|
||||
(full, holds)
|
||||
(full, !full && tree.holds_selected(n.id))
|
||||
}
|
||||
|
||||
/// The cells of row `row` (shown as `info`) of the panel over `tree`.
|
||||
|
||||
@@ -193,6 +193,9 @@ pub(super) struct LayerRows {
|
||||
/// and not empty.
|
||||
#[plain_data(assume = "node ids are integers")]
|
||||
full: HashSet<NodeId>,
|
||||
/// The nodes that hold a selected object below them ([`super::rows::holding`]).
|
||||
#[plain_data(assume = "node ids are integers")]
|
||||
holding: HashSet<NodeId>,
|
||||
/// The selected blends, in selection order.
|
||||
#[plain_data(assume = "node ids are integers")]
|
||||
blends: Vec<NodeId>,
|
||||
@@ -252,6 +255,7 @@ impl LayerRows {
|
||||
ruler,
|
||||
guide_rows,
|
||||
full: super::rows::full_layers(doc, &selected),
|
||||
holding: super::rows::holding(doc, &selected),
|
||||
selected,
|
||||
blends: blends.collect(),
|
||||
root: st.isolation.and_then(|i| isolated_root(doc, i)).map(|(n, ..)| n.id),
|
||||
@@ -310,6 +314,11 @@ impl LayerRows {
|
||||
self.full.contains(&id)
|
||||
}
|
||||
|
||||
/// Whether node `id` holds a selected object below it.
|
||||
pub(super) fn holds_selected(&self, id: NodeId) -> bool {
|
||||
self.holding.contains(&id)
|
||||
}
|
||||
|
||||
/// The node ids a row menu's command acts on: every highlighted row when the menu's row is one of
|
||||
/// them, else the row's own node.
|
||||
pub(super) fn targets(&self, target: &MenuTarget<RowId>) -> Vec<u64> {
|
||||
|
||||
@@ -150,6 +150,37 @@ pub(super) fn full_layers(doc: &Document, sel: &HashSet<NodeId>) -> HashSet<Node
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many nodes [`holding`] visited on this thread.
|
||||
pub(super) static HOLDING_VISITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The nodes of `doc` that hold an object of `sel` below them, found in one pass over the tree: the rows whose
|
||||
/// selection square shows the small mark when they are not full.
|
||||
pub(super) fn holding(doc: &Document, sel: &HashSet<NodeId>) -> HashSet<NodeId> {
|
||||
/// Adds `n` to `out` when an object of `sel` is below it, and returns whether `n` or one below it is in `sel`.
|
||||
fn visit(n: &Node, sel: &HashSet<NodeId>, out: &mut HashSet<NodeId>) -> bool {
|
||||
#[cfg(test)]
|
||||
HOLDING_VISITS.with(|v| v.set(v.get() + 1));
|
||||
let mut below = false;
|
||||
for c in n.children().into_iter().flatten() {
|
||||
below |= visit(c, sel, out);
|
||||
}
|
||||
if below {
|
||||
out.insert(n.id);
|
||||
}
|
||||
below || sel.contains(&n.id)
|
||||
}
|
||||
let mut out = HashSet::new();
|
||||
if !sel.is_empty() {
|
||||
for n in &doc.layers {
|
||||
visit(n, sel, &mut out);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The `layer.target` of a click with `mods` on the target circle of `id`, by the rules of a row click (#8639): plain
|
||||
/// targets it, Ctrl/Cmd adds it to the selection or takes it out, Shift selects the art of every row `filter` lists
|
||||
/// from `anchor` (the last circle clicked, else the targeted row) to it, and Shift+Ctrl/Cmd adds that art. With it,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -66,7 +66,7 @@ fn check(ui: &mut Ui, label: &'static str, on: bool, enabled: bool) -> Option<bo
|
||||
}
|
||||
|
||||
/// A select named `name` (shown before it when `caption`) over `items` of `(value, shown name)`; the
|
||||
/// value the user picked this pass.
|
||||
/// value the user chose this pass, not one only highlighted.
|
||||
fn pick<T: Clone + PartialEq + Send + Sync + 'static>(
|
||||
ui: &mut Ui,
|
||||
name: &str,
|
||||
@@ -82,7 +82,8 @@ fn pick<T: Clone + PartialEq + Send + Sync + 'static>(
|
||||
if caption {
|
||||
Text::new(label.clone()).show(ui);
|
||||
}
|
||||
picked = Select::new(label.clone(), Bind::given(current.clone()), &entries).enabled(enabled).id_salt(name).show(ui).value().cloned();
|
||||
picked =
|
||||
Select::new(label.clone(), Bind::given(current.clone()), &entries).enabled(enabled).id_salt(name).show(ui).events.committed().cloned();
|
||||
});
|
||||
picked
|
||||
}
|
||||
@@ -541,6 +542,45 @@ mod tests {
|
||||
assert_eq!(none.params(AssignChoice::Profile, None), None, "no other profile to pick");
|
||||
}
|
||||
|
||||
/// A profile highlighted in the Assign rows' Profile list assigns nothing, Escape leaves the document as it was,
|
||||
/// and the profile chosen with Enter is assigned in one undo step.
|
||||
#[test]
|
||||
fn a_highlighted_profile_is_assigned_only_once_it_is_chosen() {
|
||||
use craft::ui::contract::Role;
|
||||
use egui::{Key, Modifiers};
|
||||
|
||||
// Assigning a profile to the front document changes the process's active color settings.
|
||||
if !crate::testing::in_own_process("panels::separations::tests::a_highlighted_profile_is_assigned_only_once_it_is_chosen") {
|
||||
return;
|
||||
}
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({})).unwrap();
|
||||
app.run("edit.assignProfile", json!({"rgb": null, "cmyk": null})).unwrap();
|
||||
let row = AssignRow::of(&app.session.active().unwrap().doc);
|
||||
assert!(row.others.len() >= 2, "{row:?}");
|
||||
let mut panel = Panel::new(app, show);
|
||||
let state = |panel: &Panel| {
|
||||
let app = panel.app();
|
||||
let st = app.session.active().unwrap();
|
||||
(vectorcraft_engine::cmd::colormgmt::doc_profiles(&st.doc), st.history.undo.len())
|
||||
};
|
||||
let before = state(&panel);
|
||||
panel.click_role("Profile:", Role::COMBO_BOX);
|
||||
panel.key(Key::ArrowDown, Modifiers::NONE);
|
||||
panel.frame();
|
||||
assert_eq!(state(&panel), before, "a highlighted profile assigns nothing");
|
||||
panel.key(Key::Escape, Modifiers::NONE);
|
||||
panel.frame();
|
||||
assert_eq!(state(&panel), before, "Escape leaves the document's profiles as they were");
|
||||
panel.click_role("Profile:", Role::COMBO_BOX);
|
||||
panel.key(Key::ArrowDown, Modifiers::NONE);
|
||||
panel.key(Key::Enter, Modifiers::NONE);
|
||||
panel.frame();
|
||||
let ((rgb, _), undo) = state(&panel);
|
||||
assert_eq!(rgb.as_deref(), Some(row.others[1].as_str()), "Enter assigns the chosen profile");
|
||||
assert_eq!(undo, before.1 + 1, "the choice is one undo step");
|
||||
}
|
||||
|
||||
/// The Assign rows follow the document's color mode: an RGB document lists the RGB working space
|
||||
/// and the RGB profiles and assigns its RGB profile, a CMYK document the CMYK ones, and the other
|
||||
/// model's profile stays as it was.
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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<PartRef>, 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<String> {
|
||||
let payload = catch_unwind(AssertUnwindSafe(drive)).err()?;
|
||||
payload.downcast_ref::<String>().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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -645,7 +645,9 @@ pub fn control_bar_options(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let entries: Vec<Entry<&'static str>> = 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<Entry<f64>> = 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
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 importLine truncated
|
||||
> **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, joiLine truncated
|
||||
>
|
||||
> **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 <path> 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. |
|
||||
|
||||
+5
-4
@@ -846,11 +846,12 @@ 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, its character and paragraph styles, 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, its character and
|
||||
paragraph styles, 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
|
||||
|
||||
+81
-12
@@ -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 <name>]`,
|
||||
`[Layer <name>]`, `[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,9 @@ 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.
|
||||
- `Document.characterStyles` and `Document.paragraphStyles`
|
||||
(https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/,
|
||||
https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/) list the document's styles with `length`, `[i]`,
|
||||
@@ -3066,6 +3088,33 @@ other files through `$`:
|
||||
`Stale style`.
|
||||
One run names at most 4,096 styles. `ParagraphStyle.characterAttributes` throws an error that says it is not
|
||||
available 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`
|
||||
@@ -5884,6 +5933,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
|
||||
@@ -8056,8 +8110,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
|
||||
@@ -13024,6 +13080,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
|
||||
@@ -17715,6 +17783,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. |
|
||||
|
||||
+4
-3
@@ -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 anLine truncated
|
||||
> **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 `/Line truncated
|
||||
|
||||
> 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 Line truncated
|
||||
| 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 importLine truncated
|
||||
| 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 `<pattern>`/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, its text frames, text ranges and their attributes, its character and paragraph styles, and the installed fonts; the rest of the script document model (layers, artboards, paths, stories and threads of 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 their attributes, its character and paragraph styles, the installed fonts, and its stories and threaded frames; the rest of the script document model (layers, artboards, paths, text lines 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 <name>, 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. |
|
||||
|
||||
@@ -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 esLine truncated
|
||||
> **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 Line truncated
|
||||
|
||||
> 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 thaLine truncated
|
||||
| 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 openLine truncated
|
||||
| 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 Line truncated
|
||||
| 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 thaLine truncated
|
||||
| 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 openLine truncated
|
||||
| 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 Line truncated
|
||||
| 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 <path> 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 (<https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=226>) 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 (<https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=65>) says that moving the pointer around in a curve during the drag turns the new spiral, and the help page (<https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=226>) 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,10 +1115,11 @@ 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, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.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, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`.
|
||||
- Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.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: `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`.
|
||||
@@ -1186,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`.
|
||||
@@ -1607,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).
|
||||
|
||||
@@ -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` |
|
||||
|
||||
Reference in new issue
Block a user