mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-03 15:21:17 -05:00
Merge main into feat/scripts-api-d3-layers-artboards
# Conflicts: # docs/target-app-parity.md
This commit is contained in:
@@ -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> {
|
||||
|
||||
@@ -981,11 +981,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,
|
||||
@@ -1005,10 +1013,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())),
|
||||
}
|
||||
}
|
||||
@@ -1859,21 +1868,38 @@ 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 {
|
||||
if layers::is_scoped(a) {
|
||||
return layers::scoped_at(h, a);
|
||||
}
|
||||
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 {
|
||||
@@ -1882,10 +1908,15 @@ 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()))
|
||||
})
|
||||
}
|
||||
@@ -1893,10 +1924,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())),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -3108,6 +3108,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.
|
||||
|
||||
@@ -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> {
|
||||
|
||||
@@ -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);
|
||||
|
||||
File diff suppressed because one or more lines are too long
+37
-7
@@ -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>]`, `[Artboard <name>]`, `[Application]`, `[PageItems]`, `[Layers]`, `[GroupItems]`,
|
||||
@@ -2977,7 +2999,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`.
|
||||
- A document also has `layers`, `activeLayer`, `groupItems`, `compoundPathItems` and `artboards`.
|
||||
@@ -5927,6 +5949,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
|
||||
@@ -8100,8 +8127,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
|
||||
@@ -17758,6 +17787,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. |
|
||||
|
||||
+3
-2
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -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