From c49d45c8266308eb92273a40c8da8599a7940f0b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 17:01:23 -0800 Subject: [PATCH 01/19] Path Precision Tools: Common Tangents measures each line near where it touches MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each tangent measured every segment of both paths to find where it touches them, so two paths of thousands of segments with thousands of tangents took segments × tangents work. Each line now starts from the segment found for the nearest sampled direction and walks outward only as far as the stretch that lies along it. On two 2,000-sided polygons with 4,000 tangents, the segment measurements drop from about 33.5 million to 1.6 million. A turned or scaled ellipse is measured exactly however thin it is. A map is refused only when its determinant is within the rounding of its entries; before, an ellipse more than about 1e12 times longer than wide was refused as having no area. --- .../pathops/src/addons/pathtools/tangents.rs | 132 +++++++++++++++--- 1 file changed, 113 insertions(+), 19 deletions(-) diff --git a/crates/pathops/src/addons/pathtools/tangents.rs b/crates/pathops/src/addons/pathtools/tangents.rs index 2059932aa2..c01c80957e 100644 --- a/crates/pathops/src/addons/pathtools/tangents.rs +++ b/crates/pathops/src/addons/pathtools/tangents.rs @@ -77,7 +77,9 @@ impl Outline { pub fn ellipse(unit: Affine) -> Result { let [a, b, c, d, e, f] = unit.as_coeffs(); let norm = a.abs().max(b.abs()).max(c.abs()).max(d.abs()); - if !unit.as_coeffs().iter().all(|v| v.is_finite()) || norm <= 0.0 || (a * d - b * c).abs() <= 1e-12 * norm * norm { + // The determinant is rounded by about `f64::EPSILON * norm²`; one no larger than that may + // belong to a map with no area. Any thinner ellipse is measured exactly. + if !unit.as_coeffs().iter().all(|v| v.is_finite()) || norm <= 0.0 || (a * d - b * c).abs() <= f64::EPSILON * norm * norm { return Err(OutlineError::Empty); } Ok(Outline::Ellipse { center: Point::new(e, f), m: [a, b, c, d] }) @@ -270,11 +272,13 @@ impl Outline { } } - /// The points of the outline on the line `p · n = h`, its support value: the point where - /// `p · n` is largest, and the ends of any straight side along the line. Another point counts - /// when it lies within `tol` of the line plus `slope` times its distance from that largest - /// point, where `slope` is how far off the normal's angle may be. - fn touching(&self, n: Vec2, h: f64, tol: f64, slope: f64) -> Vec { + /// The points of the outline on the line `p · n = h`, its support value, which is reached on + /// segment `at`: the point where `p · n` is largest, and the ends of any straight side along + /// the line. Another point counts when it lies within `tol` of the line plus `slope` times its + /// distance from that largest point, where `slope` is how far off the normal's angle may be. + /// On a convex outline the points that count form one run around the largest one, so the + /// segments are measured from `at` outward both ways until a segment's end does not count. + fn touching(&self, n: Vec2, h: f64, tol: f64, slope: f64, at: usize) -> Vec { match self { Outline::Ellipse { center, m: [a, b, c, d] } => { let w = Vec2::new(a * n.x + b * n.y, c * n.x + d * n.y); @@ -282,9 +286,25 @@ impl Outline { vec![*center + Vec2::new(a * w.x + c * w.y, b * w.x + d * w.y)] } Outline::Convex { segments, .. } => { + let len = segments.len(); let mut all = vec![]; - for s in segments { - each_extreme(s, n, |p, v| all.push((p, v))); + let Some(first) = segments.get(at % len.max(1)) else { return vec![] }; + each_extreme(first, n, |p, v| all.push((p, v))); + let Some(&(peak, _)) = all.iter().max_by(|x, y| x.1.total_cmp(&y.1)) else { return vec![] }; + let counts = |p: Point| h - p.to_vec2().dot(n) <= tol + slope * (p - peak).hypot(); + let mut ahead = 0; + for j in 1..len { + match segments.get((at + j) % len) { + Some(s) if counts(s.p0) => each_extreme(s, n, |p, v| all.push((p, v))), + _ => break, + } + ahead = j; + } + for j in 1..len - ahead { + match segments.get((at + len - j) % len) { + Some(s) if counts(s.p3) => each_extreme(s, n, |p, v| all.push((p, v))), + _ => break, + } } let Some(&(peak, _)) = all.iter().max_by(|x, y| x.1.total_cmp(&y.1)) else { return vec![] }; all.into_iter().filter(|(p, v)| h - v <= tol + slope * (*p - peak).hypot()).map(|(p, _)| p).collect() @@ -322,6 +342,8 @@ fn bends_against(s: &CubicBez, sign: f64) -> bool { } fn each_extreme(s: &CubicBez, n: Vec2, mut f: impl FnMut(Point, f64)) { + #[cfg(test)] + tests::EXTREMES.with(|c| c.set(c.get() + 1)); let [v0, v1, v2, v3] = [s.p0, s.p1, s.p2, s.p3].map(|p| p.to_vec2().dot(n)); f(s.p0, v0); f(s.p3, v3); @@ -396,10 +418,11 @@ pub fn common_tangents(a: &Outline, b: &Outline) -> Result, Coincid let hint = |h: &[usize], k: usize| h.get(k).copied().unwrap_or(0); let external = roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 - b.support_from(dir(t), hint(&hb, k)).0, tol)?; let internal = roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 + b.support_from(-dir(t), hint(&hb_back, k)).0, tol)?; + let (a, b) = (Hinted { o: a, at: &at, hints: &ha }, Hinted { o: b, at: &at, hints: &hb }); let mut out = Vec::with_capacity(external.len() + internal.len()); for (kind, list) in [(TangentKind::External, external), (TangentKind::Internal, internal)] { for root in list { - let t = tangent_at(a, b, kind, dir(root.angle), root.double, size); + let t = tangent_at(&a, &b, kind, root.angle, root.double, size); out.push(Tangent { from: t.from + origin, to: t.to + origin, ..t }); } } @@ -414,21 +437,47 @@ struct Root { double: bool, } -/// The tangent of `kind` whose normal is `n`: `a` lies where `p · n` is at most the line's value, -/// and `b` on the same side (external) or the other side (internal). `double` when the outlines -/// touch there. -fn tangent_at(a: &Outline, b: &Outline, kind: TangentKind, n: Vec2, double: bool, size: f64) -> Tangent { +/// An outline with the segment it is touched on at each sampled normal angle. +struct Hinted<'a> { + o: &'a Outline, + at: &'a [f64], + hints: &'a [usize], +} + +impl Hinted<'_> { + /// The support value at the normal angle `angle` and the segment it is reached on, walking on + /// from the segment of the sample at or before `angle`. + fn support(&self, angle: f64) -> (f64, usize) { + let angle = angle.rem_euclid(TAU); + // Before the first sample, the last one (taken 2π back) comes before `angle`. + let k = self.at.partition_point(|t| *t <= angle).checked_sub(1).unwrap_or(self.at.len().saturating_sub(1)); + self.o.support_from(dir(angle), self.hints.get(k).copied().unwrap_or(0)) + } +} + +/// The tangent of `kind` whose normal is at `angle`: `a` lies where `p · n` is at most the line's +/// value, and `b` on the same side (external) or the other side (internal). `double` when the +/// outlines touch there. +fn tangent_at(a: &Hinted, b: &Hinted, kind: TangentKind, angle: f64, double: bool, size: f64) -> Tangent { + let n = dir(angle); // The rounding allowed in `p · n` grows with each outline's own size and its distance from the // origin. let rounding = |o: &Outline| 1e-12 * o.size() + 1e-14 * (o.center().to_vec2().hypot() + o.size()); - let (tol_a, tol_b) = (rounding(a), rounding(b)); + let (tol_a, tol_b) = (rounding(a.o), rounding(b.o)); // Bisection finds a simple root's angle to about the rounding of the support values; the // golden-section search finds a double root's to about 1e-8 radians. let slope = if double { 1e-7 } else { 1e-10 }; - let ha = a.support(n); - let (on_a, on_b) = match kind { - TangentKind::External => (a.touching(n, ha, tol_a, slope), b.touching(n, b.support(n), tol_b, slope)), - TangentKind::Internal => (a.touching(n, ha, tol_a, slope), b.touching(-n, b.support(-n), tol_b, slope)), + let (ha, sa) = a.support(angle); + let on_a = a.o.touching(n, ha, tol_a, slope, sa); + let on_b = match kind { + TangentKind::External => { + let (hb, sb) = b.support(angle); + b.o.touching(n, hb, tol_b, slope, sb) + } + TangentKind::Internal => { + let (hb, sb) = b.support(angle + TAU / 2.0); + b.o.touching(-n, hb, tol_b, slope, sb) + } }; // Positions along the line, which runs square to `n` through `n * ha`. let t = Vec2::new(-n.y, n.x); @@ -441,7 +490,7 @@ fn tangent_at(a: &Outline, b: &Outline, kind: TangentKind, n: Vec2, double: bool // stand a little apart. let (from, to) = if double && hi - lo <= 1e-6 * size { // Touching at one point: the narrower outline's width along the line, centered there. - let width = [a, b].map(|o| o.support(t) + o.support(-t)).into_iter().fold(f64::MAX, f64::min); + let width = [a, b].map(|o| o.support(angle + TAU / 4.0).0 + o.support(angle - TAU / 4.0).0).into_iter().fold(f64::MAX, f64::min); let mid = (lo + hi) / 2.0; (mid - width / 2.0, mid + width / 2.0) } else if mean(&on_a) <= mean(&on_b) { @@ -575,11 +624,18 @@ fn golden(g: &dyn Fn(f64) -> f64, mut lo: f64, mut hi: f64) -> (f64, f64) { #[cfg(test)] mod tests { + use std::cell::Cell; + use kurbo::Rect; use vectorcraft_geom::shapes; use super::*; + thread_local! { + /// How many times [`each_extreme`] has measured a segment on this thread. + pub(super) static EXTREMES: Cell = const { Cell::new(0) }; + } + fn circle(cx: f64, cy: f64, r: f64) -> Outline { Outline::ellipse(Affine::new([r, 0.0, 0.0, r, cx, cy])).unwrap() } @@ -850,6 +906,44 @@ mod tests { assert!(all.iter().all(|t| ((t.to - t.from).hypot() - 200.0 * (TAU / 1600.0).sin()).abs() < 1e-6), "{:?}", all.first()); } + #[test] + fn each_tangent_measures_only_the_segments_near_where_it_touches() { + // Two regular 2,000-gons about one center, one turned half a step: 4,000 external + // tangents. Measuring every segment of both outlines for every tangent takes about 16,000 + // measurements per tangent. + let sides = 2_000; + let gon = |turn: f64| { + let pts: Vec = (0..sides).map(|k| (dir(turn + TAU * k as f64 / sides as f64) * 100.0).to_point()).collect(); + SubPath::polyline(&pts, true) + }; + let (a, b) = (Outline::convex(&gon(0.0)).unwrap(), Outline::convex(&gon(TAU / (2 * sides) as f64)).unwrap()); + EXTREMES.with(|c| c.set(0)); + let all = common_tangents(&a, &b).unwrap(); + let calls = EXTREMES.with(Cell::get); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 2 * sides); + assert!(calls < 1_000 * all.len(), "{calls} measurements for {} tangents", all.len()); + let r = 100.0 * (TAU / (4 * sides) as f64).sin(); + assert!(all.iter().all(|t| ((t.to - t.from).hypot() - 2.0 * r).abs() < 1e-6), "{:?}", all.first()); + } + + #[test] + fn a_very_thin_ellipse_is_measured_exactly() { + // Semi-axes 1e6 and 1e-7, a ratio of 1e13, beside a circle: the tangents run from the + // ellipse's tips to the circle. + let thin = Affine::scale_non_uniform(1e6, 1e-7); + let all = common_tangents(&Outline::ellipse(thin).unwrap(), &circle(0.0, 100.0, 10.0)).unwrap(); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 2, "{all:?}"); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::Internal).count(), 2, "{all:?}"); + let (sa, sb) = (sample_ellipse(thin, 20_000), sample_ellipse(Affine::new([10.0, 0.0, 0.0, 10.0, 0.0, 100.0]), 5_000)); + for t in &all { + check_against_samples(t, &sa, &sb, 1e-3); + let tip = if (t.from - Point::new(1e6, 0.0)).hypot() < 1e-3 || (t.from - Point::new(-1e6, 0.0)).hypot() < 1e-3 { t.from } else { t.to }; + assert!((tip.x.abs() - 1e6).abs() < 1e-3 && tip.y.abs() < 1e-6, "{t:?}"); + } + // A map whose determinant is lost in the rounding of its entries is still refused. + assert_eq!(Outline::ellipse(Affine::new([1.0, 1.0, 1.0, 1.0 + f64::EPSILON, 0.0, 0.0])).err(), Some(OutlineError::Empty)); + } + #[test] fn a_curve_peaking_inside_a_segment_is_measured_at_its_peak() { // p(t) · n has the control values 0, 0.25, 0.5, -0.25: its derivative's linear term is From 7e1d76ae7d4e8ebd70b48589dfb9b4fdbe9bd775 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 17:31:26 -0800 Subject: [PATCH 02/19] Path Precision Tools: Common Tangents tests a turned thin ellipse and the area limit The thin-ellipse test now also turns the figure 30 degrees and checks that each line still ends at the ellipse's tip. A determinant four times its rounding is accepted and one equal to its rounding is refused, so the limit is tested on both sides. The comment on the limit said the opposite of the rule: an ellipse is measured exactly when its determinant is larger than the rounding of its entries. The segment counter used by the tests is declared next to the function it counts, and the estimate in the work test is corrected to about 8,000 measurements per tangent. --- .../pathops/src/addons/pathtools/tangents.rs | 55 +++++++++++-------- 1 file changed, 33 insertions(+), 22 deletions(-) diff --git a/crates/pathops/src/addons/pathtools/tangents.rs b/crates/pathops/src/addons/pathtools/tangents.rs index c01c80957e..9e198229fd 100644 --- a/crates/pathops/src/addons/pathtools/tangents.rs +++ b/crates/pathops/src/addons/pathtools/tangents.rs @@ -78,7 +78,8 @@ impl Outline { let [a, b, c, d, e, f] = unit.as_coeffs(); let norm = a.abs().max(b.abs()).max(c.abs()).max(d.abs()); // The determinant is rounded by about `f64::EPSILON * norm²`; one no larger than that may - // belong to a map with no area. Any thinner ellipse is measured exactly. + // belong to a map with no area. An ellipse whose determinant is larger is measured + // exactly. if !unit.as_coeffs().iter().all(|v| v.is_finite()) || norm <= 0.0 || (a * d - b * c).abs() <= f64::EPSILON * norm * norm { return Err(OutlineError::Empty); } @@ -313,8 +314,6 @@ impl Outline { } } -/// Calls `f` with each point of `s` where `p · n` can be largest (its ends and the places where -/// the curve runs square to `n`) and the value there. /// Whether cubic `s` bends against `sign` (the way its outline turns) anywhere. The cross product /// of its first and second derivatives is a quadratic in t; its lowest value on [0, 1] is compared /// with the segment's control polygon length squared. @@ -341,9 +340,17 @@ fn bends_against(s: &CubicBez, sign: f64) -> bool { low < -1e-9 * scale } +#[cfg(test)] +thread_local! { + /// How many times [`each_extreme`] has measured a segment on this thread, for the tests. + static EXTREMES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Calls `f` with each point of `s` where `p · n` can be largest (its ends and the places where +/// the curve runs square to `n`) and the value there. fn each_extreme(s: &CubicBez, n: Vec2, mut f: impl FnMut(Point, f64)) { #[cfg(test)] - tests::EXTREMES.with(|c| c.set(c.get() + 1)); + EXTREMES.with(|n| n.set(n.get() + 1)); let [v0, v1, v2, v3] = [s.p0, s.p1, s.p2, s.p3].map(|p| p.to_vec2().dot(n)); f(s.p0, v0); f(s.p3, v3); @@ -631,11 +638,6 @@ mod tests { use super::*; - thread_local! { - /// How many times [`each_extreme`] has measured a segment on this thread. - pub(super) static EXTREMES: Cell = const { Cell::new(0) }; - } - fn circle(cx: f64, cy: f64, r: f64) -> Outline { Outline::ellipse(Affine::new([r, 0.0, 0.0, r, cx, cy])).unwrap() } @@ -909,7 +911,7 @@ mod tests { #[test] fn each_tangent_measures_only_the_segments_near_where_it_touches() { // Two regular 2,000-gons about one center, one turned half a step: 4,000 external - // tangents. Measuring every segment of both outlines for every tangent takes about 16,000 + // tangents. Measuring every segment of both outlines for every tangent takes about 8,000 // measurements per tangent. let sides = 2_000; let gon = |turn: f64| { @@ -928,19 +930,28 @@ mod tests { #[test] fn a_very_thin_ellipse_is_measured_exactly() { - // Semi-axes 1e6 and 1e-7, a ratio of 1e13, beside a circle: the tangents run from the - // ellipse's tips to the circle. - let thin = Affine::scale_non_uniform(1e6, 1e-7); - let all = common_tangents(&Outline::ellipse(thin).unwrap(), &circle(0.0, 100.0, 10.0)).unwrap(); - assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 2, "{all:?}"); - assert_eq!(all.iter().filter(|t| t.kind == TangentKind::Internal).count(), 2, "{all:?}"); - let (sa, sb) = (sample_ellipse(thin, 20_000), sample_ellipse(Affine::new([10.0, 0.0, 0.0, 10.0, 0.0, 100.0]), 5_000)); - for t in &all { - check_against_samples(t, &sa, &sb, 1e-3); - let tip = if (t.from - Point::new(1e6, 0.0)).hypot() < 1e-3 || (t.from - Point::new(-1e6, 0.0)).hypot() < 1e-3 { t.from } else { t.to }; - assert!((tip.x.abs() - 1e6).abs() < 1e-3 && tip.y.abs() < 1e-6, "{t:?}"); + // Semi-axes 1e6 and 1e-7, a ratio of 1e13, beside a circle, then the whole figure turned + // 30 degrees: the tangents run from the ellipse's tips to the circle. + for deg in [0.0, 30.0] { + let turn = Affine::rotate(f64::to_radians(deg)); + let thin = turn * Affine::scale_non_uniform(1e6, 1e-7); + let round = turn * Affine::new([10.0, 0.0, 0.0, 10.0, 0.0, 100.0]); + let all = common_tangents(&Outline::ellipse(thin).unwrap(), &Outline::ellipse(round).unwrap()).unwrap(); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 2, "{all:?}"); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::Internal).count(), 2, "{all:?}"); + let (sa, sb) = (sample_ellipse(thin, 20_000), sample_ellipse(round, 5_000)); + for t in &all { + check_against_samples(t, &sa, &sb, 1e-3); + // The end on the ellipse, taken back to the unturned figure. + let (from, to) = (turn.inverse() * t.from, turn.inverse() * t.to); + let tip = if (from.x.abs() - 1e6).abs() < 1e-3 { from } else { to }; + assert!((tip.x.abs() - 1e6).abs() < 1e-3 && tip.y.abs() < 1e-6, "{deg} {t:?}"); + } } - // A map whose determinant is lost in the rounding of its entries is still refused. + // A determinant a few times its rounding is taken; one lost in the rounding of the map's + // entries is still refused. + assert!(Outline::ellipse(Affine::new([1.0, 0.0, 0.0, 4.0 * f64::EPSILON, 0.0, 0.0])).is_ok()); + assert_eq!(Outline::ellipse(Affine::new([1.0, 0.0, 0.0, f64::EPSILON, 0.0, 0.0])).err(), Some(OutlineError::Empty)); assert_eq!(Outline::ellipse(Affine::new([1.0, 1.0, 1.0, 1.0 + f64::EPSILON, 0.0, 0.0])).err(), Some(OutlineError::Empty)); } From d487dae5b3d31bfab978332f92080b75c98eece1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 19:19:45 -0800 Subject: [PATCH 03/19] Path Precision Tools: Common Tangents refuses a path that turns inward at a join The convexity check compared points sampled along each segment and the curvature inside each segment, but not the corner where one segment meets the next. A segment that leaves its start a little the wrong way could make an inward corner that neither check saw. Each join is now checked by the directions the two segments meet it in, skipping segments of no length. --- .../pathops/src/addons/pathtools/tangents.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/crates/pathops/src/addons/pathtools/tangents.rs b/crates/pathops/src/addons/pathtools/tangents.rs index 9e198229fd..b8a7ce6b6e 100644 --- a/crates/pathops/src/addons/pathtools/tangents.rs +++ b/crates/pathops/src/addons/pathtools/tangents.rs @@ -156,6 +156,16 @@ impl Outline { if segments.iter().any(|s| bends_against(s, sign)) { return Err(OutlineError::NotConvex); } + // A corner can also turn inward between two of the points: each join is checked by the + // directions the segments leave and reach it in. Segments of no length are passed over. + let nonzero = |vs: [Vec2; 3]| vs.into_iter().find(|v| v.hypot() > 1e-9 * size).map(|v| v / v.hypot()); + let ends: Vec<(Vec2, Vec2)> = segments + .iter() + .filter_map(|s| nonzero([s.p1 - s.p0, s.p2 - s.p0, s.p3 - s.p0]).zip(nonzero([s.p3 - s.p2, s.p3 - s.p1, s.p3 - s.p0]))) + .collect(); + if ends.iter().enumerate().any(|(i, (_, end))| ends[(i + 1) % ends.len()].0.cross(*end) * sign > 1e-9) { + return Err(OutlineError::NotConvex); + } let center = (Vec2::new(cx / (3.0 * area2), cy / (3.0 * area2)) * size + origin).to_point(); if !center.x.is_finite() || !center.y.is_finite() { return Err(OutlineError::Empty); @@ -982,6 +992,15 @@ mod tests { bp.close_path(); let bend = vectorcraft_geom::PathData::from_bezpath(&bp).subpaths[0].clone(); assert_eq!(Outline::convex(&bend).err(), Some(OutlineError::NotConvex)); + // A triangle whose first side is a cubic that leaves its start a little the wrong way: the + // corner there turns inward, though the checked points and the curve itself turn one way. + let mut bp = vectorcraft_geom::BezPath::new(); + bp.move_to((0.0, 0.0)); + bp.curve_to((-1.0, -1.0), (66.0, -2.0), (100.0, 0.0)); + bp.line_to((50.0, 100.0)); + bp.close_path(); + let notch = vectorcraft_geom::PathData::from_bezpath(&bp).subpaths[0].clone(); + assert_eq!(Outline::convex(¬ch).err(), Some(OutlineError::NotConvex)); // A square traced twice around winds around twice. let twice: Vec = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].repeat(2).into_iter().map(Point::from).collect(); assert_eq!(Outline::convex(&SubPath::polyline(&twice, true)).err(), Some(OutlineError::NotConvex)); From 83f21f44965f725989bff6276f0b1ece48e8c3bb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 19:36:17 -0800 Subject: [PATCH 04/19] Path Precision Tools: Common Tangents adds the centerline between tiny paths The centerline was left out whenever the two centers were less than 1e-9 points apart, so two separate paths a billionth of a point wide got their tangents but no centerline. Centers now count as one point only when they are closer than a billionth of the larger path's size. --- crates/engine/src/cmd/addons/pathtools/tangents.rs | 3 ++- .../src/cmd/addons/pathtools/tangents/tests.rs | 13 +++++++++++++ crates/pathops/src/addons/pathtools/tangents.rs | 2 +- 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/addons/pathtools/tangents.rs b/crates/engine/src/cmd/addons/pathtools/tangents.rs index 4376cbe791..8102777687 100644 --- a/crates/engine/src/cmd/addons/pathtools/tangents.rs +++ b/crates/engine/src/cmd/addons/pathtools/tangents.rs @@ -96,7 +96,8 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result { }; return Ok(json!({ "ids": [], "external": 0, "internal": 0, "centerline": null, "warning": warning.to_string() })); } - let center = (centerline && (a.center() - b.center()).hypot() > 1e-9).then(|| (a.center(), b.center())); + // Centers closer than a billionth of the larger path's size count as one point: no line. + let center = (centerline && (a.center() - b.center()).hypot() > 1e-9 * a.size().max(b.size())).then(|| (a.center(), b.center())); let fill = Paint::None; let stroke = if s.paint.stroke.is_none() { Paint::solid(Color::BLACK) } else { s.paint.stroke.clone() }; let mut look = s.new_art_look(fill, stroke, s.paint.stroke_width.max(0.1)); diff --git a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs index 5ed6e2b0d6..aef694bbdd 100644 --- a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs @@ -162,6 +162,19 @@ fn a_convex_bezier_path_and_the_centerline() { } } +#[test] +fn tiny_paths_close_together_still_get_the_centerline() { + // Two circles a ten-billionth of a point wide, half a billionth apart: separate, with all four + // tangents, and centers apart by far more than their sizes' rounding. + let mut s = session(); + let a = circle(&mut s, 1.0, 1.0, 1e-10); + let b = circle(&mut s, 1.0 + 5e-10, 1.0, 1e-10); + let r = s.execute(C, &json!({"ids": [a.0, b.0], "centerline": true})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(2)), "{r}"); + assert_eq!(r["ids"].as_array().map(Vec::len), Some(5), "{r}"); + assert_eq!(r["centerline"], r["ids"][4]); +} + #[test] fn the_lines_take_the_current_stroke_and_no_fill() { let mut s = session(); diff --git a/crates/pathops/src/addons/pathtools/tangents.rs b/crates/pathops/src/addons/pathtools/tangents.rs index b8a7ce6b6e..a42e628cad 100644 --- a/crates/pathops/src/addons/pathtools/tangents.rs +++ b/crates/pathops/src/addons/pathtools/tangents.rs @@ -259,7 +259,7 @@ impl Outline { } /// The diagonal of the bounds (an ellipse's: of the box its axes span). - fn size(&self) -> f64 { + pub fn size(&self) -> f64 { match self { Outline::Ellipse { m, .. } => { let [a, b, c, d] = *m; From d738e7f0c0816fc3ce86f0f81cb11e082121d67e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 21:31:37 -0800 Subject: [PATCH 05/19] Image Trace: Flat Logo traces a disc on a gray panel without slivers of a paler ground When the colors of an image lie on one line, as a pale gray ground, a gray panel and a charcoal disc do, an edge pixel between the panel and the disc is also reproduced by a mix of the ground and the disc. Flat Logo switches such a pixel to the mix of the classes beside it only when its neighbors lie on both sides of the class it drops, which a class beyond both classes of the edge never satisfies. A charcoal disc on a gray panel on a paler ground traced with 28 slivers of the ground, of at most two pixels each, around it when its edges were sharp, and with one sliver when they were blurred by 0.7 pixel, with the colors found or named. A pixel now also takes the mix of the classes beside it when the class it drops lies beyond both of them on their line, the pixel's own neighbors lie on each side of it, no neighbor lies past the nearer of the two toward the dropped class, and a chain of neighbors, each nearer that class than the one before, leads from the pixel, in at most 6 steps, to that class's color or to a flat area of that class. A class named some levels off the color of its flat areas still counts. The pixels of a pale line on the disc, whether one pixel wide, blurred over three pixels or falling between two pixels, and the edge of a gap of the ground's color between the disc and the panel keep the ground in their mixes. An edge blurred by a pixel or more can still leave slivers of the ground. Docs: docs/image-trace-adjustments.md, docs/target-app-parity.md. --- crates/trace/src/logo/tests.rs | 32 ++++++ crates/trace/src/logo/unmix.rs | 175 +++++++++++++++++++++++++++++--- docs/image-trace-adjustments.md | 13 +++ docs/target-app-parity.md | 1 + 4 files changed, 205 insertions(+), 16 deletions(-) diff --git a/crates/trace/src/logo/tests.rs b/crates/trace/src/logo/tests.rs index 33ab678a1f..2f346a80a1 100644 --- a/crates/trace/src/logo/tests.rs +++ b/crates/trace/src/logo/tests.rs @@ -1158,3 +1158,35 @@ fn a_noisy_hard_edged_gray_between_black_and_white_is_one_shape() { } } } + +#[test] +fn a_disc_on_a_gray_panel_on_a_paler_ground_has_no_slivers_of_the_ground() { + // The panel's gray lies on the line from the ground's gray to the disc's charcoal, so the disc's + // edge pixels are also a mix of the ground and the disc. + let (ground, panel, disc) = ([240, 240, 240], [200, 200, 200], [60, 60, 60]); + for blur in [0.0, 0.7] { + let grays = render(150, 150, blur, move |x, y| { + let (cx, cy) = (x.clamp(35.0, 115.0), y.clamp(35.0, 115.0)); + Some(if (x - 75.0).hypot(y - 75.0) < 30.0 { + disc + } else if (20.0..130.0).contains(&x) && (20.0..130.0).contains(&y) && (x - cx).hypot(y - cy) < 15.0 { + panel + } else { + ground + }) + }); + for named in [false, true] { + let logo_colors = if named { vec!["#F0F0F0".into(), "#C8C8C8".into(), "#3C3C3C".into()] } else { Vec::new() }; + let res = trace(&grays, &TraceParams { logo_colors, ..logo_params() }); + let paths: Vec<_> = res.paths.iter().map(|t| (t.color, t.pixels)).collect(); + assert_eq!(res.paths.len(), 3, "blur {blur}, named {named}: one path per color; {paths:?}"); + for k in 0..16 { + let a = f64::from(k) * std::f64::consts::TAU / 16.0; + let at = Point::new(75.0 + 31.0 * a.cos(), 75.0 + 31.0 * a.sin()); + assert_eq!(top_color(&res, at), Some(panel), "blur {blur}, named {named}: beside the disc at {at:?}"); + } + assert_eq!(top_color(&res, Point::new(8.0, 75.0)), Some(ground), "blur {blur}, named {named}: the ground"); + assert_eq!(top_color(&res, Point::new(75.0, 75.0)), Some(disc), "blur {blur}, named {named}: the disc"); + } + } +} diff --git a/crates/trace/src/logo/unmix.rs b/crates/trace/src/logo/unmix.rs index 3268c9c20a..d148309d50 100644 --- a/crates/trace/src/logo/unmix.rs +++ b/crates/trace/src/logo/unmix.rs @@ -5,7 +5,8 @@ //! runs, so each pixel is instead explained as a mix of at most three classes, whichever mix //! reproduces the pixel best. When another mix also reproduces it (with a gray between black and //! white among the classes, a black-to-white edge pixel is a mix of black and gray as well as of -//! black and white), the pixel takes the mix whose classes lie nearest it in the flat areas around it, +//! black and white, and a gray-to-black edge pixel is a mix of white and black as well as of gray +//! and black), the pixel takes the mix whose classes lie nearest it in the flat areas around it, //! when its neighbors show an edge between those classes. use std::collections::{HashMap, HashSet}; @@ -217,7 +218,7 @@ pub(crate) fn unmix(pix: &[Px], width: usize, height: usize, classes: &[[f64; 4] continue; } let Some(mixes) = mixed.get(&key) else { continue }; - let edges: Vec<&Weights> = mixes.tied.iter().filter(|m| across_edge(pix, width, height, i, classes, &mixes.best, m)).collect(); + let edges: Vec<&Weights> = mixes.tied.iter().filter(|m| across_edge(pix, &flat, (width, height), i, classes, &mixes.best, m)).collect(); if edges.is_empty() { continue; } @@ -244,10 +245,24 @@ pub(crate) fn unmix(pix: &[Px], width: usize, height: usize, classes: &[[f64; 4] /// Whether pixel `i` lies on an edge between the two classes of `other`, rather than in an area of /// a class of `best` that `other` leaves out: for each such class, the pixel has a neighbor beyond -/// it toward each class of `other`, along the line between them. (A black-to-white edge pixel as -/// light as a gray has a darker neighbor and a lighter one; a gray stroke on white has no neighbor -/// darker than the gray.) -fn across_edge(pix: &[Px], width: usize, height: usize, i: usize, classes: &[[f64; 4]], best: &Weights, other: &Weights) -> bool { +/// it toward each class of `other`, along the line between them, or, for a class that lies beyond +/// both classes of `other` on that line, a neighbor on each side of the pixel itself, none past +/// the class of `other` nearer the class left out, and a chain of neighbors from the pixel to that +/// nearer class or a flat area of it (`flat`), each nearer it than the one before. (A black-to-white +/// edge pixel as light as a gray has a darker neighbor and a lighter one; a gray stroke on white +/// has no neighbor darker than the gray; a gray-to-black edge pixel has a lighter neighbor and a +/// darker one, and lighter pixels lead to the flat gray; a pale line one pixel wide on black has +/// only darker neighbors; the pixels beside a blurred pale line's middle reach no flat gray; and a +/// white gap between black and gray has a neighbor lighter than the gray.) +fn across_edge( + pix: &[Px], + flat: &[Option], + (width, height): (usize, usize), + i: usize, + classes: &[[f64; 4]], + best: &Weights, + other: &Weights, +) -> bool { let [(a, _), (b, _)] = other.as_slice() else { return false }; let (Some(ca), Some(cb)) = (classes.get(*a), classes.get(*b)) else { return false }; let ab: [f64; 4] = std::array::from_fn(|j| cb[j] - ca[j]); @@ -262,21 +277,75 @@ fn across_edge(pix: &[Px], width: usize, height: usize, i: usize, classes: &[[f6 let off = (0..4).map(|j| (v[j] - ca[j] - t * ab[j]).powi(2)).sum::().sqrt(); (t, off) }; - let (x, y) = (i % width.max(1), i / width.max(1)); - let neighbors: Vec = (y.saturating_sub(1)..(y + 2).min(height)) - .flat_map(|yy| (x.saturating_sub(1)..(x + 2).min(width)).map(move |xx| yy * width + xx)) - .filter(|&j| j != i) - .filter_map(|j| pix.get(j)) - .map(|q| place([f64::from(q[0]), f64::from(q[1]), f64::from(q[2]), f64::from(q[3])])) - .filter(|&(_, off)| off <= 2.0 * PURE) - .map(|(t, _)| t) - .collect(); + // Where pixel `j` lies along the line, when it lies within `2 * PURE` of it. + let at = |j: usize| { + pix.get(j) + .map(|q| place([f64::from(q[0]), f64::from(q[1]), f64::from(q[2]), f64::from(q[3])])) + .filter(|&(_, off)| off <= 2.0 * PURE) + .map(|(t, _)| t) + }; + // The pixels around pixel `j`. + let around = |j: usize| { + let (x, y) = (j % width.max(1), j / width.max(1)); + (y.saturating_sub(1)..(y + 2).min(height)) + .flat_map(move |yy| (x.saturating_sub(1)..(x + 2).min(width)).map(move |xx| yy * width + xx)) + .filter(move |&n| n != j) + }; + let neighbors: Vec = around(i).filter_map(at).collect(); let left_out: Vec = best.iter().filter(|&&(c, w)| w > 0.0 && c != *a && c != *b).map(|&(c, _)| c).collect(); + // Whether the pixel has a neighbor on each side of place `t` along the line. + let straddled = |t: f64| neighbors.iter().any(|&tn| (t - tn) * len > PURE) && neighbors.iter().any(|&tn| (tn - t) * len > PURE); + // Whether pixel `j`, at place `t`, lies within `PURE` of class `c` (at place `to`), or in a flat + // area of class `c` ([`flat_classes`]), or beside one and within `PURE` of its color along the + // line (as when `c` is named some levels off the area's color). + let touches = |j: usize, t: f64, c: usize, to: f64| { + let in_c = |n: usize| flat.get(n).copied().flatten() == Some(c); + (t - to).abs() * len <= PURE || in_c(j) || around(j).any(|n| in_c(n) && at(n).is_some_and(|tn| (tn - t).abs() * len <= PURE)) + }; + // Whether a chain of neighbors from the pixel, each nearer place `to` than the one before and + // none past it (`past`), comes to class `c` ([`touches`]) in at most `NEARBY` steps. (From a + // pixel beside a pale line's middle, the middle is the only neighbor nearer the gray, and it has + // none, and it is far from the gray.) + let reaches = |to: f64, c: usize, past: &dyn Fn(f64) -> bool| { + let Some(t) = at(i) else { return false }; + let mut front = vec![(i, t)]; + let mut seen = HashSet::from([i]); + for step in 0..=NEARBY { + let mut next = Vec::new(); + for &(j, t) in &front { + if touches(j, t, c, to) { + return true; + } + if step < NEARBY { + for n in around(j) { + if let Some(tn) = at(n).filter(|&tn| !past(tn) && (tn - to).abs() < (t - to).abs()) + && seen.insert(n) + { + next.push((n, tn)); + } + } + } + } + if next.is_empty() { + return false; + } + front = next; + } + false + }; !left_out.is_empty() && left_out.iter().all(|&c| { let Some(&cv) = classes.get(c) else { return false }; let (tc, _) = place(cv); - neighbors.iter().any(|&t| (tc - t) * len > PURE) && neighbors.iter().any(|&t| (t - tc) * len > PURE) + if straddled(tc) { + return true; + } + if (0.0..=1.0).contains(&tc) { + return false; + } + let beyond = |tn: f64| if tc < 0.0 { -tn * len > PURE } else { (tn - 1.0) * len > PURE }; + let (to, near) = if tc < 0.0 { (0.0, *a) } else { (1.0, *b) }; + !neighbors.iter().any(|&tn| beyond(tn)) && at(i).is_some_and(straddled) && reaches(to, near, &beyond) }) } @@ -670,6 +739,80 @@ mod tests { } } + #[test] + fn an_edge_pixel_takes_no_class_beyond_both_classes_beside_it() { + // A pale ground, a gray and a charcoal on one line: a row of flat gray, one edge pixel halfway + // to charcoal, flat charcoal. The edge pixel is a mix of the gray and the charcoal, with none + // of the ground in it. + let g = |v: f64| [v / 255.0, v / 255.0, v / 255.0, 1.0]; + let classes = vec![g(240.0), g(200.0), g(60.0), [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0]]; + let px = |v: f32| [v / 255.0, v / 255.0, v / 255.0, 1.0]; + let mut pix = vec![px(200.0); 5]; + pix.push(px(130.0)); + pix.extend([px(60.0); 5]); + let (pl, _, _) = unmix(&pix, 11, 1, &classes); + assert_eq!(pl[0][5], 0.0, "ground in the edge pixel"); + assert!((pl[1][5] - 0.5).abs() < 0.02 && (pl[2][5] - 0.5).abs() < 0.02, "gray {} charcoal {}", pl[1][5], pl[2][5]); + // The cases below are vertical lines: three rows alike, read in the middle row. + // The same edge with the panel's pixels three levels darker than the named gray. + let mut pix = vec![px(197.0); 5]; + pix.push(px(130.0)); + pix.extend([px(60.0); 5]); + let (pl, _, _) = unmix(&pix.repeat(3), 11, 3, &classes); + assert_eq!(pl[0][11 + 5], 0.0, "ground in the edge pixel beside a gray three levels off"); + // An edge pixel whose lightest neighbor leads nowhere, with another chain of lighter pixels + // to the gray. + let outer = [vec![px(200.0); 5], vec![px(170.0)], vec![px(60.0); 7]].concat(); + let middle = [vec![px(200.0); 5], vec![px(170.0), px(130.0), px(180.0)], vec![px(60.0); 5]].concat(); + let (pl, _, _) = unmix(&[outer.clone(), middle, outer].concat(), 13, 3, &classes); + assert_eq!(pl[0][13 + 6], 0.0, "ground in the edge pixel beside a dead end"); + // A pixel half ground and half charcoal between charcoal pixels, flat gray three pixels off: + // a thin pale line on the charcoal, kept. + let mut pix = vec![px(200.0); 3]; + pix.extend([px(60.0); 2]); + pix.push(px(150.0)); + pix.extend([px(60.0); 5]); + let (pl, _, _) = unmix(&pix.repeat(3), 11, 3, &classes); + assert!((pl[0][11 + 5] - 0.5).abs() < 0.02, "the line: ground {}", pl[0][11 + 5]); + // A gap of the ground's color one pixel wide between flat charcoal and flat gray: the pixel + // half charcoal and half ground beside it keeps its ground. + let mut pix = vec![px(60.0); 5]; + pix.extend([px(150.0), px(236.0)]); + pix.extend([px(200.0); 5]); + let (pl, _, _) = unmix(&pix.repeat(3), 12, 3, &classes); + assert!((pl[0][12 + 5] - 0.5).abs() < 0.02, "the gap: ground {}", pl[0][12 + 5]); + // A pale line blurred over three pixels on the charcoal, flat gray five pixels off: the pixels + // beside its middle have a lighter neighbor and a darker one, and keep their ground. + let mut pix = vec![px(200.0); 5]; + pix.extend([px(60.0); 3]); + pix.extend([px(103.0), px(154.0), px(103.0)]); + pix.extend([px(60.0); 9]); + let (pl, _, _) = unmix(&pix.repeat(3), 20, 3, &classes); + for j in [20 + 8, 20 + 10] { + assert!((pl[0][j] - 43.0 / 180.0).abs() < 0.02 && pl[1][j] == 0.0, "the blurred line at {j}: ground {} gray {}", pl[0][j], pl[1][j]); + } + // A pale line one pixel wide that falls between two pixels, covering half of one and three + // quarters of the other: both pixels keep their ground. + let mut pix = vec![px(200.0); 5]; + pix.extend([px(60.0); 3]); + pix.extend([px(150.0), px(195.0)]); + pix.extend([px(60.0); 10]); + let (pl, _, _) = unmix(&pix.repeat(3), 20, 3, &classes); + for (j, want) in [(20 + 8, 0.5), (20 + 9, 0.75)] { + let (ground, gray) = (pl[0][j], pl[1][j]); + assert!((ground - want).abs() < 0.02 && gray == 0.0, "the line between pixels at {j}: ground {ground} gray {gray}"); + } + // An edge from the gray to the charcoal blurred by 0.7 pixel: the pixels between take no + // ground. + let mut pix = vec![px(200.0); 5]; + pix.extend([px(199.97), px(197.8), px(166.7), px(93.3), px(62.2)]); + pix.extend([px(60.0); 5]); + let (pl, _, _) = unmix(&pix.repeat(3), 15, 3, &classes); + for j in [15 + 7, 15 + 8] { + assert_eq!(pl[0][j], 0.0, "the blurred edge at {j}: ground"); + } + } + #[test] fn row_distances_match_a_scan_of_the_window_around_each_pixel() { // Three classes scattered over 23 x 17 pixels, some pixels holding two, most none. diff --git a/docs/image-trace-adjustments.md b/docs/image-trace-adjustments.md index 2bd58e4df4..4d96ec6299 100644 --- a/docs/image-trace-adjustments.md +++ b/docs/image-trace-adjustments.md @@ -134,6 +134,19 @@ between pixels or is blurred traces as black and white. A flat area whose color some levels off, counts as holding the named colors it is a blend of, and so do the pixels of exactly its color that touch it. +The same holds when the left-out color lies beyond both colors of the edge, as a pale gray ground lies +beyond a gray panel and a charcoal disc: an edge pixel between the panel and the disc is also a blend of +the ground and the disc. Flat Logo reads it as a blend of the panel and the disc when, along the line +through the three colors, the pixel has a neighbor on each side of it, no neighbor lies past the panel +toward the ground, and a chain of neighbors, each nearer the panel's color than the one before, leads +from the pixel, in at most 6 steps, to the panel's color or to a flat area of the panel. The same rule +applies to a left-out color darker than both colors of the edge, and to colors that are not grays. A +charcoal disc on a gray panel on a paler ground then traces with no slivers of the ground around it when +its edges are sharp or blurred by 0.7 pixel. An edge blurred by a pixel or more can still leave slivers +of the ground. The pixels of a pale line on the disc, whether one pixel wide, blurred over three pixels +or falling between two pixels, and the edge of a gap of the ground's color between the disc and the +panel keep the ground in their blends. + **Large images.** An image of more than 1500 pixels on a side is traced as any other, only more slowly, and the trace says so: `imageTrace.make` returns the note in `warnings` and the status bar shows it (the [results optimization](https://helpx.adobe.com/illustrator/using/image-trace-results-optimization.html) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index cc4082ad68..cb7677aa70 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1591,6 +1591,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Image Trace, Flat Logo named colors only:** with `logoColors` named, `"logoWhite": false` traces those colors only, so white areas take the nearest of them and no white is added; a named white is kept, and enclosed transparent areas stay holes; code-drawn tests in `crates/trace` and `crates/engine`. - **Image Trace, Flat Logo flat-art check with named colors:** with `logoColors` named, whether the image is flat art is judged by its own colors, as many as are named, with white, or as the Colors setting gives, whichever is more. Named colors 20 levels off a flat badge's colors still trace it, a hatch on a light ground gives the same result with close and far named colors, a gradient's refusal score does not depend on how far the named colors are from it, and areas of colors that were not named are traced in the named colors instead of being refused; code-drawn tests in `crates/trace`. - **Image Trace, Flat Logo with a color between two others:** an anti-aliased edge pixel between black and white is read as a blend of black and white, not of black and a gray that lies between them, when the flat areas around it and the pixels beside it show that edge, so a black disc beside a gray square on white, with sharp edges or edges blurred by up to about half a pixel, traces with one gray path, the square, instead of the square plus 8 to 24 gray slivers around the disc with the colors found or named exactly (an edge blurred by a pixel or more, or pixel noise of a level or more, can still leave gray slivers); gray strokes two and three pixels wide beside black stay gray (a soft-edged gray stroke about two pixels wide that touches black traces as black and white, and a short one about three pixels wide can lose most or all of its gray), and a one-pixel gray line of at least 13 touching pixels between black and white stays gray (a shorter one, or one that falls between pixels or is blurred, traces as black and white); code-drawn tests in `crates/trace`. +- **Image Trace, Flat Logo with a color beyond both colors of an edge:** an edge pixel between a gray panel and a charcoal disc on a paler gray ground is read as a blend of the panel and the disc, not of the ground and the disc, when the pixels beside it lie on each side of it, none lies past the panel toward the ground, and lighter pixels lead from it to the panel's color or to a flat area of the panel, so the disc traces with three paths, one per color, with the colors found or named, instead of with 28 slivers of the ground around it when its edges are sharp and one sliver when they are blurred by 0.7 pixel (an edge blurred by a pixel or more can still leave slivers of the ground); the pixels of a pale line on the disc, one pixel wide, blurred over three pixels or falling between two pixels, and the edge of a gap of the ground's color between the disc and the panel keep the ground in their blends; code-drawn tests in `crates/trace`. - **Image Trace, Keep Colors:** `"keepColors": ["#rrggbb", …]` traces only the palette colors near a listed color (Abutting: each with the paths the trace of every color gives it; Overlapping: not reaching under the colors left out), in Black and White, Grayscale and Color; code-drawn tests in `crates/trace` and `crates/engine`. - **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own, and regions they bound merge without seams where the lines cross at rounded coordinates (#893); filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points is refused with advice rather than running out of memory, an image over 64 megapixels is traced scaled down to that size (aspect kept, paths at the image's own size) and one over 192 megapixels is refused, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image (a crop box on the image, starting on its part over the artboard, dragged by its handles or inside it, the outside dimmed, with X/Y/W/H, Apply and Cancel in the Control bar, Enter and Escape, #734; an image that isn't turned or skewed, isn't CMYK and can be read at its recorded size is cut from its own pixels when the crop edges fall on its pixel grid, copied as they are without resampling; any other image is drawn, #5534; `object.cropImage {rect}` for agents, `{trim: true}` cuts an image to its pixels that aren't fully transparent, pixel for pixel) and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), View, the Image Trace panel and Expand, plus Release in Properties; the five View modes (Tracing Result, with Outlines, Outlines, Outlines with Source Image, Source Image) redraw a trace on screen without tracing again, are saved with it and `imageTrace.setView` sets them, while exports and Expand keep the result; the panel's Advanced section is a header that stays open or closed as it was left (part of #641); Color mode's Palette: Limited, Full Tone (as many colours as the tones need, Less … More), Automatic (flat art with its own colours, else Full Tone; a heuristic) and Document Library (the most used colours of the document's swatches or a swatch library, filled with the swatch colours as they are), part of #641; Advanced › Create: Fills and/or Strokes, where lines up to the Stroke width trace as stroked centre lines (distance transform, thinning, a skeleton graph with spurs pruned, curve fitting; one width per line; without Fills, wider areas become stroked outlines), part of #641), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror). A single selected mirror repeat shows a prominent axis with a center move handle and two rotation handles. Drag the line or center to change spacing, or an end to change angle; Shift snaps rotation to 45°. The original artwork stays in place, the reflected copy previews live, Escape cancels and each drag takes one undo step through `object.repeat.options`. Controls follow zoom/view rotation and hide with edges or the bounding box. Engine and headless canvas regressions passed for gestures, history and visibility; native move, rotation and Escape screenshots were reviewed. [Public mirror-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-mirror-repeat-options.html). A single selected grid repeat shows a handle below the grid for rows, one right of it for columns and one past its bottom-right corner for both, and sliders between its first two columns and rows for the horizontal and vertical spacing; the source keeps its size, each drag is one undo step and Escape cancels it ([public grid-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html), #2691). Object › Expand turns radial, grid and mirror repeats into groups of their instances (#1765, #1756). While Crop Image shows its box, the Control bar also sets the cropped image's resolution (PPI: a list of 72, 96, 150, 200 and 300 ppi with the ones above the image's own disabled, or a typed value; at most the image's own, or 300 ppi for a linked image ([Crop Image](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=352))), a reference point that X and Y name and that W and H resize about, and a link that keeps W and H in proportion; `object.cropImage {ppi}` resamples the cut pixels and refuses a resolution above the limit, and `tool.setOption` sets `ppi`, `reference` and `linked` ([Crop images](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/crop-images-in-illustrator.html)). The list's resolutions and the default (the image's own resolution, the center, unlinked) are VectorCraft's own. From 160207e9f2d3de7fe87a2caabd805cff853f4cb6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 03:32:11 -0800 Subject: [PATCH 06/19] EPS import: readhexstring and readline read the data in one pass readhexstring and readline called the one-byte file read for every input character, copying each byte into a new vector. They now scan the bytes left in the file in one slice and advance the file by the bytes they used. The results are unchanged: the same bytes, the same boolean, the same next unread byte, from the program's own file (after the whitespace that ends the last token), a decoded buffer and a filter decoded when first read. readhexstring stops on the digit that completes the last byte and drops a lone digit at the end of the data; readline takes CR LF as one line ending, leaves the byte after a lone CR unread, and leaves the line ending unread when the line fills the string. Tests run the new readers next to copies of the byte-at-a-time loops over 13 stream forms and several hundred inputs, comparing the result and everything left to read; an image read through a readhexstring procedure is compared with the same samples given as a hexadecimal string. The import fuzz tests gain readline and a case for both operators. data_op allows clippy::cognitive_complexity. Without the allow, clippy rates it 54 against the limit of 30; with the old loops in place it passes. --- crates/engine/tests/import_fuzz.rs | 28 +- crates/eps/src/import.rs | 2 + crates/eps/src/import/data/ops.rs | 102 +++++--- crates/eps/src/import/tests_images.rs | 17 ++ crates/eps/src/import/tests_reads.rs | 359 ++++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 6 files changed, 466 insertions(+), 43 deletions(-) create mode 100644 crates/eps/src/import/tests_reads.rs diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 5614aef56a..f8d1ecaa61 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -2776,6 +2776,32 @@ proptest! { paste_from_elsewhere("clipboard.importEps", json!({"dataBase64": vectorcraft_format::base64_encode(ps.as_bytes())}))?; } + /// Any bytes read by `readhexstring` or `readline` into strings of any length, from the + /// program's own file, through a filter decoded when first read, or from a file being run: + /// read as data, or as an error. + #[test] + fn eps_readhexstring_and_readline_data_never_panic( + data in prop::collection::vec(prop::sample::select(vec![b'0', b'9', b'a', b'F', b'g', b' ', b'\t', b'\r', b'\n', b'>', b'%', b'(', 0u8, 0xff]), 0..300), + len in 0usize..40, + line in any::(), + source in 0usize..3, + ) { + let op = if line { "readline" } else { "readhexstring" }; + let file = if source == 1 { "currentfile /ASCIIHexDecode filter" } else { "currentfile" }; + let reads = format!("/s {len} string def /f {file} def 30 {{ f s {op} pop pop }} repeat"); + let mut bytes = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec(); + if source == 2 { + bytes.extend_from_slice(format!("currentfile 0 (endstream) /SubFileDecode filter cvx exec\n{reads}\n").as_bytes()); + bytes.extend_from_slice(&data); + bytes.extend_from_slice(b"\nendstream\nshowpage\n"); + } else { + bytes.extend_from_slice(format!("{reads}\n").as_bytes()); + bytes.extend_from_slice(&data); + bytes.extend_from_slice(b"\nshowpage\n"); + } + survive("readhexstring and readline data", || vectorcraft_eps::import(&bytes).ok().map(|r| r.document))?; + } + /// Damaged or hostile CMYK images (a CMYK JPEG, an image with a key color): read as images, /// or as an error. #[test] @@ -3004,7 +3030,7 @@ fn arb_ps_token() -> impl Strategy { "gsave", "grestore", "save", "restore", "concat", "translate", "scale", "rotate", "setlinewidth", "setdash", "setgray", "setrgbcolor", "setcmykcolor", "sethsbcolor", "setcolorspace", "setcolor", "setpattern", "makepattern", "shfill", "arc", "arcn", "arct", "arcto", "rectfill", "rectclip", "rectstroke", "image", "imagemask", "colorimage", "currentfile", "filter", - "readhexstring", "readstring", "show", "stringwidth", "charpath", "findfont", "scalefont", "makefont", "setfont", "selectfont", + "readhexstring", "readstring", "readline", "show", "stringwidth", "charpath", "findfont", "scalefont", "makefont", "setfont", "selectfont", "def", "bind", "load", "dup", "exch", "pop", "roll", "index", "copy", "for", "repeat", "loop", "exit", "if", "ifelse", "exec", "stopped", "begin", "end", "dict", "array", "string", "get", "put", "getinterval", "putinterval", "aload", "astore", "forall", "[", "]", "<<", ">>", "{", "}", "matrix", "currentmatrix", "setmatrix", "transform", "itransform", "invertmatrix", "pathbbox", diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index 4e9fcc58ae..259be45eac 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -68,6 +68,8 @@ mod tests_images; #[cfg(test)] mod tests_native; #[cfg(test)] +mod tests_reads; +#[cfg(test)] mod tests_type1; #[cfg(test)] mod tests_type42; diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index 04e5431d30..392dbabae8 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -31,6 +31,7 @@ pub(super) enum Source { } impl Interp<'_> { + #[allow(clippy::cognitive_complexity)] // One arm for each file operator, most of them a few lines. pub fn data_op(&mut self, op: Op) -> Res { use Op::*; match op { @@ -50,23 +51,7 @@ impl Interp<'_> { ReadLine => { let s = self.pop_str()?; let Obj::File { stream: f, .. } = self.pop()? else { return ps_err("typecheck", "") }; - let n = s.len(); - let mut line = vec![]; - let mut ended = false; - while line.len() < n { - match self.read(&f, 1)?.first() { - Some(b'\n') | None => { - ended = true; - break; - } - Some(b'\r') => { - self.skip_lf(&f); - ended = true; - break; - } - Some(b) => line.push(*b), - } - } + let (line, ended) = self.read_line(&f, s.len())?; self.fill(s, &line)?; self.push(Obj::Bool(ended))?; } @@ -219,38 +204,71 @@ impl Interp<'_> { }) } - /// After `readline` consumes CR, consume only an immediately following LF. PostScript - /// treats CR/LF as one line ending (PLRM §3.8); raw reads must keep every other byte. - /// The preceding `read` has already materialized any pending filter. - fn skip_lf(&mut self, f: &Rc>) { - match &mut *f.borrow_mut() { + /// Run `scan` over the bytes left in file `f`, in one slice, and consume as many of them as + /// it says it used. A file still pending after `materialize` has no bytes left. + fn scan(&mut self, f: &Rc>, scan: impl FnOnce(&[u8]) -> (T, usize)) -> Res { + self.materialize(f)?; + Ok(match &mut *f.borrow_mut() { Stream::Current => { - if self.lex.rest().first() == Some(&b'\n') { - self.lex.advance(1); - } + let (found, used) = scan(self.lex.data()); + self.lex.advance(used); + found } Stream::Buf { data, pos, .. } => { - if data.get(*pos) == Some(&b'\n') { - *pos += 1; - } + let start = (*pos).min(data.len()); + let (found, used) = scan(data.get(start..).unwrap_or_default()); + *pos = start.saturating_add(used).min(data.len()); + found } - Stream::Pending { .. } => {} - } + Stream::Pending { .. } => scan(&[]).0, + }) } - /// Up to `n` bytes read as hexadecimal digits from `f` (other characters skipped). - pub(in super::super) fn read_hex(&mut self, f: &Rc>, n: usize) -> Res> { - let mut out = Vec::with_capacity(n); - let mut high: Option = None; - while out.len() < n { - let Some(&b) = self.read(f, 1)?.first() else { break }; - let Some(v) = char::from(b).to_digit(16) else { continue }; - match high.take() { - Some(h) => out.push(h << 4 | v as u8), - None => high = Some(v as u8), - } + /// `readline` from `f` into a string of `n` bytes: the line, and whether it ended at a line + /// ending or at the end of the data. The line ending is consumed and left out of the line. + /// CR LF is one line ending (PLRM §3.8), and a lone CR leaves the byte after it unread. A + /// line that fills the string leaves the bytes after it unread, a line ending included. + pub(in super::super) fn read_line(&mut self, f: &Rc>, n: usize) -> Res<(Vec, bool)> { + if n == 0 { + return Ok((vec![], false)); } - Ok(out) + self.scan(f, |data| { + let room = data.get(..n).unwrap_or(data); + match room.iter().position(|b| matches!(b, b'\n' | b'\r')) { + Some(i) => { + let crlf = room.get(i) == Some(&b'\r') && data.get(i + 1) == Some(&b'\n'); + ((room.get(..i).unwrap_or_default().to_vec(), true), i + 1 + usize::from(crlf)) + } + None if room.len() == n => ((room.to_vec(), false), n), + None => ((room.to_vec(), true), room.len()), + } + }) + } + + /// Up to `n` bytes read as hexadecimal digits from `f` (other characters skipped). The read + /// stops at the digit that completes the `n`th byte and leaves what follows unread. A lone + /// digit at the end of the data gives no byte. + pub(in super::super) fn read_hex(&mut self, f: &Rc>, n: usize) -> Res> { + if n == 0 { + return Ok(vec![]); + } + self.scan(f, |data| { + let mut out = Vec::with_capacity(n.min(data.len() / 2)); + let mut high: Option = None; + let mut used = 0; + for &b in data { + if out.len() == n { + break; + } + used += 1; + let Some(v) = char::from(b).to_digit(16) else { continue }; + match high.take() { + Some(h) => out.push(h << 4 | v as u8), + None => high = Some(v as u8), + } + } + (out, used) + }) } /// Skip the whitespace and the `>` that end hexadecimal data in `f`, if a `>` is next: the diff --git a/crates/eps/src/import/tests_images.rs b/crates/eps/src/import/tests_images.rs index 193b81a233..82a06e5f0e 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -106,6 +106,23 @@ fn image_data_comes_from_the_file_being_run() { ); } +/// An image whose procedure reads its rows with `readhexstring` comes out with the same pixels as +/// the same samples given as one hexadecimal string, with the digits broken by CR LF, LF, tabs, +/// spaces and characters that are not digits, read from the program's own file and from a file +/// being run. +#[test] +fn hex_rows_read_by_a_procedure_match_a_hexadecimal_string() { + let rgb: Vec = (0..36u32).map(|i| (i * 37 % 256) as u8).collect(); + let digits = hex(&rgb); + let breaks = ["\r\n", "\n", "\t", " z", "%"]; + let broken: String = digits.as_bytes().chunks(5).zip(breaks.iter().cycle()).map(|(d, b)| format!("{}{b}", String::from_utf8_lossy(d))).collect(); + let want = pixels(&read(&format!("10 10 scale 4 3 8 [4 0 0 -3 0 3] <{digits}> false 3 colorimage")), 4, 3); + assert_eq!(want, rgb.chunks(3).map(|p| [p[0], p[1], p[2], 255]).collect::>()); + let image = "10 10 scale 4 3 8 [4 0 0 -3 0 3] {currentfile 12 string readhexstring pop} false 3 colorimage"; + assert_eq!(pixels(&read(&format!("{image}\r\n{broken}\n")), 4, 3), want); + assert_eq!(pixels(&read(&format!("currentfile 0 (endstream) /SubFileDecode filter cvx exec\n{image}\n{broken}\nendstream\n")), 4, 3), want); +} + /// A filter waits until it is first read, then reads the file it was made over, wherever the /// program runs by then: one over the program's own file, read in a file being run, and one over /// a file being run, read in a file that one runs. diff --git a/crates/eps/src/import/tests_reads.rs b/crates/eps/src/import/tests_reads.rs new file mode 100644 index 0000000000..3220edd028 --- /dev/null +++ b/crates/eps/src/import/tests_reads.rs @@ -0,0 +1,359 @@ +//! `readhexstring` and `readline` (PLRM 3rd ed., §8.2) read the data left in a file in one pass. +//! The tests run the one-pass readers next to reference readers that take one byte per call, on the +//! same data in the same interpreter state: the program's own file after the whitespace that ends +//! the last token, a decoded buffer read from its start or part way in, and a filter decoded when it +//! is first read. The bytes, the result or error, and every byte left unread must agree. + +use std::cell::RefCell; +use std::fmt::Debug; +use std::rc::Rc; +use std::time::{Duration, Instant}; + +use vectorcraft_doc::Document; +use vectorcraft_geom::{Affine, Rect}; + +use super::data::Stream; +use super::graphics::{GState, Out}; +use super::interp::Interp; +use super::obj::{Obj, Res}; + +type File = Rc>; + +/// Bytes as hexadecimal digits. +fn hex(data: &[u8]) -> String { + data.iter().map(|b| format!("{b:02x}")).collect() +} + +/// An interpreter that has run `src` up to its `quit`, and the file object the program left on the +/// operand stack. What follows `quit` in `src` is still unread. +fn file_after(src: &[u8]) -> (Interp<'_>, File) { + let mut doc = Document::new(100.0, 100.0); + doc.layers.clear(); + let page = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 100.0]); + let mut it = Interp::new(src, GState::default(), Out::new(doc, page, Rect::new(0.0, 0.0, 100.0, 100.0))); + assert_eq!(it.run(), Ok(()), "{}", String::from_utf8_lossy(src)); + let Ok(Obj::File { stream, .. }) = it.pop() else { panic!("no file on the stack: {}", String::from_utf8_lossy(src)) }; + (it, stream) +} + +/// The reference `readline`: one byte per call, a CR followed by an LF ending the line once. +fn line_by_bytes(it: &mut Interp, f: &File, n: usize) -> Res<(Vec, bool)> { + let mut line = vec![]; + let mut ended = false; + while line.len() < n { + match it.read(f, 1)?.first() { + Some(b'\n') | None => { + ended = true; + break; + } + Some(b'\r') => { + match &mut *f.borrow_mut() { + Stream::Current => { + if it.lex.rest().first() == Some(&b'\n') { + it.lex.advance(1); + } + } + Stream::Buf { data, pos, .. } => { + if data.get(*pos) == Some(&b'\n') { + *pos += 1; + } + } + Stream::Pending { .. } => {} + } + ended = true; + break; + } + Some(b) => line.push(*b), + } + } + Ok((line, ended)) +} + +/// The reference `readhexstring`: one byte per call, characters that are not hexadecimal digits +/// skipped. +fn hex_by_bytes(it: &mut Interp, f: &File, n: usize) -> Res> { + let mut out = Vec::with_capacity(n); + let mut high: Option = None; + while out.len() < n { + let Some(&b) = it.read(f, 1)?.first() else { break }; + let Some(v) = char::from(b).to_digit(16) else { continue }; + match high.take() { + Some(h) => out.push(h << 4 | v as u8), + None => high = Some(v as u8), + } + } + Ok(out) +} + +fn line_one_pass(it: &mut Interp, f: &File, n: usize) -> Res<(Vec, bool)> { + it.read_line(f, n) +} + +fn hex_one_pass(it: &mut Interp, f: &File, n: usize) -> Res> { + it.read_hex(f, n) +} + +/// Hexadecimal data as CID `StartData` reads it: the digits, then a closing `>` if one is next. +fn hex_and_end_one_pass(it: &mut Interp, f: &File, n: usize) -> Res> { + let d = it.read_hex(f, n)?; + it.skip_hex_end(f)?; + Ok(d) +} + +fn hex_and_end_by_bytes(it: &mut Interp, f: &File, n: usize) -> Res> { + let d = hex_by_bytes(it, f, n)?; + it.skip_hex_end(f)?; + Ok(d) +} + +/// How the program reaches the data. +#[derive(Clone, Copy, Debug)] +enum Form { + /// `currentfile`, with this whitespace after the token before the data. + Current(&'static [u8]), + /// A buffer decoded at once, with this many bytes of it read before the data. + Buf(usize), + /// An `ASCIIHexDecode` filter over `currentfile`, decoded when it is first read, with this + /// whitespace after the token before the digits. + Pending(&'static [u8]), +} + +const FORMS: [Form; 13] = [ + Form::Current(b" "), + Form::Current(b"\n"), + Form::Current(b"\r"), + Form::Current(b"\r\n"), + Form::Current(b"\r\r\n"), + Form::Current(b"\n\r"), + Form::Current(b"\t\t"), + Form::Buf(0), + Form::Buf(2), + Form::Buf(3), + Form::Pending(b"\n"), + Form::Pending(b"\r\n"), + Form::Pending(b" "), +]; + +/// A program that leaves a file over `data` on the operand stack, in form `form`. +fn program(form: Form, data: &[u8]) -> Vec { + match form { + Form::Current(lead) => [b"currentfile quit".as_slice(), lead, data].concat(), + Form::Buf(0) => format!("<{}> /ReusableStreamDecode filter quit", hex(data)).into_bytes(), + Form::Buf(skip) => { + let before = b"\r\n\r".get(..skip).unwrap_or(b"\r\n\r".as_slice()); + format!("<{}{}> /ReusableStreamDecode filter dup {skip} string readstring pop pop quit", hex(before), hex(data)).into_bytes() + } + Form::Pending(lead) => [b"currentfile /ASCIIHexDecode filter quit".as_slice(), lead, hex(data).as_bytes(), b"> tail"].concat(), + } +} + +type Reader = fn(&mut Interp, &File, usize) -> Res; + +/// Read `data` in `form` with `one_pass` and with `by_bytes` in two interpreters in the same state, +/// and check that they agree on the result and on everything left to read. +fn agree(form: Form, data: &[u8], n: usize, one_pass: Reader, by_bytes: Reader) { + let src = program(form, data); + let (mut a, fa) = file_after(&src); + let (mut b, fb) = file_after(&src); + let at = || format!("{form:?}, {:?}, n = {n}", String::from_utf8_lossy(data)); + assert_eq!(one_pass(&mut a, &fa, n), by_bytes(&mut b, &fb, n), "result: {}", at()); + assert_eq!(a.lex.rest(), b.lex.rest(), "program left unread: {}", at()); + assert_eq!(a.read(&fa, usize::MAX), b.read(&fb, usize::MAX), "file left unread: {}", at()); + assert_eq!(a.lex.rest(), b.lex.rest(), "program left after the file: {}", at()); + a.release(); + b.release(); +} + +/// A fixed sequence of pseudo-random numbers (xorshift), so a failure repeats. +struct Rng(u64); + +impl Rng { + fn below(&mut self, n: usize) -> usize { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + (self.0 % n.max(1) as u64) as usize + } +} + +/// `chosen`, then `count` strings of up to 24 bytes from `alphabet`. +fn samples(chosen: &[&[u8]], alphabet: &[u8], count: usize, rng: &mut Rng) -> Vec> { + let random = (0..count).map(|_| { + let len = rng.below(25); + (0..len).filter_map(|_| alphabet.get(rng.below(alphabet.len())).copied()).collect() + }); + chosen.iter().map(|s| s.to_vec()).chain(random).collect() +} + +/// String lengths to read `data` with: none, one, past its end, exactly its length and one more, +/// and one at random. +fn lengths(data: &[u8], rng: &mut Rng) -> [usize; 6] { + [0, 1, 3, data.len(), data.len() + 1, rng.below(data.len() + 3)] +} + +#[test] +fn readline_reads_in_one_pass_as_byte_by_byte() { + let mut rng = Rng(0x9e37_79b9_7f4a_7c15); + let chosen: [&[u8]; 16] = [ + b"", + b"\n", + b"\r", + b"\r\n", + b"\n\r", + b"\r\r\n", + b"abc", + b"abc\n", + b"abc\r", + b"abc\rX", + b"abc\r\nX", + b"abc\n\nX", + b"abcdefgh\r\nX", + b"abcdefgh\nX", + b"a\0b\xff\rX", + b"abc\r\n", + ]; + for data in samples(&chosen, b"ab\r\n\r\n x\0\xff", 40, &mut rng) { + for form in FORMS { + for n in lengths(&data, &mut rng) { + agree(form, &data, n, line_one_pass, line_by_bytes); + } + } + } +} + +#[test] +fn readhexstring_reads_in_one_pass_as_byte_by_byte() { + let mut rng = Rng(0x2545_f491_4f6c_dd1d); + let chosen: [&[u8]; 14] = [ + b"", + b"0", + b"a", + b"0a", + b"0a1", + b"0 a\r\n1b>X", + b"zz0g1", + b"ff\r\n00\nAA", + b"0a1b2c3d", + b"0a1b\r\n2c>", + b"\r\n0a", + b"a b c d e", + b"0a>", + b"0a \r\n >X", + ]; + for data in samples(&chosen, b"0123456789abcdefABCDEFg \r\n\t>z%", 40, &mut rng) { + for form in FORMS { + for n in lengths(&data, &mut rng) { + agree(form, &data, n, hex_one_pass, hex_by_bytes); + agree(form, &data, n, hex_and_end_one_pass, hex_and_end_by_bytes); + } + } + } +} + +/// `readline` of `data` into `n` bytes, after `currentfile` and a CR LF, gives `line` and `ended` +/// and leaves `left` unread. +fn line_case(data: &[u8], n: usize, line: &[u8], ended: bool, left: &[u8]) { + let src = program(Form::Current(b"\r\n"), data); + let (mut it, f) = file_after(&src); + assert_eq!(it.read_line(&f, n), Ok((line.to_vec(), ended)), "{:?}", String::from_utf8_lossy(data)); + assert_eq!(it.read(&f, usize::MAX), Ok(left.to_vec()), "{:?}", String::from_utf8_lossy(data)); + it.release(); +} + +/// `readhexstring` of `data` into `n` bytes, after `currentfile` and a CR LF, gives `bytes` and +/// leaves `left` unread in the program. +fn hex_case(data: &[u8], n: usize, bytes: &[u8], left: &[u8]) { + let src = program(Form::Current(b"\r\n"), data); + let (mut it, f) = file_after(&src); + assert_eq!(it.read_hex(&f, n), Ok(bytes.to_vec()), "{:?}", String::from_utf8_lossy(data)); + assert_eq!(it.lex.rest(), left, "{:?}", String::from_utf8_lossy(data)); + it.release(); +} + +/// The results the one-pass readers give at the edges of the data, stated directly. +#[test] +fn one_pass_reads_stop_where_their_data_ends() { + // A CR LF ends one line; a lone CR leaves the next byte unread. + line_case(b"ab\r\nX", 8, b"ab", true, b"X"); + line_case(b"ab\rX", 8, b"ab", true, b"X"); + line_case(b"ab\nX", 8, b"ab", true, b"X"); + // A line that fills the string leaves its line ending unread. + line_case(b"abcd\nX", 4, b"abcd", false, b"\nX"); + line_case(b"abc\r\nX", 3, b"abc", false, b"\r\nX"); + // The end of the data ends the line. + line_case(b"ab", 8, b"ab", true, b""); + line_case(b"", 8, b"", true, b""); + // The read stops on the digit that completes the last byte. + hex_case(b"0a\r\n1b>X", 2, &[0x0a, 0x1b], b">X"); + // Characters that are not digits are skipped. + hex_case(b"z0 g\ta%", 1, &[0x0a], b"%"); + // A lone digit at the end of the data gives no byte. + hex_case(b"0a1", 2, &[0x0a], b""); + hex_case(b"\r\n", 2, &[], b""); + // No byte to read takes nothing, not even the whitespace after the token. + hex_case(b"0a", 0, &[], b"\r\n0a"); +} + +/// The median of `runs`. +fn median(runs: &[Duration]) -> Duration { + let mut sorted = runs.to_vec(); + sorted.sort(); + sorted.get(sorted.len() / 2).copied().unwrap_or_default() +} + +/// Read all of `src`'s data with `reader` in strings of `n` bytes, `calls` times, and how long it +/// took. The interpreter is made before the clock starts. +fn timed(src: &[u8], reader: Reader, n: usize, calls: usize) -> (Vec, Duration) { + let (mut it, f) = file_after(src); + let start = Instant::now(); + let got: Vec = (0..calls).map(|_| reader(&mut it, &f, n).unwrap_or_else(|e| panic!("{e:?}"))).collect(); + let took = start.elapsed(); + it.release(); + (got, took) +} + +/// Time both readers on `src` in 7 runs, alternating which goes first, check that they read the +/// same, and print every run and the medians. +fn compare(what: &str, src: &[u8], one_pass: Reader, by_bytes: Reader, n: usize, calls: usize) { + let (mut old, mut new) = (vec![], vec![]); + for run in 0..7 { + let order: [bool; 2] = if run % 2 == 0 { [false, true] } else { [true, false] }; + let mut got = vec![]; + for one in order { + let (read, took) = timed(src, if one { one_pass } else { by_bytes }, n, calls); + if one { + new.push(took) + } else { + old.push(took) + } + got.push(read); + } + assert!(got.first() == got.get(1), "{what}: the readers differ"); + } + let ms = |d: &Duration| format!("{:.1}", d.as_secs_f64() * 1000.0); + println!("{what}: {} bytes of data, {calls} calls of {n} bytes", src.len()); + println!(" byte by byte, ms: {}", old.iter().map(ms).collect::>().join(" ")); + println!(" one pass, ms: {}", new.iter().map(ms).collect::>().join(" ")); + let (o, w) = (median(&old), median(&new)); + println!(" median: byte by byte {} ms, one pass {} ms, {:.1}x", ms(&o), ms(&w), o.as_secs_f64() / w.as_secs_f64().max(1e-9)); +} + +/// Times the one-pass readers against the byte-at-a-time reference readers on the same data in one +/// process: the hexadecimal samples of a 1000 × 1000 RGB image in lines of 64 digits, read a row +/// of 3,000 bytes at a time, and 200,000 lines of 40 bytes read by `readline` into an 80-byte +/// string. Run it in release: +/// `cargo test --release -p vectorcraft-eps --lib tests_reads::one_pass_reads_timed -- --ignored --nocapture`. +#[test] +#[ignore = "manual timing probe; wall-clock performance depends on machine load"] +fn one_pass_reads_timed() { + let rgb: Vec = (0..3_000_000u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 24) as u8).collect(); + let digits = hex(&rgb); + let mut data = Vec::with_capacity(digits.len() + digits.len() / 64 + 1); + for line in digits.as_bytes().chunks(64) { + data.extend_from_slice(line); + data.push(b'\n'); + } + compare("readhexstring", &program(Form::Current(b"\n"), &data), hex_one_pass, hex_by_bytes, 3_000, 1_000); + let lines: Vec = (0..200_000).flat_map(|i| format!("{:<39}\n", format!("line {i}")).into_bytes()).collect(); + compare("readline", &program(Form::Current(b"\n"), &lines), line_one_pass, line_by_bytes, 80, 200_000); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..c7531d4f0d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2040,6 +2040,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - A copied `.ai` or `.ait` file that holds a PDF pastes the objects of its editing data as File › Open reads them: every layer's objects go into the active layer in their stacking order, with their names, hidden objects and type objects, instead of the PDF page's art with its type as outlines. When the editing data can't be read, the file pastes its page as before (`clipboard.importPdf {editingData}`). The objects of a hidden layer come in hidden, from a pasted EPS too. - Import and export, later 2026-10-13 merges: SVGs that move objects with a CSS transform (`translate(100px, 0)`, `rotate(45deg)`) or style type with the `font` shorthand import as drawn (#1565); SVG symbols whose shapes use percentage lengths import at the size and place they are drawn, the percentages being of the symbol's `viewBox` (#1596); Inkscape's flowed text (`flowRoot`) opens as area type in its rectangle, a paragraph per `flowPara`, instead of being dropped, and a region that can't be read is left out with a warning (#1569, fixes #1568); the warning for an unsupported SVG filter names the filter, its primitives and the object, and says the object is drawn without it (#1599, fixes #1598); the pages of an Inkscape multi-page SVG become artboards, named by their labels (#1603, fixes #1601); SVG export with CSS classes or style entities stays fast in documents with many distinct styles (#1567); PDF and `.ai` import: evenly letter-spaced or tightened type on a path keeps its length along the path instead of closing up to the font's advances (#1586), and type on a path whose stroke is written glyph by glyph comes in as one text object with its stroke, not one object per glyph (#1585); the ICC profiles embedded in JPEG, TIFF and PSD exports have every tag on a 4-byte boundary (ICC.1 §7.1.2), so strict readers accept them (#1589, fixes #1584); GIF, PNG-8 and other indexed exports find each pixel's palette colour through an index instead of a scan, with identical output (#1576); a zero-length subpath draws its round cap as a dot and its projecting cap as a square, so dots in imported `.ai` and SVG files show (#1619, fixes #1613). - Files and untrusted input, 2026-10-14 merges: EPS import: a stitched shading keeps its hard colour changes (#1654, #1653). WMF/EMF import refuses an oversized embedded PNG or JPEG from its header, before any pixels are decoded (#1776). PDF open no longer takes exponential time on a crafted name tree with shared nodes when it looks for the editing data (#1781). The size limits on a native file's embedded data also apply to files read from memory, not only streamed ones (#1783). Saving over a private file on Unix no longer leaves a readable temporary copy beside it while the file is written (#1778). An Export for Screens suffix can no longer place files outside the export folder (#1777). Package refuses a folder where it would overwrite the open document or one of its linked files (#1786). ruzstd 0.9.1 fixes a decompression bomb (RUSTSEC-2026-0344) reachable from EPS/`.ai` and Affinity import (#1807). File Info dates are stamped only after a save succeeds, so a failed save no longer changes them (#1774). Linked files that change during a drag are updated after the drag instead of being missed (#1773). + - EPS import: `readhexstring` and `readline` read the data left in a file in one pass instead of one byte per call, with the same bytes, result and next unread byte as before (about nine times less reader time on 6 MB of hex image data and on 8 MB of lines). - **Fields, search and window, 2026-10-14 merges:** Fields commit what was typed when you click away or move to another field, as Enter does; Escape still discards it (#1787). Up and Down move through the command search results and Enter runs the highlighted one (#1798, #1757). Slider rails show on Medium Dark (#1808, #1662). On Windows the custom title bar's window stays truly borderless, so the pointer lines up with what is drawn on systems where the hidden caption offset it (#1791, #1758; awaiting the reporter's confirmation). - **Tools, panels and type, later 2026-10-14 merges:** the Transform panel's, Properties panel's and Control bar's X, Y, W and H show and edit the bounds of the anchor points selected with Direct Selection, and a whole-object selection is unchanged (#1839, fixes #1824). With Snap to Grid on, anchors and objects snap to the grid even when Snap to Pixel is also ticked: the grid wins (#1840; #1816 stays open until the reporter confirms). A marquee with the Selection or Direct Selection tool also selects the unlocked ruler guides it crosses (#1836). The toolbar shows no group labels by default (a preference brings them back) and runs on in one or two columns; the All Tools drawer lists the tools by flyout group with their shortcuts, has a menu (Reset, Basic, Advanced) and a Show section for the Fill/Stroke, Coloring, Draw Mode and Screen Mode controls (`toolbar.show`, #1751). An action clicked in the Actions panel stays selected, so Play Current Selection and Delete Selection act on it (#1853, part of #1629; editing actions and action shortcuts remain). Redo pressed during a drag keeps the drag as a step instead of losing the redone edit (#1856, #1719). Preferences are written as soon as OK is pressed, so they survive a session that doesn't end with a normal quit (#1857; #1747 stays open until the reporter confirms). New and Redefine Character Style take the format of the selected text range, also while typing (#1634). Type inside symbols, pattern tiles, graph designs and opacity masks gets its layout bounds back when a native file opens, so warped type in a symbol looks the same after save and reopen (#1833, #1738). Editing, renaming, deleting or merging a global swatch reaches the art of opacity masks, and a swatch used only in a mask is no longer listed as unused (#1830, #1735). On macOS, Save As, Save a Copy and the first Save show their sheet again; the Format menu on the sheet (#866) is withdrawn until the format can be set before the sheet opens, and #866 is open again (#1855; #1800, #1831 and #1518 stay open until confirmed on a Mac). - **Files and untrusted input, later 2026-10-14 merges:** SVG import applies style sheet rules with `:not()` selectors, with their nesting bounded (#1799, #1557), no longer stalls on a style sheet with many stacked descendant selectors over deep nesting (#1834, #1703), and reads an SVG's linked files within the automation roots in force again (#1870). DXF export writes the VPORT record's view direction once (group code 36 was written twice, which strict readers reject, #1789). A deeply nested file no longer overflows the stack: nesting is capped at 32 objects (deeper groups are merged with a warning; SVG past 256 elements and PDF past 256 nested arrays are refused), symbols and patterns that use themselves open without the offending instance or paint, and a document nested more than about 40 deep can no longer be saved to a file that won't open again (#1852). PDF and `.ai` files nested deeply inside compressed streams, page trees holding themselves and functions or colour spaces built on themselves no longer crash the app (hayro 0.8; the import runs on a 16 MB thread, #1871); a decompression bomb or impossible predictor parameters are refused (#1873, #1700, #1701); a brush whose art draws the brush again through a symbol or pattern no longer crashes the app, and graph designs, Affinity, DXF, metafiles and plug-ins were probed with hostile input (#1872). Hostile EPS, Affinity and native files can no longer run memory or CPU away through ASCII85 data, PostScript objects holding themselves, flat-colour pixel layers or far and overlapping data offsets (#1863: #1715, #1714, #1704, #1699), and the save fallback for folders that refuse a rename keeps the old file's content until the new one is in (#1695). A file whose ids sit at their largest value no longer breaks new objects (#1718); a failed `command.batch` puts each document back whole, its file, history and a drag in progress included (#1697); a control request that timed out before the app took it never runs later, and the reply says which case it was (#1725, [control-protocol.md](control-protocol.md)); the Eyedropper and recolouring refuse an image too large as RGBA before decoding it (#1717) (all #1862). A save or export that fails is reported in a dialog that names the file and stays until closed, with the document left modified and the old file untouched (#1685); a browser download that can't start fails the save instead of marking it saved (#1693); a file that finishes opening waits while a dialog is open, so Save As options can't save the wrong document (#1694) (all #1865). krilla is built without its text shaping, so the unmaintained rustybuzz and ttf-parser don't ship (#1874, #1730); the CI gate compiles the web app for wasm, and the web's SVG nesting cap (34) follows from its 1 MiB stack (#1875). From 52bbca2ecb9686f4781b17df109e54d6636367c6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 03:42:20 -0800 Subject: [PATCH 07/19] Type: Show Similar Fonts lists a family with no numbers in common after the measured ones FontLikeness::distance left out every number either face does not give, so a family whose faces give none of them (static faces with no OS/2 or post table) was 0 from every family, and Show Similar Fonts could list it right after the chosen family, as an exact match. Faces that share no number to compare are now f32::INFINITY apart, so such a family comes after every family of its script group that shares one, and families equally far keep their order. The order of measured families does not change. This is VectorCraft's own rule. Builds on #7983, which added Show Similar Fonts. --- crates/engine/src/cmd/fonts.rs | 2 +- crates/text/src/fontdb/lookup.rs | 4 +++- crates/text/src/fontdb/traits.rs | 12 ++++++++++-- crates/text/src/test_fonts.rs | 24 ++++++++++++++++++++++++ crates/text/src/tests/similar.rs | 31 +++++++++++++++++++++++++++++-- docs/mcp.md | 3 ++- docs/target-app-parity.md | 1 + docs/type-parity.md | 2 +- 8 files changed, 71 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/fonts.rs b/crates/engine/src/cmd/fonts.rs index 5a000c3327..f98386bcf1 100644 --- a/crates/engine/src/cmd/fonts.rs +++ b/crates/engine/src/cmd/fonts.rs @@ -58,7 +58,7 @@ pub fn specs() -> Vec { "Show Similar Fonts", [], None, - "{family (any of its names), limit?: whole number 1..100000 (default: all)} → {family: the family's own name, families: [names]}: the families `text.fontList` lists, ordered as a font menu's Show Similar Fonts orders them: the family itself first, then those that set the same script (Japanese, Thai or neither), then the others, each group nearest first by VectorCraft's own measure of the faces nearest an upright Regular (OS/2 PANOSE digits, weight and width classes, x-height, cap height and average character width, the italic angle, and the kind); an error when the family isn't available or the font menus don't list it, or `limit` is not a whole number from 1 to 100000", + "{family (any of its names), limit?: whole number 1..100000 (default: all)} → {family: the family's own name, families: [names]}: the families `text.fontList` lists, ordered as a font menu's Show Similar Fonts orders them: the family itself first, then those that set the same script (Japanese, Thai or neither), then the others, each group nearest first by VectorCraft's own measure of the faces nearest an upright Regular (OS/2 PANOSE digits, weight and width classes, x-height, cap height and average character width, the italic angle, and the kind; a family that shares none of these numbers with it comes after those that share one); an error when the family isn't available or the font menus don't list it, or `limit` is not a whole number from 1 to 100000", always, similar_fonts ), diff --git a/crates/text/src/fontdb/lookup.rs b/crates/text/src/fontdb/lookup.rs index 597e8bbc6c..27302aed2f 100644 --- a/crates/text/src/fontdb/lookup.rs +++ b/crates/text/src/fontdb/lookup.rs @@ -153,7 +153,9 @@ impl FontDb { /// neither, as [`FontTraits`] tells), then the others, each group nearest first by /// [`FontLikeness::distance`](super::FontLikeness::distance) of their /// [`family_traits`](Self::family_traits), a family of another kind ([`FontTraits::class`]) - /// counting 2 further. Families equally far keep their order in `families`. Reads no font + /// counting 2 further. A family that shares none of those numbers with `family` comes after + /// every family that shares one in its group. Families equally far keep their order in + /// `families`. Reads no font /// file, as `family_traits` does not. pub fn similar_families(&self, family: &str, families: &[String]) -> Vec { let base = self.family_traits(family); diff --git a/crates/text/src/fontdb/traits.rs b/crates/text/src/fontdb/traits.rs index 335e4dba13..abcfe863e7 100644 --- a/crates/text/src/fontdb/traits.rs +++ b/crates/text/src/fontdb/traits.rs @@ -174,11 +174,15 @@ impl FontLikeness { /// How unlike two faces look: 0 for faces whose numbers are all the same, more the further /// apart they are. A number one of the faces does not give is left out. PANOSE digits are /// compared only between faces of the same PANOSE family kind; faces of different kinds count - /// 3 apart. The weights and scales are VectorCraft's own. + /// 3 apart. Faces that share no number to compare (neither a PANOSE family kind, a weight, a + /// width, a height, an average width nor an italic angle) are `f32::INFINITY` apart, further + /// than any faces that share one. The weights and scales are VectorCraft's own. pub fn distance(&self, other: &Self) -> f32 { let mut d = 0.0; + let mut compared = false; let (kind, other_kind) = (self.panose[0], other.panose[0]); if kind > 1 && other_kind > 1 { + compared = true; if kind == other_kind { for (a, b) in self.panose.iter().zip(&other.panose).skip(1) { if *a > 1 && *b > 1 { @@ -190,21 +194,25 @@ impl FontLikeness { } } if self.weight != 0 && other.weight != 0 { + compared = true; d += f32::from(self.weight.abs_diff(other.weight)) / 200.0; } if self.width != 0 && other.width != 0 { + compared = true; d += f32::from(self.width.abs_diff(other.width)) * 0.5; } for (a, b, scale) in [(self.x_height, other.x_height, 10.0), (self.cap_height, other.cap_height, 5.0), (self.avg_width, other.avg_width, 8.0)] { if a != 0 && b != 0 { + compared = true; d += f32::from(a.abs_diff(b)) / 1000.0 * scale; } } if let (Some(a), Some(b)) = (self.italic_angle, other.italic_angle) { + compared = true; d += f32::from(a.abs_diff(b)) / 50.0; } - d + if compared { d } else { f32::INFINITY } } } diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index 69edcbd4c3..3e8ae95d2e 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -365,6 +365,30 @@ pub fn height_outside_font() -> Option> { heights_font(HEIGHT_OUTSIDE_FAMILY, Some((HEIGHT_OUTSIDE_X, HEIGHT_OUTSIDE_CAP)), false) } +/// The family of [`numberless_font`]. +pub const NUMBERLESS_FAMILY: &str = "Numberlesstest Sans"; + +/// The bundled Source Sans 3 Regular as family [`NUMBERLESS_FAMILY`], without its OS/2 and `post` +/// tables, so it gives none of the numbers Show Similar Fonts compares faces by. `None` when it +/// can't be built. +pub fn numberless_font() -> Option> { + const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); + let font = skrifa::FontRef::new(BASE).ok()?; + let full = format!("{NUMBERLESS_FAMILY} Regular"); + let postscript = format!("{}-Regular", NUMBERLESS_FAMILY.replace(' ', "")); + let name = name_table(&[(1, NUMBERLESS_FAMILY), (2, "Regular"), (4, &full), (6, &postscript)])?; + let mut builder = FontBuilder::new(); + builder.add_raw(Tag::new(b"name"), name); + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if builder.contains(tag) || tag == Tag::new(b"OS/2") || tag == Tag::new(b"post") { + continue; + } + builder.add_raw(tag, font.table_data(r.tag())?.as_bytes().to_vec()); + } + Some(builder.build()) +} + /// The bundled Source Sans 3 Regular as `family`: with the x height and cap height `heights` in /// its OS/2 table, else a version 1 OS/2 table, which holds neither; with `base`, the `BASE` /// table of [`height_font`]. diff --git a/crates/text/src/tests/similar.rs b/crates/text/src/tests/similar.rs index 718f4607ea..6f2dbc3ae9 100644 --- a/crates/text/src/tests/similar.rs +++ b/crates/text/src/tests/similar.rs @@ -3,7 +3,9 @@ use skrifa::raw::TableProvider; -use crate::test_fonts::{HEIGHT_CAP, HEIGHT_FAMILY, HEIGHT_X, HEIGHTLESS_FAMILY, VARIABLE_FAMILY, height_font, variable_font}; +use crate::test_fonts::{ + HEIGHT_CAP, HEIGHT_FAMILY, HEIGHT_X, HEIGHTLESS_FAMILY, NUMBERLESS_FAMILY, VARIABLE_FAMILY, height_font, numberless_font, variable_font, +}; use crate::*; /// A database of the bundled fonts and the two copies of Source Sans 3 Regular with and without @@ -88,8 +90,14 @@ fn likeness_is_a_distance() { assert_eq!(sans.distance(&serif), serif.distance(&sans), "symmetric"); assert!(sans.distance(&serif) > 0.0 && sans.distance(&mono) > 0.0); // A number a face does not give is left out, not counted as 0. + assert_eq!(sans.distance(&FontLikeness { x_height: 0, cap_height: 0, ..sans }), 0.0); + // Faces that share no number are further apart than any faces that share one, not alike. let unknown = FontLikeness::default(); - assert_eq!(sans.distance(&unknown), 0.0); + assert_eq!(sans.distance(&unknown), f32::INFINITY); + assert_eq!(unknown.distance(&sans), f32::INFINITY, "symmetric"); + assert_eq!(unknown.distance(&unknown), f32::INFINITY); + let weight_only = FontLikeness { weight: 400, ..unknown }; + assert_eq!(sans.distance(&weight_only), 0.0, "the weight alone is compared"); let lighter = FontLikeness { weight: 300, ..sans }; assert!((sans.distance(&lighter) - 0.5).abs() < 1e-6, "100 weight units apart"); } @@ -117,3 +125,22 @@ fn families_are_ordered_by_likeness() { assert_eq!(without[0], HEIGHTLESS_FAMILY); assert!(db.similar_families("Source Sans 3", &[]).is_empty()); } + +/// A family that gives none of the numbers comes after every family that shares one with the +/// family asked about, instead of first as though it looked the same. +#[test] +fn a_family_without_numbers_comes_after_the_measured_ones() { + let db = db(); + assert_eq!(db.add_font(numberless_font().expect("the test font builds")), 1); + assert_eq!(db.family_traits(NUMBERLESS_FAMILY).likeness, FontLikeness::default()); + let families = names(&[NUMBERLESS_FAMILY, "JetBrains Mono", "Source Serif 4", "Inter", HEIGHTLESS_FAMILY, "Source Sans 3"]); + let order = db.similar_families("Source Sans 3", &families); + assert_eq!(order[..2], names(&["Source Sans 3", HEIGHTLESS_FAMILY]), "{order:?}"); + assert_eq!(order.last().map(String::as_str), Some(NUMBERLESS_FAMILY), "{order:?}"); + // The measured families keep the order they have without it. + let measured: Vec = order.iter().filter(|f| *f != NUMBERLESS_FAMILY).cloned().collect(); + assert_eq!(measured, db.similar_families("Source Sans 3", &families[1..])); + // Asked about itself, it comes first, and the families it shares no number with keep their + // order in the list. + assert_eq!(db.similar_families(NUMBERLESS_FAMILY, &families), families); +} diff --git a/docs/mcp.md b/docs/mcp.md index c7aa202d3f..3884d66c34 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11205,7 +11205,8 @@ others, each group nearest first. The measure is VectorCraft's own. It compares Regular by its OS/2 PANOSE digits (only between faces of the same PANOSE family kind), weight and width classes, x-height, cap height and average character width, and its `post` italic angle (a named instance of a variable font takes its `wght` and `slnt` settings), leaving out a number either face does not give, and counts a family of another kind (serif, sans -serif, script and the font menu's other kinds) as further away. It reads these when a font is cataloged or loaded and opens +serif, script and the font menu's other kinds) as further away. A family that shares none of these numbers with `family` +comes after every family in its group that shares one. It reads these when a font is cataloged or loaded and opens no font file when asked. `limit` (a whole number from 1 to 100000) keeps the first ones. A missing or blank `family` fails with `` `family` is required ``, one that is not a string with `` `family` must be a string ``, a family that isn't available or that the font menus don't list with ``font family `` is not available``, and any diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..29d96c603d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1439,6 +1439,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Inline graphics of symbols that hold other symbols:** an inline graphic of a symbol whose art holds an instance of another symbol is sized by that symbol's own art, placed by the instance, and follows it when that symbol changes. A symbol's type is laid out after the type in the art of the symbols its instances show. An inline graphic of a symbol whose art reaches that symbol through an instance and an inline graphic is an empty slot; an instance that does not size the art, such as one a clipping path hides, does not count. An instance of a missing symbol, of a symbol without art, of a symbol that holds an instance of itself, or of a symbol whose art nests symbols 32 deep is measured by the 20 × 20 square. This is VectorCraft's own rule. Tests: `an_inline_graphic_follows_the_art_of_a_symbol_nested_in_its_symbol`, `symbols_are_resolved_after_the_symbols_their_instances_show`, `a_symbol_that_shows_itself_through_an_instance_is_an_empty_slot` in `crates/engine/src/tests/inline.rs`; `a_symbol_nested_in_symbol_art_is_measured_by_its_own_art`, `nested_instances_without_art_of_their_own_are_measured_by_the_square`, `only_instances_that_size_a_symbols_art_make_it_depend_on_their_symbol` in `crates/doc/src/inline.rs`. - **Recent font pickers (#3515):** The shared Character, Properties, Glyphs and Find Font family picker lists recently applied families first, once each, in most-recent order and limited by Preferences › Type › Number of Recent Fonts. Search and filters apply to both sections; unavailable families are omitted. Section headings cannot be selected or previewed. Confirmed character-range font edits update the same saved history; previews and failed edits do not. Requirement: [issue #3515](https://github.com/storytold/vectorcraft/issues/3515). - **Show samples on white (a VectorCraft addition):** Preferences › Type › Show samples on white (`fontSamplesOnWhite`, off by default) draws each family's sample in every font menu, and in Type → Font in the in-window menu bar, in dark type on a white area in every interface brightness. A highlighted row's color shows above and below the white area, and the names and the rest of the menu keep the interface's colors. The checkbox is dimmed while Enable in-menu font previews is off. Tests: `crates/ui-egui/src/tests/font_menu.rs`, `crates/ui-egui/src/font_menu/tests.rs`, `crates/ui-egui/src/prefs_dialog/tests.rs`. +- **Show Similar Fonts: families without numbers come last:** in a font menu's Show Similar Fonts list and `text.similarFonts`, a family whose faces give none of the numbers the list compares (PANOSE, weight, width, heights, average width, italic angle) in common with the chosen family comes after every family of its script group that shares one, instead of right after the chosen family as an exact match. This is VectorCraft's own rule; the help page (https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html) describes the list only as fonts that look like the chosen one. Regression tests: `a_family_without_numbers_comes_after_the_measured_ones` and `likeness_is_a_distance` in `crates/text/src/tests/similar.rs`. - **Find Font: Replace With Font From:** a dropdown under Replace With Font chooses the list the replacement font comes from: Document lists the families the document uses, once each; Recent lists the recently applied families that are installed (fonts applied with Find Font's Change and Change All included), newest first, as many as Preferences › Type › Number of Recent Fonts allows; System, the default, lists the installed families available in the font menu. The dialog opens on System with Source Sans 3 chosen, or the font menu's first family when Source Sans 3 is not installed. Choosing a list keeps the chosen font when the list has it and it is installed; otherwise Document and Recent choose the list's first installed font, and System chooses Source Sans 3 or the font menu's first family. Change and Change All are unavailable when the list has no installed font (Recent before any font was applied) and when the chosen family is not installed or is not in the shown list. Behavior reference: [Find and replace fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-replace-fonts.html) (public documentation). Tests: `crates/ui-egui/src/find_font.rs`. - **Select Text by Font: scope (a VectorCraft addition, #5529):** `select.font` takes `scope`: `"document"` (the default, as before), `{artboards: [index, …]}` or `{layers: [id, …]}` (sublayers included). On an artboard means what All on Active Artboard takes (the bounds overlap it or the center is on it; one shared test, `select::on_artboard`); hidden and locked text stays out as before; a symbol instance counts where the instance is. Type › Find Font…'s Find In dropdown passes the active artboard or the selected layers (else the current layer). Tests: `crates/engine/src/cmd/fonts.rs`, `crates/ui-egui/src/find_font.rs`, `crates/engine/tests/command_sweep.rs`. - **Find Font: type in opacity masks and pattern swatches:** Type › Find Font…'s Document list (`text.fonts`), Find (`select.font`), Change and Change All (`text.replaceFont`), Replace Missing Fonts (`addon.cleanup.replaceFonts`), the Missing Fonts dialog (`text.missingFonts`), Document Info's Fonts and Font Details for the whole document (`document.info`), File › Package and the export warning about fonts that aren't available include the type in opacity masks (on objects and layers, disabled masks and masks inside mask, symbol or pattern art included) and in the art of pattern swatches, also a swatch that nothing paints with. A pattern's type is listed and changed once, however many objects the pattern paints. Find selects the objects whose mask holds the font, the text whose inline graphics draw a symbol whose art uses it, and the objects painted with a pattern whose art uses it by a visible fill or stroke above 0% opacity (VectorCraft's own rule; a layer's mask and a swatch that nothing paints with select nothing); Change and Change All leave the type in the mask of a hidden or locked object in its font and count it in `skipped`, and Change does the same with the type of a pattern that only hidden or locked selected objects paint with. The help page (https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-replace-fonts.html) says the Document list holds all the fonts the document uses. Tests: `crates/engine/src/cmd/fonts.rs`, `crates/engine/src/cmd/addons/cleanup/text/tests.rs`, `crates/engine/src/cmd/docinfo.rs`. diff --git a/docs/type-parity.md b/docs/type-parity.md index 7697025ca9..f9088c283d 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -35,7 +35,7 @@ against Illustrator's public documentation; **estimated** unless noted. | OpenType panel, Glyphs panel, alternates | done | Highlight Alternate Glyphs preference (#394, off by default) paints pink behind OpenType substitutions on screen when on (required shaping such as Arabic joining forms and the lam-alef ligature, including a lam-alef older fonts file under `liga`, is not highlighted; an optional feature that changes the ligature is); stylistic sets ss01–ss20, stylistic and titling alternates, proportional and lining figures, superscript and subscript are character-style features (`text.setStyle {features}`, #1607); the OpenType panel's Position menu sets superscript, subscript, numerator or denominator glyphs (`sups`, `subs`, `numr`, `dnom`). The OpenType panel's Stylistic Sets menu lists the selected font's `ss01`–`ss20` features, using a font-supplied name where available and `Set N` otherwise; several sets can be active, and selecting an active one removes it. For a mixed-font selection it uses the first selected character's font, a VectorCraft design choice ([public help](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/add-stylistic-sets-to-selected-text.html), [OpenType feature specification](https://learn.microsoft.com/en-us/typography/opentype/spec/features_pt)). The Glyphs panel highlights the character selected with the Type tool (a range's first character, else the one before the caret) and scrolls it into view as the selection moves (#4908; `panels::glyphs` tests); its Show menu lists Unicode ranges and Alternates for Current Selection, the selected character's alternate glyphs from the font's `GSUB` table. A double-click applies the OpenType feature that draws a variant to that character alone, or uses a glyph choice when no supported feature draws it; see the Glyphs panel row below for Entire Font and the joining limits. A grid cell whose glyph has alternates shows a triangle in its lower right corner; a click on it opens a pop-up of that glyph and its alternates in the font's order, and a pick inserts the character at the caret drawn with that glyph, or draws the selected character with it, in one undo step; in Entire Font a glyph no character maps has the triangle too, and a pick goes on the selected character as a double-click on that glyph's cell does ([CS6 reference, Glyphs panel overview](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=373)); the triangle's size and the pop-up's eight columns and six rows are VectorCraft's own (`panels::glyphs` tests `a_cells_corner_triangle_opens_its_alternates_and_a_pick_inserts_one`, `a_pick_replaces_the_selected_character_and_says_why_when_it_cannot`, `a_pick_that_cannot_be_drawn_leaves_the_text_as_it_was`, `an_unencoded_glyphs_corner_triangle_applies_its_alternates_to_the_selection`; `has_alternates_follows_the_listed_substitutions` in the text crate) | | Glyphs panel: alternates as OpenType feature values, unencoded glyphs | done | #5514, as [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html) describes (Show › Alternates For Current Selection; replace the selected character by double-clicking the glyph). A character-style feature takes a value (`"salt=2"`, the font's alternate number; `ss01`–`ss20`, `swsh`, `titl` and `aalt` too) in `features` and `featureChanges`, in SVG `font-feature-settings` (`"salt" 2`) and in native files as the plain string. Show › Entire Font applies an unencoded glyph the same way when it is an alternate of the selected character in its word, applies one no feature reaches (`A.salt` in a font with no `salt`) to the selected character as a glyph choice (it may not join), and dims the others with the reason in the tooltip (e.g. `yehfarsi.fina.alt2 belongs to ی (U+06CC) at the end of a word; your selection is ي (U+064A)`); an Arabic presentation form picked there inserts its letter so the word joins. Runs that differ only in their features shape as one piece of text, each run's features over its own characters, so a variant on one letter of an Arabic word keeps its neighbours' initial, medial and final forms and the letters still touch. The panel lists the alternates of the glyph the shaper makes for the selected character in its word (a medial letter shows medial variants), and a double-click applies the OpenType feature that draws the variant (`salt=N` or `ssNN`) to that character alone, in one undo step (`text.setRangeStyle`); a variant no feature reaches falls back to a replacement glyph (`text.setGlyphAlternate`), which its tooltip says may not join. Show › Entire Font also lists the glyphs no character maps, with their name or `gid N` and the feature that gives them. The text crate reads each face's `GSUB` once (alternate sets, single substitutions, the feature that reaches a glyph). Not done: alternates reached through contextual or ligature lookups, and features of the font that the style has no tag for (`cv01`–`cv99`, `hist`). Evidence: `tests::glyph_alternates` in the text crate (a fixture font with a medial teh at `salt=1` to `3`, the neighbours' forms, no gap; Kufi Murabba PIIIX when it is installed), `features::tests::feature_values_are_parsed_validated_and_shaped`, `tests::textedit::feature_values_are_set_replaced_and_saved`, the `panels::glyphs` tests. | | OpenType panel menu: H or V Style, Roman Italics | done | With Show East Asian Options, as [Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) describes: H or V Style is the character feature `hkna` (kana in the font's horizontal forms, shaped as `vkna` in vertical type) and Roman Italics is `ital` (the font's italic half-width alphanumerics), set with `text.setStyle` / `text.setRangeStyle {features, featureChanges}`, on or off only, and in Character Style Options › OpenType Features ([OpenType feature list](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist)). | -| Font menu: samples, live preview, filters, favourites, recent families; font matching by any name; Find Font | done | #3515: recently applied families appear first, once each; missing families are omitted and the existing Number of Recent Fonts setting applies; #339; script filter: Japanese, Latin, Thai; the font scan on Linux also reads the folders fontconfig's configuration lists, such as TeX fonts under `/usr/share/texmf/fonts` (#1548, fixes #1529; not verified on Linux); Select Text by Font takes a scope: the document, chosen artboards or chosen layers; Find Font's Find In offers Document, Artboard (the active one) and Layers (the selected ones, else the current one) (#5529, a VectorCraft addition); Replace With Font lists family and style rows, one click setting both, with a search over them; its list scrolls on its own, apart from the document's font list (#4972); wherever the font menu opens, its filters keep the same four rows, and it opens at least wide enough for them and for a family name up to 220 points wide with its sample (up to 60% of the window), each sample filling its row's height (a VectorCraft layout); a filter chosen in the font menu of the Character panel, the Control bar or the Properties panel is on in the others, and the filters are cleared when the app quits ([Font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html)); the font menus of the Glyphs panel and of the dialogs that pick a font share the same filters (a VectorCraft choice); Show Similar Fonts: the ≈ button on a family's row lists the families that look like it first ([Font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html)), by VectorCraft's own measure of PANOSE, weight, width, heights, average width and italic angle, same script first, and the ≈ chip under the filters clears it (`text.similarFonts`; evidence: `font_menu::tests::show_similar_fonts_orders_the_list_by_likeness`, `tests::similar::families_are_ordered_by_likeness`). | +| Font menu: samples, live preview, filters, favourites, recent families; font matching by any name; Find Font | done | #3515: recently applied families appear first, once each; missing families are omitted and the existing Number of Recent Fonts setting applies; #339; script filter: Japanese, Latin, Thai; the font scan on Linux also reads the folders fontconfig's configuration lists, such as TeX fonts under `/usr/share/texmf/fonts` (#1548, fixes #1529; not verified on Linux); Select Text by Font takes a scope: the document, chosen artboards or chosen layers; Find Font's Find In offers Document, Artboard (the active one) and Layers (the selected ones, else the current one) (#5529, a VectorCraft addition); Replace With Font lists family and style rows, one click setting both, with a search over them; its list scrolls on its own, apart from the document's font list (#4972); wherever the font menu opens, its filters keep the same four rows, and it opens at least wide enough for them and for a family name up to 220 points wide with its sample (up to 60% of the window), each sample filling its row's height (a VectorCraft layout); a filter chosen in the font menu of the Character panel, the Control bar or the Properties panel is on in the others, and the filters are cleared when the app quits ([Font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html)); the font menus of the Glyphs panel and of the dialogs that pick a font share the same filters (a VectorCraft choice); Show Similar Fonts: the ≈ button on a family's row lists the families that look like it first ([Font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html)), by VectorCraft's own measure of PANOSE, weight, width, heights, average width and italic angle, same script first, a family sharing none of these numbers with it last in its group (VectorCraft's own rule), and the ≈ chip under the filters clears it (`text.similarFonts`; evidence: `font_menu::tests::show_similar_fonts_orders_the_list_by_likeness`, `tests::similar::families_are_ordered_by_likeness`, `tests::similar::a_family_without_numbers_comes_after_the_measured_ones`). | | Missing glyphs set in an installed font made for their script (Thai, Lao, Khmer, Myanmar first; then any font that has them) | done | Thai: Leelawadee UI, Tahoma, Thonburi, Sukhumvit Set, Noto Sans Thai, TLWG | | Full font-name matching (OpenType name ID 4) | done | #1258: loaded/cataloged faces and Missing Fonts searches; localized names and variable default faces; Windows font-service QA pending | | Variable fonts | done | named instances as styles; Character panel › Variable Font sets each axis (`fontAxes`); the font menu's Font Technology › Variable lists only variable font families, with the script, kind and ★ filters ([Find, apply, and adjust variable fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-apply-and-adjust-variable-fonts.html)); a family with a variable file beside static ones counts as variable. Evidence: `font_menu::tests::the_variable_filter_lists_only_variable_families`, `tests_axes::a_family_with_variation_axes_is_variable`, `tests_sysfonts::a_family_with_a_variable_file_beside_static_ones_is_variable` | From 9ecc8087c32b6bd408989d1b183fee76254d08f7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 04:44:31 -0800 Subject: [PATCH 08/19] Shape tools: Backtick held while dragging leaves copies of the shape Holding Backtick while dragging out a rectangle, rounded rectangle, ellipse, polygon, star or line leaves a copy of the shape being drawn each time the pointer has moved 8 screen points with the key down, up to 128 copies a drag. Each copy is its own object, drawn as the drag showed it then. The release keeps the copies and the last shape as one undo step, and Escape takes them all back. The spacing and the limit are VectorCraft's own values. The `backquote` descriptions of `pointer_gesture` name the shape tools. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/tests/shapetools.rs | 66 ++++++++++ crates/mcp/src/tools/definitions.rs | 4 +- crates/tools/src/shape.rs | 86 ++++++++++++- crates/tools/src/shape/tests.rs | 167 ++++++++++++++++++++++++++ docs/mcp.md | 14 +++ docs/target-app-parity.md | 1 + 6 files changed, 334 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/tests/shapetools.rs b/crates/engine/src/tests/shapetools.rs index 3c7d34a4fe..572c637dd5 100644 --- a/crates/engine/src/tests/shapetools.rs +++ b/crates/engine/src/tests/shapetools.rs @@ -149,6 +149,72 @@ fn a_shape_tool_turns_the_shape_from_just_outside_a_corner() { assert_eq!(angle(&s, id), 0.0, "rounding does not turn it"); } +/// How many objects the first layer holds. +fn objects(s: &Session) -> usize { + s.doc().unwrap().doc.layers[0].children().map(|c| c.len()).unwrap_or_default() +} + +/// Feed the pointer events `(kind, x, y, backtick held)` to the active tool, with no modifier. +fn quote_gesture(s: &mut Session, events: &[(PointerKind, f64, f64, bool)]) { + for (k, x, y, held) in events { + s.pointer(&PointerEvent { backquote: *held, ..PointerEvent::new(*k, *x, *y) }, view()).unwrap(); + } +} + +/// A Rectangle tool drag from (50, 50) with Backtick held from (100, 100) to (140, 100), let go +/// before (160, 120), all moved by `o` along both axes: two copies, 70 × 50 and 90 × 50 pt, and +/// the 110 × 70 pt rectangle it ends with. With `release`, the drag is let go; without, it is +/// still in progress. +fn trail(s: &mut Session, o: f64, release: bool) { + use PointerKind::{Down, Drag, Up}; + quote_gesture( + s, + &[ + (Down, 50.0 + o, 50.0 + o, false), + (Drag, 100.0 + o, 100.0 + o, true), + (Drag, 120.0 + o, 100.0 + o, true), + (Drag, 140.0 + o, 100.0 + o, true), + ], + ); + quote_gesture(s, &[(Drag, 160.0 + o, 120.0 + o, false)]); + if release { + quote_gesture(s, &[(Up, 160.0 + o, 120.0 + o, false)]); + } +} + +/// The sizes of the first layer's objects, back to front. +fn sizes(s: &Session) -> Vec<(f64, f64)> { + let ids: Vec = s.doc().unwrap().doc.layers[0].children().map(|c| c.iter().map(|n| n.id).collect()).unwrap_or_default(); + ids.into_iter().map(|id| bounds(s, id)).map(|r| (r.width(), r.height())).collect() +} + +/// Backtick held while a rectangle is dragged out leaves copies of it along the drag: each its own +/// object, and the release keeps them with the last rectangle as one undo step, with Real-time +/// Drawing and Editing on or off. Escape takes the copies back with the shape being drawn. +#[test] +fn a_backtick_drag_leaves_copies_of_the_shape_as_one_undo_step() { + for real_time in [true, false] { + let mut s = new_doc(); + s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": real_time})).unwrap(); + s.select_tool("rectangle", view()).unwrap(); + let steps = undo_steps(&s); + trail(&mut s, 0.0, true); + assert_eq!(sizes(&s), vec![(70.0, 50.0), (90.0, 50.0), (110.0, 70.0)], "real time {real_time}"); + assert_eq!(undo_steps(&s), steps + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(objects(&s), 0, "Undo takes all three back"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(objects(&s), 3, "Redo puts all three back"); + // Escape takes back the copies and the shape being drawn, away from the selection. + let steps = undo_steps(&s); + trail(&mut s, 200.0, false); + s.tool_key(ToolKey::Escape, NONE, view()).unwrap(); + quote_gesture(&mut s, &[(PointerKind::Up, 360.0, 320.0, false)]); + assert_eq!(objects(&s), 3, "real time {real_time}: nothing new"); + assert_eq!(undo_steps(&s), steps, "no step"); + } +} + /// The Selection tool takes the centre point of an unfilled shape too: a drag there moves it /// instead of starting a marquee. #[test] diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index e549c2a362..1b86095c6e 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -209,7 +209,7 @@ pub fn tool_definitions() -> Vec { "x": num("Document x (pt)"), "y": num("Document y (pt)"), "mods": mods_schema(), - "backquote": {"type": "boolean", "description": "Backquote held for this event: Selection and transform tool drags transform only pattern paint"}, + "backquote": {"type": "boolean", "description": "Backquote held for this event: Selection and transform tool drags transform only pattern paint; Rectangle, Rounded Rectangle, Ellipse, Polygon, Star and Line Segment drags leave copies of the shape being drawn"}, "pressure": num("Pen pressure 0..1 (default 1): the Liquify tools' intensity with Use Pressure Pen on, and the pressure the Paintbrush records"), "tiltX": num("Pen tilt in degrees −90..90, positive leaning right (document axes); with tiltY, the tilt the Paintbrush records for Tilt and Bearing brushes. One without the other is 0"), "tiltY": num("Pen tilt in degrees −90..90, positive leaning down the page"), @@ -218,7 +218,7 @@ pub fn tool_definitions() -> Vec { }), &["kind", "x", "y"]), }, "mods": mods_schema(), - "backquote": {"type": "boolean", "description": "Default backquote held state for events: Selection and transform tool drags transform only pattern paint"}, + "backquote": {"type": "boolean", "description": "Default backquote held state for events: Selection and transform tool drags transform only pattern paint; Rectangle, Rounded Rectangle, Ellipse, Polygon, Star and Line Segment drags leave copies of the shape being drawn"}, }), &["events"], ), diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index 5a4bb93cb7..b185de4c27 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -9,6 +9,10 @@ //! to Tangent on, a line pressed on one convex curved path and dragged near another lands on a //! common tangent of the two, both its ends moving to the touch points ([`TangentLine`]). //! Escape cancels the drag and puts back the options its keys and Ctrl/Cmd changed. +//! Backtick (`` ` ``, the grave accent) held while dragging leaves a copy of the shape being drawn +//! every [`COPY_SPACING`] screen points the pointer travels, up to [`MAX_COPIES`] in one drag; the +//! release keeps the copies and the last shape as one undo step +//! (). //! //! The selection keeps its bounding box and its Live Shape widgets on show with the Rectangle, //! Rounded Rectangle, Ellipse, Polygon and Star tools, so a shape just drawn can be adjusted at @@ -38,6 +42,14 @@ use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, Tool /// value stop there too. pub const MAX_CORNER_RADIUS: f64 = 1296.0; +/// How far (screen points) the pointer travels with Backtick held between two copies a shape drag +/// leaves: VectorCraft's own spacing. +pub const COPY_SPACING: f64 = 8.0; + +/// The most copies one shape drag with Backtick held leaves, besides the shape it ends with: +/// VectorCraft's own limit. +pub const MAX_COPIES: usize = 128; + /// How far (screen points, along each axis) from a bounding-box handle's centre a shape tool's /// press scales the selection: half the drawn handle square, which is 6 points wide at the default /// Selection & Anchor Display › Size 3 and a point wider or narrower per step. The Selection tool @@ -124,6 +136,12 @@ pub struct ShapeTool { /// The move of the selection snapped to a point, a guide or the grid at its last step: the /// arrow turns hollow, as the Selection tool's does. snapped: bool, + /// The copies the drag has left with Backtick held, oldest first: each shape's command and + /// params as the drag showed it when the copy was left. + copies: Vec<(String, Value)>, + /// While Backtick is held in a drag, the pointer position the next copy is measured from: where + /// the last copy was left, or where the drag first had the key down. + copy_from: Option, } /// The options that keys and Ctrl/Cmd change while a shape is dragged out. @@ -177,9 +195,56 @@ impl ShapeTool { guides: vec![], measure: None, snapped: false, + copies: vec![], + copy_from: None, } } + /// With Backtick `held` at pointer `raw`, leave a copy of the shape the drag shows (`cmd` and + /// `params`) once the pointer is [`COPY_SPACING`] screen points from the last copy, or from + /// where the key was first held. A shape with no width, height or length, one the same as the + /// last copy, and any past [`MAX_COPIES`] are not left. Without the key, the next copy is + /// measured from where it goes down again. + fn leave_copy(&mut self, cx: &ToolContext, raw: Point, held: bool, cmd: &str, params: &Value) { + if !held { + self.copy_from = None; + return; + } + let Some(from) = self.copy_from else { + self.copy_from = Some(raw); + return; + }; + let (x, y) = screen_offset(cx, raw - from); + if x.hypot(y) < COPY_SPACING || self.copies.len() >= MAX_COPIES || !draws_something(cmd, params) { + return; + } + self.copy_from = Some(raw); + if self.copies.last().is_some_and(|(c, p)| c == cmd && p == params) { + return; + } + self.copies.push((cmd.to_owned(), params.clone())); + } + + /// The preview of the shape `cmd` with `params`: with copies left, a `command.batch` that draws + /// them and then the shape, unless it has no size or is the same as the last copy. + fn preview(&self, cmd: String, params: Value) -> Action { + if self.copies.is_empty() { + return Action::Preview(cmd, params); + } + let step = |c: &str, p: &Value| json!({ "command": c, "params": p }); + let mut commands: Vec = self.copies.iter().map(|(c, p)| step(c, p)).collect(); + if draws_something(&cmd, ¶ms) && self.copies.last().is_none_or(|(c, p)| *c != cmd || *p != params) { + commands.push(step(&cmd, ¶ms)); + } + Action::Preview("command.batch".into(), json!({ "label": self.label(), "commands": commands })) + } + + /// Forget the copies of the drag that ended. + fn clear_copies(&mut self) { + self.copies.clear(); + self.copy_from = None; + } + fn drag_options(&self) -> DragOptions { DragOptions { sides: self.sides, points: self.points, corner_radius: self.corner_radius, star_ratio: self.star_ratio } } @@ -500,6 +565,19 @@ impl ShapeTool { } } +/// Does the shape command `cmd` with `params` draw something: a box with a width and a height, a +/// polygon or star with a radius, a line with a length? +fn draws_something(cmd: &str, params: &Value) -> bool { + let n = |k: &str| params.get(k).and_then(Value::as_f64).unwrap_or(0.0); + match cmd { + // The drag gives a polygon or star a radius of at least 0.01 pt, even on its centre. + "shape.polygon" => n("radius") > 0.01, + "shape.star" => n("radius1") > 0.01, + "shape.line" => (n("x2") - n("x1")).hypot(n("y2") - n("y1")) > 0.0, + _ => n("width").abs() > 0.0 && n("height").abs() > 0.0, + } +} + /// The box a drag from `start` to `p` draws (from its centre with Alt, square with Shift), /// measured along the page axes turned by Constrain Angle `base`: the box in those axes, and the /// axes (`None` for the page's own: 0° or a whole turn, where the box is on the page exactly). @@ -597,6 +675,7 @@ impl Tool for ShapeTool { self.began = false; self.inner = None; self.before_drag = None; + self.clear_copies(); vec![] } PointerKind::Drag => { @@ -653,7 +732,8 @@ impl Tool for ShapeTool { }; let (a, b) = tangent.unwrap_or((s, ev.pos)); let (c, v) = self.command_at(a, b, ev.mods, cx.constrain_angle); - out.push(Action::Preview(c, v)); + self.leave_copy(cx, raw, ev.backquote, &c, &v); + out.push(self.preview(c, v)); out } PointerKind::Up => { @@ -662,6 +742,7 @@ impl Tool for ShapeTool { self.tangent_line.clear(); self.inner = None; self.before_drag = None; + self.clear_copies(); if self.began { self.began = false; vec![Action::Commit] @@ -724,11 +805,12 @@ impl Tool for ShapeTool { }; if changed { let (c, v) = self.command_at(s, self.last, self.mods, cx.constrain_angle); - vec![Action::Preview(c, v)] + vec![self.preview(c, v)] } else if key == ToolKey::Escape { self.start = None; self.began = false; self.inner = None; + self.clear_copies(); if let Some(o) = self.before_drag.take() { self.restore_drag_options(o); } diff --git a/crates/tools/src/shape/tests.rs b/crates/tools/src/shape/tests.rs index 1aadbf7dee..494ed226c1 100644 --- a/crates/tools/src/shape/tests.rs +++ b/crates/tools/src/shape/tests.rs @@ -1372,3 +1372,170 @@ fn a_move_from_the_centre_point_snaps_and_shows_the_hollow_arrow() { assert!(matches!(a.last(), Some(Action::Preview(_, v)) if v["matrix"][4] == json!(10.0)), "{a:?}"); assert_eq!(t.cursor(&c, Point::new(160.0, 150.0), Mods::default()), Cursor::Arrow); } + +/// A drag event to `(x, y)` with Backtick held or not. +fn quote_drag(x: f64, y: f64, held: bool) -> PointerEvent { + PointerEvent { backquote: held, ..PointerEvent::new(PointerKind::Drag, x, y) } +} + +/// The shapes the last preview in `a` draws, as their commands and params: the steps of a +/// `command.batch`, or the one shape. The bool says whether it was a batch. +fn previewed_shapes(a: &[Action]) -> (bool, Vec<(String, Value)>) { + match a.last() { + Some(Action::Preview(c, v)) if c == "command.batch" => { + assert!(v.get("commands").and_then(Value::as_array).is_some(), "{v}"); + let steps = v["commands"].as_array().into_iter().flatten(); + (true, steps.map(|s| (s["command"].as_str().unwrap_or_default().to_owned(), s["params"].clone())).collect()) + } + Some(Action::Preview(c, v)) => (false, vec![(c.clone(), v.clone())]), + _ => panic!("no preview: {a:?}"), + } +} + +/// The widths of the rectangles the last preview in `a` draws, and whether it was a batch. +fn previewed_widths(a: &[Action]) -> (bool, Vec) { + let (batch, shapes) = previewed_shapes(a); + (batch, shapes.iter().map(|(_, p)| p["width"].as_f64().unwrap_or(f64::NAN)).collect()) +} + +/// Backtick held while a rectangle is dragged out leaves a copy every 8 screen points the pointer +/// travels from where the key was first held or the last copy was left; the shape being drawn +/// still follows the pointer. A key press without pointer travel leaves none, letting go stops +/// the copies and keeps those left, and pressing it again starts measuring afresh. The release +/// commits once. +#[test] +fn backtick_drag_leaves_copies_of_the_rectangle_being_drawn() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let c = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ShapeTool::new("rectangle"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 10.0, 10.0)); + assert_eq!(previewed_widths(&t.pointer(&c, "e_drag(50.0, 30.0, false))), (false, vec![40.0])); + // The key goes down with the pointer still: no copy. + assert_eq!(previewed_widths(&t.pointer(&c, "e_drag(50.0, 30.0, true))), (false, vec![40.0])); + // 4 pt of travel is short of the spacing. + assert_eq!(previewed_widths(&t.pointer(&c, "e_drag(54.0, 30.0, true))), (false, vec![44.0])); + // 10 pt: a copy, the same as the shape shown, so the batch draws it once. + assert_eq!(previewed_widths(&t.pointer(&c, "e_drag(60.0, 30.0, true))), (true, vec![50.0])); + assert_eq!(previewed_widths(&t.pointer(&c, "e_drag(70.0, 30.0, true))), (true, vec![50.0, 60.0])); + // 5 pt past the last copy: none left, and the live shape follows. + assert_eq!(previewed_widths(&t.pointer(&c, "e_drag(75.0, 30.0, true))), (true, vec![50.0, 60.0, 65.0])); + // Let go of the key: the copies stay and no more are left. + assert_eq!(previewed_widths(&t.pointer(&c, "e_drag(90.0, 30.0, false))), (true, vec![50.0, 60.0, 80.0])); + assert_eq!(previewed_widths(&t.pointer(&c, "e_drag(120.0, 30.0, false))), (true, vec![50.0, 60.0, 110.0])); + // Pressed again: measured from where it went down. + assert_eq!(previewed_widths(&t.pointer(&c, "e_drag(125.0, 30.0, true))), (true, vec![50.0, 60.0, 115.0])); + assert_eq!(previewed_widths(&t.pointer(&c, "e_drag(135.0, 30.0, true))), (true, vec![50.0, 60.0, 125.0])); + assert_eq!(t.pointer(&c, &PointerEvent { backquote: true, ..PointerEvent::new(PointerKind::Up, 135.0, 30.0) }), vec![Action::Commit]); + // The next drag starts with no copies. + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 10.0, 10.0)); + assert_eq!(previewed_widths(&t.pointer(&c, "e_drag(50.0, 30.0, false))), (false, vec![40.0])); +} + +/// Every shape tool leaves copies of its own shape, drawn with the modifiers held when each copy +/// was left: Shift's square stays square, and Alt's from the centre stays centred. +#[test] +fn backtick_drag_leaves_copies_with_every_shape_tool_and_its_modifiers() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let c = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + for (id, cmd) in [ + ("rectangle", "shape.rectangle"), + ("roundedRectangle", "shape.rectangle"), + ("ellipse", "shape.ellipse"), + ("polygon", "shape.polygon"), + ("star", "shape.star"), + ("lineSegment", "shape.line"), + ] { + let mut t = ShapeTool::new(id); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + t.pointer(&c, "e_drag(140.0, 130.0, true)); + t.pointer(&c, "e_drag(160.0, 130.0, true)); + let (batch, shapes) = previewed_shapes(&t.pointer(&c, "e_drag(180.0, 140.0, true))); + assert!(batch, "{id}"); + assert_eq!(shapes.len(), 2, "{id}: two copies, the second the shape shown: {shapes:?}"); + assert!(shapes.iter().all(|(c, _)| c == cmd), "{id}: {shapes:?}"); + assert_ne!(shapes[0].1, shapes[1].1, "{id}: each copy as the drag showed it then"); + } + // Shift and Alt: each copy is the square drawn from the centre at that moment. + let shift_alt = Mods { shift: true, alt: true, ..Default::default() }; + let mut t = ShapeTool::new("rectangle"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + t.pointer(&c, "e_drag(130.0, 120.0, true).with_mods(shift_alt)); + let (_, shapes) = previewed_shapes(&t.pointer(&c, "e_drag(150.0, 120.0, true).with_mods(shift_alt))); + let (_, r) = &shapes[0]; + assert_eq!(r["width"], r["height"], "square: {r}"); + assert_eq!(r["x"].as_f64().unwrap_or_default() + r["width"].as_f64().unwrap_or_default() / 2.0, 100.0, "centred: {r}"); +} + +/// ↑ during a polygon drag with copies left changes only the shape being drawn; Escape cancels +/// the copies with it, and the next drag starts without them. +#[test] +fn backtick_copies_keep_their_sides_and_escape_cancels_them() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let c = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ShapeTool::new("polygon"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + t.pointer(&c, "e_drag(140.0, 100.0, true)); + t.pointer(&c, "e_drag(150.0, 100.0, true)); + let (batch, shapes) = previewed_shapes(&t.key(&c, ToolKey::Up, Mods::default())); + assert!(batch); + let sides: Vec<_> = shapes.iter().map(|(_, p)| p["sides"].clone()).collect(); + assert_eq!(sides, vec![json!(6), json!(7)], "the copy keeps its sides"); + assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::Cancel]); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + let (batch, _) = previewed_shapes(&t.pointer(&c, "e_drag(140.0, 100.0, false))); + assert!(!batch, "no copies after Escape"); +} + +/// No copy is left of a shape without a height or a length, and one drag leaves at most +/// [`MAX_COPIES`] copies while the shape being drawn still follows the pointer. +#[test] +fn backtick_copies_skip_empty_shapes_and_stop_at_the_limit() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let c = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + // A rectangle with no height: nothing is left. + let mut t = ShapeTool::new("rectangle"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 10.0, 10.0)); + for x in [30.0, 40.0, 50.0, 60.0] { + assert!(!previewed_shapes(&t.pointer(&c, "e_drag(x, 10.0, true))).0, "{x}"); + } + // A line back on its start: no copy there. + let mut t = ShapeTool::new("lineSegment"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 10.0, 10.0)); + t.pointer(&c, "e_drag(30.0, 10.0, true)); + assert!(!previewed_shapes(&t.pointer(&c, "e_drag(10.0, 10.0, true))).0); + // The limit. + let mut t = ShapeTool::new("rectangle"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 0.0, 0.0)); + t.pointer(&c, "e_drag(10.0, 10.0, true)); + let mut last = vec![]; + for i in 1..=(MAX_COPIES as u32 + 20) { + let at = 10.0 + f64::from(i) * 10.0; + last = t.pointer(&c, "e_drag(at, at, true)); + } + let (batch, widths) = previewed_widths(&last); + assert!(batch); + assert_eq!(widths.len(), MAX_COPIES + 1, "the copies and the shape being drawn"); + assert_eq!(widths.last(), Some(&(10.0 + f64::from(MAX_COPIES as u32 + 20) * 10.0)), "the shape follows the pointer"); +} + +/// The spacing is measured on screen: at 400% zoom, 2 pt of travel is 8 screen points. +#[test] +fn backtick_copy_spacing_is_measured_on_screen() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let c = ToolContext { smart_guides: false, zoom: 4.0, ..cx(&d, &s, &p) }; + let mut t = ShapeTool::new("rectangle"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 10.0, 10.0)); + t.pointer(&c, "e_drag(20.0, 20.0, true)); + assert!(!previewed_shapes(&t.pointer(&c, "e_drag(21.5, 20.0, true))).0, "6 screen points"); + assert!(previewed_shapes(&t.pointer(&c, "e_drag(22.0, 20.0, true))).0, "8 screen points"); +} diff --git a/docs/mcp.md b/docs/mcp.md index c7aa202d3f..a47362dc4c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7008,6 +7008,20 @@ of it headless), gathered once per document state; the shape being drawn is neve With a 100 × 100 square at (100, 100), the first starts the rectangle on its corner (200, 200); the second puts the Pen's second anchor at (150, 431), in line with the square's centre. +With `backquote` true on a `drag` event, the `rectangle`, `roundedRectangle`, `ellipse`, `polygon`, `star` and +`lineSegment` tools leave a copy of the shape being drawn each time the pointer has moved 8 screen points since the +last copy, or since the first event with the key down; a key change with no pointer travel leaves none. Each copy is +the shape as that event showed it, with its modifiers and Up/Down counts, and is its own object. The `up` keeps the +copies and the last shape as one undo step, and Escape takes them all back. One drag leaves at most 128 copies, and a +shape with no width, height or length leaves none. The spacing and the limit are VectorCraft's own values; the +continuous duplicate itself is in the Keys for drawing table of +[the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=469). With Smart +Guides off, this drag leaves a 70 × 50 and a 90 × 50 copy and the 110 × 70 rectangle: + +```json +{"name":"pointer_gesture","arguments":{"tool":"rectangle","events":[{"kind":"down","x":50,"y":50},{"kind":"drag","x":100,"y":100,"backquote":true},{"kind":"drag","x":120,"y":100,"backquote":true},{"kind":"drag","x":140,"y":100,"backquote":true},{"kind":"drag","x":160,"y":120},{"kind":"up","x":160,"y":120}]}} +``` + ## Type preferences - `placeholderText` (on by default): type the Type tools place (`pointer_gesture` with `type`, `areaType`…) starts with diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..29c9d8c63a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1196,6 +1196,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. The Flare tool's center drag turns the rays by 0.1 radian at each drag update in which the pointer's document y grows, and back by as much at each one in which it falls, Shift held keeps their turn, and Space held during either of its drags moves the flare. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. The Flare tool's center drag turns the rays with the pointer, Shift keeps them in their original orientation (unturned, or turned by a nonzero General › Constrain Angle), and Space held during either of its drags moves the flare. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. The Flare tool's center drag turns the rays with the pointer, Shift keeps them in their original orientation, and Space held during either of its drags moves the flare. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). + Backtick (`` ` ``) held while a rectangle, rounded rectangle, ellipse, polygon, star or line is dragged out leaves copies of the shape being drawn along the drag, each its own object: the continuous duplicate that the Keys for drawing table of [the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=469) lists. Each copy is the shape as the drag showed it then, with its modifiers and Up/Down counts; the release keeps the copies and the last shape as one undo step, and Escape takes them all back. The spacing (a copy each time the pointer has moved 8 screen points with the key down, none for the key alone) and the limit of 128 copies a drag are VectorCraft's own values, and a shape with no width, height or length leaves no copy. The arc, spiral, grid and Flare tools do not leave copies (tests `backtick_drag_leaves_copies_of_the_rectangle_being_drawn` and, through the engine, `a_backtick_drag_leaves_copies_of_the_shape_as_one_undo_step`). Escape while a polygon, star or rounded rectangle is dragged out cancels it and puts back the side count, point count, corner radius or star ratio its Up/Down and Ctrl/Cmd changed, so the next drag, the tool's options and General › Corner Radius start from the values before the canceled drag; a drag that is let go keeps them, and an option set with `tool.setOption` during the drag stays. This is VectorCraft's own rule. While a grid is dragged out, F lowers `rowSkew` (rectangular) or `radialSkew` (polar) by 10 percentage points and V raises it by 10; X lowers `columnSkew` (rectangular) or `concentricSkew` (polar) by 10 and C raises it by 10. Plain and Shift presses work; with Alt, Ctrl or Cmd held they do not, as for the other letters a tool takes while dragging. Each press changes the skew once and updates the preview; values stay within ±500% and remain in the tool options after release. The [default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) (archived copy) list the four drag keys and a 10% change. The signs (positive values follow VectorCraft's existing skew convention, so F and X lower the stored value) and one change per press with key repeat ignored are our own rules. While an arc is dragged out, C switches it between open and closed, F switches its base between the X and Y axes in the same box, and Up/Down raise and lower its slope by 10 within −100…100; each press switches once, and the values stay as the Arc tool's options. The [default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) (archived copy) list C, F and Up/Down for an arc being dragged out. F as the base switch, the arrows changing the slope, the step of 10 and one switch per press are our own rules. From 101e4625e9e0c342e1cf3cfc584c5887f13d15bf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 04:53:40 -0800 Subject: [PATCH 09/19] Graphic Styles: a style with no fill and no stroke shows an outlined shape with a red slash A style whose rows paint nothing showed as a blank white tile. Its thumbnail now shows the preview square or type outlined in black and filled with white, with the style's effects, under a red slash. The panel's views, the Control bar's Style picker and chip, the dragged chip, graphic style library panels and the large preview on the selected object all show it. A row that paints None does not count as a fill or stroke; a hidden row or one with zero opacity does. --- crates/ui-egui/src/panels/graphic_styles.rs | 179 ++++++++++++++++++-- docs/target-app-parity.md | 1 + 2 files changed, 169 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index d7b622ba77..7e459e6544 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -1,5 +1,6 @@ //! Graphic Styles panel: the document's styles as rendered thumbnails (Thumbnail View) or rows -//! (Small and Large List View), shown on a square or on type. Clicking a style applies it to the +//! (Small and Large List View), shown on a square or on type; a style with no fill and no stroke +//! shows the shape outlined in black and filled with white, under a red slash. Clicking a style applies it to the //! selection (Alt-click adds it on top); Shift-click adds to the panel's selection every style from //! the last one clicked without Shift through this one; Cmd/Ctrl-click adds or removes one; //! double-click opens Graphic Style Options. Dragging a style moves it in the list, or applies it @@ -15,10 +16,10 @@ use std::sync::Arc; use egui::{Color32, Rect, Response, Sense, Stroke, StrokeKind, TextureHandle, Ui, pos2, vec2}; use serde_json::{Value, json}; -use vectorcraft_color::{BlendMode, Paint}; +use vectorcraft_color::{BlendMode, Color, Paint}; use vectorcraft_doc::style_libs::STYLE_LIBRARIES; use vectorcraft_doc::text::{CharStyle, TextObject}; -use vectorcraft_doc::{Appearance, AppearanceItem, Document, GraphicStyle, Node, NodeId, NodeKind, PatternDef, StyleLibrary}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, GraphicStyle, Node, NodeId, NodeKind, PatternDef, StrokeLayer, StyleLibrary}; use vectorcraft_engine::cmd::stylelib; use vectorcraft_engine::cmd::swatchlib::LibraryInfo; use vectorcraft_geom::{Affine, Point, shapes}; @@ -80,6 +81,48 @@ fn uses_brush(g: &GraphicStyle) -> bool { g.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.brush.is_some())) } +/// Does `g` have no fill and no stroke? A fill or stroke row whose paint is None does not count; a +/// hidden row or one with zero opacity does. The thumbnails of such a style show the preview shape +/// with a black outline, a white fill and a red slash ([`backing`], [`slash`]). +fn paints_nothing(g: &GraphicStyle) -> bool { + g.appearance.items.iter().all(|i| i.paint().is_none()) +} + +/// `g` with a white fill below its rows and a black stroke `width` wide above them: the shape a +/// style with no fill and no stroke is shown on, with the style's effects and transparency. +fn backing(g: &GraphicStyle, width: f64) -> GraphicStyle { + let mut g = g.clone(); + g.appearance.items.insert(0, AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::WHITE)))); + g.appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), width))); + g +} + +/// The red of the slash on the thumbnail of a style with no fill and no stroke. +const SLASH: [f32; 3] = [230.0, 0.0, 0.0]; + +/// Draw a red slash (`/`) across the middle of `img`, a third of its side long, over what is there. +fn slash(img: &mut egui::ColorImage) { + let [w, h] = img.size; + let side = w.min(h) as f32; + let (cx, cy, half) = (w as f32 / 2.0, h as f32 / 2.0, side / 6.0); + let (a, b) = (pos2(cx - half, cy + half), pos2(cx + half, cy - half)); + let radius = (side * 0.035).max(0.9); + let ab = b - a; + for y in 0..h { + for x in 0..w { + let p = pos2(x as f32 + 0.5, y as f32 + 0.5); + let t = ((p - a).dot(ab) / ab.length_sq()).clamp(0.0, 1.0); + let cover = (radius + 0.5 - (p - (a + ab * t)).length()).clamp(0.0, 1.0); + if cover > 0.0 + && let Some(px) = img.pixels.get_mut(y * w + x) + { + let mix = |old: u8, new: f32| (old as f32 + (new - old as f32) * cover).round() as u8; + *px = Color32::from_rgb(mix(px.r(), SLASH[0]), mix(px.g(), SLASH[1]), mix(px.b(), SLASH[2])); + } + } + } +} + /// What a style's thumbnail paints with besides the style: the patterns and brushes of a document, /// or the patterns of a library. #[derive(Clone, Copy)] @@ -147,9 +190,20 @@ fn look_hashes(ctx: &egui::Context, app: &VectorcraftApp) -> Arc> { } /// Style `g` applied (as `graphicStyle.apply` applies it) to the preview shape, rendered `px` -/// pixels square on white, with `paints`. +/// pixels square on white, with `paints`. A style with no fill and no stroke ([`paints_nothing`]) +/// is shown on the shape outlined in black and filled with white, under a red slash. fn render(app: &VectorcraftApp, paints: Paints, g: &GraphicStyle, preview: Preview, px: u32) -> Option { const SIDE: f64 = 100.0; + let empty = paints_nothing(g); + let backed; + let g = if empty { + // An outline 1.5 pixels wide on images up to 150 pixels across, and one hundredth of the + // image width on larger ones. + backed = backing(g, (1.5 * SIDE / px.max(1) as f64).max(1.0)); + &backed + } else { + g + }; let mut doc = Document::new(SIDE, SIDE); doc.patterns = paints.patterns.to_vec(); if uses_brush(g) @@ -172,7 +226,11 @@ fn render(app: &VectorcraftApp, paints: Paints, g: &GraphicStyle, preview: Previ let layer = doc.layers[0].id; doc.insert(Some(layer), 0, app.session.styled(&shape, g)).ok()?; let img = RENDERER.with(|r| r.borrow_mut().render_region(&doc, vectorcraft_geom::Rect::new(0.0, 0.0, SIDE, SIDE), px as f64 / SIDE, true)); - Some(crate::canvas::color_image(&img)) + let mut img = crate::canvas::color_image(&img); + if empty { + slash(&mut img); + } + Some(img) } /// The thumbnail of style `g` (`look`: its [`look_hash`]) at `size` points. @@ -226,8 +284,10 @@ pub(super) fn outline(ui: &Ui, r: Rect, on: bool, hovered: bool) { ui.painter().rect_stroke(r, 0.0, Stroke::new(if on { 2.0 } else { 1.0 }, color), StrokeKind::Inside); } -/// Style `g` on a copy of the first selected object, `px` pixels square on white. One texture, -/// re-rendered only when the document, the style's look or the size changes. +/// Style `g` on a copy of the first selected object, `px` pixels square on white; a style with no +/// fill and no stroke shows the object outlined in black and filled with white, under a red slash, +/// as [`render`] shows it. One texture, re-rendered only when the document, the style's look or the +/// size changes. fn object_preview(app: &VectorcraftApp, ctx: &egui::Context, g: &GraphicStyle, look: u64, px: u32) -> Option { let st = app.session.active()?; let n = st.doc.node(*st.selection.objects.first()?)?; @@ -238,14 +298,30 @@ fn object_preview(app: &VectorcraftApp, ctx: &egui::Context, g: &GraphicStyle, l { return Some(tex); } - let styled = app.session.styled(n, g); - let img = RENDERER.with(|r| r.borrow_mut().render_node_thumbnail(&st.doc, &styled, px, Some([255; 4])))?; - let color = crate::canvas::color_image(&img); - let tex = ctx.load_texture("gs-large-object", color, egui::TextureOptions::LINEAR); + let tex = ctx.load_texture("gs-large-object", render_object(app, &st.doc, n, g, px)?, egui::TextureOptions::LINEAR); ctx.data_mut(|d| d.insert_temp(slot, (key, tex.clone()))); Some(tex) } +/// Style `g` on a copy of `n` (an object of `doc`), rendered `px` pixels square on white: the image +/// of [`object_preview`]. +fn render_object(app: &VectorcraftApp, doc: &Document, n: &Node, g: &GraphicStyle, px: u32) -> Option { + let empty = paints_nothing(g); + let styled = if empty { + // An outline about 1.5 pixels wide on the object scaled to the preview. + let side = n.geometric_bounds().map_or(1.0, |b| b.width().max(b.height())); + app.session.styled(n, &backing(g, (1.5 * side / px.max(1) as f64).max(1e-3))) + } else { + app.session.styled(n, g) + }; + let img = RENDERER.with(|r| r.borrow_mut().render_node_thumbnail(doc, &styled, px, Some([255; 4])))?; + let mut img = crate::canvas::color_image(&img); + if empty { + slash(&mut img); + } + Some(img) +} + /// The large preview of style `i` next to the pointer while the right button is held on it: on /// the selected object when there is one, else on the preview shape. fn large_preview(app: &VectorcraftApp, ctx: &egui::Context, s: &Shown, i: usize) { @@ -954,6 +1030,87 @@ mod tests { assert_eq!(px(2, 2), Color32::WHITE); } + /// Is `c` the slash's red? + fn red(c: Color32) -> bool { + c.r() > 180 && c.g() < 70 && c.b() < 70 + } + + /// Is `c` near black? + fn dark(c: Color32) -> bool { + c.r() < 90 && c.g() < 90 && c.b() < 90 + } + + /// A style with no fill and no stroke shows its thumbnail on the preview square or on type, + /// outlined in black and filled with white, under a red slash; so does a style whose rows paint + /// None, and one with only effects, whose effects still show. The large preview on the selected + /// object shows the same. + #[test] + fn a_style_with_no_fill_and_no_stroke_shows_an_outlined_shape_and_a_red_slash() { + let app = app(); + let d = app.session.active().unwrap().doc.clone(); + let image = |app: &VectorcraftApp, g: &GraphicStyle, preview: Preview| render(app, Paints::of(&d), g, preview, 40).unwrap(); + let px = |img: &egui::ColorImage, x: usize, y: usize| img.pixels[y * img.size[0] + x]; + let empty = GraphicStyle::new("Empty", Appearance::default()); + let nones = GraphicStyle::new("Nones", Appearance::basic(Paint::None, Paint::None, 1.0)); + for g in [&empty, &nones] { + let img = image(&app, g, Preview::Square); + // The square spans 8.8 to 31.2 pixels: a black edge, white inside, red in the middle. + assert!(red(px(&img, 20, 20)), "{}: {:?}", g.name, px(&img, 20, 20)); + assert!((7..=10).any(|x| dark(px(&img, x, 20))), "{}: the left edge is black", g.name); + assert_eq!(px(&img, 13, 13), Color32::WHITE, "{}", g.name); + assert_eq!(px(&img, 2, 2), Color32::WHITE, "{}", g.name); + assert!(!red(px(&img, 13, 13)) && !red(px(&img, 27, 27))); + } + // On type: the slash over the outlined characters. + let img = image(&app, &empty, Preview::Text); + assert!(red(px(&img, 20, 20))); + assert!(img.pixels.iter().any(|c| dark(*c)), "the characters are outlined in black"); + // Effects still show: a drop shadow 10 points down and right of the square. + let shadow = vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params: json!({"x": 10, "y": 10, "blur": 0}), visible: true }; + let effects = GraphicStyle::new("Shadow", Appearance { effects: vec![shadow], ..Appearance::default() }); + let img = image(&app, &effects, Preview::Square); + assert!(red(px(&img, 20, 20))); + assert_ne!(px(&img, 33, 33), Color32::WHITE, "the shadow shows below the square"); + // The large preview on the selected rectangle. + let st = app.session.active().unwrap(); + let n = st.doc.node(st.selection.objects[0]).unwrap(); + let img = render_object(&app, &st.doc, n, &empty, 60).unwrap(); + assert!(red(px(&img, 30, 30))); + assert!(dark(px(&img, 1, 30)), "{:?}", px(&img, 1, 30)); + assert_eq!(px(&img, 10, 10), Color32::WHITE); + // A style that paints keeps its own look there, without the slash. + let blue = GraphicStyle::new("Blue", Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 1.0)); + let img = render_object(&app, &st.doc, n, &blue, 60).unwrap(); + assert_eq!(px(&img, 30, 30), Color32::from_rgb(0, 0, 255)); + } + + /// A style with only a fill, or only a stroke, shows its own paint; a hidden fill or one with + /// zero opacity still counts as a fill, so its thumbnail shows no slash. + #[test] + fn a_fill_or_a_stroke_alone_or_a_hidden_fill_shows_no_slash() { + let app = app(); + let d = app.session.active().unwrap().doc.clone(); + let image = |g: &GraphicStyle| render(&app, Paints::of(&d), g, Preview::Square, 40).unwrap(); + let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0)); + let fill = GraphicStyle::new("Fill", Appearance::basic(blue.clone(), Paint::None, 1.0)); + let stroke = GraphicStyle::new("Stroke", Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.0, 0.6, 0.0)), 4.0)); + let mut hidden = GraphicStyle::new("Hidden", Appearance::basic(blue.clone(), Paint::None, 1.0)); + if let Some(f) = hidden.appearance.fill_mut() { + f.visible = false; + } + let mut clear = GraphicStyle::new("Clear", Appearance::basic(blue, Paint::None, 1.0)); + if let Some(f) = clear.appearance.fill_mut() { + f.opacity = 0.0; + } + for g in [&fill, &stroke, &hidden, &clear] { + assert!(!paints_nothing(g), "{}", g.name); + assert!(!image(g).pixels.iter().any(|c| red(*c)), "{} shows no slash", g.name); + } + assert_eq!(image(&fill).pixels[20 * 40 + 20], Color32::from_rgb(0, 0, 255)); + assert_eq!(image(&hidden).pixels[20 * 40 + 20], Color32::WHITE); + assert!(image(&stroke).pixels.iter().any(|c| c.g() > 100 && c.r() < 60 && c.b() < 60), "the stroke shows"); + } + #[test] fn merge_asks_for_a_name_and_drops_move_styles_or_make_new_ones() { let mut app = app(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..b4bda6f151 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1759,6 +1759,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Graphic styles:** styles keep opacity and blend mode, capture groups and type, apply on top with Alt, and link to the objects using them; Redefine, Break Link, Graphic Style Options, Select All Unused, Sort by Name, and Select > Same Graphic Style / Appearance Attribute. The panel has list and thumbnail views with rendered previews, merge, reorder and drag and drop, plus a Control bar Style picker; eleven generated style libraries (including Game HUD, Status Effects, Neon & Glow, Painted and Sketched, whose seven styles each repaint a solid fill with one watercolor, dry brush, pastel, charcoal or ink effect, and Textures) save and load as `.vcstyles`. The built-in Textures graphic style library (`graphicStyle.addFromLibrary {library: "textures"}`) has eight styles that paint their fills and strokes with the texture effects: Fine Grain (Grain), Canvas Weave and Burlap Sack (Texturizer), Cracked Glaze (Craquelure), Mosaic Floor (Mosaic Tiles), Quilted Squares (Patchwork), Leaded Glass (Stained Glass) and Damp Paper (Water Paper). The help page names new graphic styles for textures ([What's new](https://helpx.adobe.com/illustrator/desktop/new-features/whats-new.html)) without naming them, so the styles, their names and their settings are VectorCraft's own (`tests::stylelib::textures_styles_apply_their_texture_effects_and_keep_their_params_through_save_and_open`). In the Graphic Styles panel, Shift-click selects a range of styles and Ctrl/Cmd-click adds or removes one. + In the Graphic Styles panel's thumbnail and list views, a style with no fill and no stroke, one with only effects or transparency included, shows its preview shape with a black outline, a white fill and a red slash, as the help page describes for the panel's thumbnails ([Graphic styles](https://helpx.adobe.com/illustrator/using/graphic-styles.html)); its effects still draw on that shape. The Control bar's Style picker and chip, graphic style library panels and the large preview on the selected object show the same marker. A fill or stroke row that paints None does not count as a fill or stroke, and a hidden row or one with zero opacity does; these rules, the marker outside the panel's thumbnails and the slash's direction and size are VectorCraft's own (`a_style_with_no_fill_and_no_stroke_shows_an_outlined_shape_and_a_red_slash` in `crates/ui-egui/src/panels/graphic_styles.rs`). Applying a style to several objects, and Redefine Graphic Style, give the objects one shared copy of the style's appearance instead of a copy each; an object that is edited later gets its own copy, and an object whose placed gradients are fitted to its own bounds gets its own. The undo history's memory estimate counts a shared appearance once. Saved files are unchanged (`crates/engine/src/tests/styles.rs`). - **Several text styles at once:** in the Character Styles and Paragraph Styles panels, Shift-click highlights a range of styles and Ctrl/Cmd-click adds or removes one, without applying them; the panel menu's Select All Unused (`charStyle.unused`, `paraStyle.unused`) highlights the styles no type uses (in the layers, opacity masks, symbols, graph designs, pattern tiles and the art of brushes), never the Normal style; Delete, the button or the menu item, deletes every highlighted style but Normal in one undo step (`charStyle.delete {names}`, `paraStyle.delete {names}`). The menu's Duplicate copies every highlighted style in one undo step and highlights the copies. A highlighted row dragged onto Create New Style or Delete carries every highlighted style: dropped on Create New Style it copies them all and highlights the copies, and dropped on Delete it deletes them all but Normal and clears the highlight; a row from outside the highlight carries only its own style. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Load text styles from another document:** the Character Styles and Paragraph Styles panel menus have Load Character Styles… or Load Paragraph Styles… and Load All Styles…, which copy the styles of a document picked in an open dialog, with the swatches and patterns they paint with, in one undo step (`charStyle.load`, `paraStyle.load`, `textStyle.loadAll`); a style the document already has, under its name or a numbered one, is not added again, any other whose name is taken gets a number, and the file's Normal styles are not loaded. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). From 8a47799f173730247e7459fa700f8c7395a106b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 05:09:57 -0800 Subject: [PATCH 10/19] Magic Wand: Fill Color and Stroke Color tolerances compare CMYK values in a CMYK document In a CMYK document the Fill Color and Stroke Color tolerances run from 0 to 100 and measure the Euclidean distance between the C, M, Y and K percentages; RGB, Gray and Lab colors are converted to CMYK. RGB documents keep the 0 to 255 RGB distance. The panel's fields take the range of the active document. A tolerance above 100 set in an RGB document is kept and applies as 100 while a CMYK document is active. magicWand.set now returns an error for a tolerance that is out of range or not a number, and for a switch that is not true or false, and then changes no setting, reset included; before, it clamped the values and applied reset first. --- crates/engine/src/cmd/wand.rs | 252 +++++++++++++++++++++--- crates/ui-egui/src/panels/magic_wand.rs | 23 ++- docs/mcp.md | 10 + docs/target-app-parity.md | 1 + 4 files changed, 253 insertions(+), 33 deletions(-) diff --git a/crates/engine/src/cmd/wand.rs b/crates/engine/src/cmd/wand.rs index 218871972f..145ffd8dd1 100644 --- a/crates/engine/src/cmd/wand.rs +++ b/crates/engine/src/cmd/wand.rs @@ -5,13 +5,14 @@ use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use vectorcraft_color::Paint; -use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_doc::{ColorMode, Document, Node, NodeId, NodeKind}; use super::select::selectable_ids; -use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, has_doc, object_param, str_param}; +use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd, has_doc, object_param, str_param, switch_or}; -/// Magic Wand panel settings. Tolerances: colours as 0–255 RGB distance, stroke weight in -/// points, opacity in percent. +/// Magic Wand panel settings. Tolerances: colors as a Euclidean distance, 0–255 between RGB +/// values in an RGB document and 0–100 between CMYK percentages in a CMYK document; stroke +/// weight in points; opacity in percent. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct WandSettings { @@ -58,33 +59,68 @@ pub fn specs() -> Vec { "Magic Wand Options", ["Window", "Magic Wand"], None, - "{fillColor?, fillTolerance?: 0-255, strokeColor?, strokeTolerance?: 0-255, strokeWeight?, weightTolerance?: pt, opacity?, opacityTolerance?: %, blendingMode?, reset?: bool} → the settings", + "{fillColor?, fillTolerance?: 0-255 in an RGB document or 0-100 in a CMYK one, strokeColor?, strokeTolerance?: as fillTolerance, strokeWeight?, weightTolerance?: 0-1000 pt, opacity?, opacityTolerance?: 0-100 %, blendingMode?, reset?: bool} → the settings; a value out of range is an error and changes nothing, and an omitted one keeps its setting", always, set ), - cmd!(query "magicWand.options", "Magic Wand Settings", [], None, "{} → the Magic Wand settings", always, |s, _| Ok(json!(s.menu.wand))), + cmd!( + query "magicWand.options", + "Magic Wand Settings", + [], + None, + "{} → the Magic Wand settings (color tolerances at most 100 in a CMYK document)", + always, + |s, _| Ok(json!(s.menu.wand.effective(active_mode(s)))) + ), ] } -fn set(s: &mut Session, p: &Value) -> Result { - if bool_or(p, "reset", false) { - s.menu.wand = WandSettings::default(); +/// The active document's color mode, RGB with no document open. +fn active_mode(s: &Session) -> ColorMode { + s.doc().map(|st| st.doc.color_mode).unwrap_or_default() +} + +/// The largest Fill Color and Stroke Color tolerance in a document of `mode`. +pub fn color_tolerance_max(mode: ColorMode) -> f64 { + match mode { + ColorMode::Rgb => 255.0, + ColorMode::Cmyk => 100.0, } - let mut v = serde_json::to_value(&s.menu.wand).map_err(|e| EngineError::Other(e.to_string()))?; - if let (Some(o), Some(src)) = (v.as_object_mut(), p.as_object()) { - for (k, val) in src { - if o.contains_key(k) { - o.insert(k.clone(), val.clone()); - } +} + +fn set(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "magicWand.set"; + let mode = active_mode(s); + let color_max = color_tolerance_max(mode); + let mut w = if switch_or(p, "reset", false, CMD)? { WandSettings::default() } else { s.menu.wand.clone() }; + for (key, flag) in [ + ("fillColor", &mut w.fill_color), + ("strokeColor", &mut w.stroke_color), + ("strokeWeight", &mut w.stroke_weight), + ("opacity", &mut w.opacity), + ("blendingMode", &mut w.blending_mode), + ] { + // Only a missing key keeps the setting; null, like any other value that isn't true or + // false, is an error. + if let Some(v) = p.get(key) { + *flag = v.as_bool().ok_or_else(|| bad(CMD, format!("`{key}` must be true or false")))?; } } - let mut w: WandSettings = serde_json::from_value(v).map_err(|e| bad("magicWand.set", e.to_string()))?; - w.fill_tolerance = w.fill_tolerance.clamp(0.0, 255.0); - w.stroke_tolerance = w.stroke_tolerance.clamp(0.0, 255.0); - w.weight_tolerance = w.weight_tolerance.clamp(0.0, 1000.0); - w.opacity_tolerance = w.opacity_tolerance.clamp(0.0, 100.0); + for (key, value, max) in [ + ("fillTolerance", &mut w.fill_tolerance, color_max), + ("strokeTolerance", &mut w.stroke_tolerance, color_max), + ("weightTolerance", &mut w.weight_tolerance, 1000.0), + ("opacityTolerance", &mut w.opacity_tolerance, 100.0), + ] { + let Some(v) = p.get(key) else { continue }; + let n = v.as_f64().ok_or_else(|| bad(CMD, format!("`{key}` must be a number, not {v}")))?; + if !(n.is_finite() && (0.0..=max).contains(&n)) { + return Err(bad(CMD, format!("`{key}` must be from 0 to {max}, not {n}"))); + } + *value = n; + } s.menu.wand = w; - Ok(json!(s.menu.wand)) + Ok(json!(s.menu.wand.effective(mode))) } /// The fill an object shows: type's comes from its characters (the first run speaks for all; type @@ -104,25 +140,48 @@ pub(crate) fn stroke_of(n: &Node) -> (Paint, f64) { } } -/// Are two paints within `tol` (0–255 Euclidean RGB distance)? Non-solid paints must match exactly. -pub fn similar_paint(a: &Paint, b: &Paint, tol: f64) -> bool { +/// Are two paints within `tol`? In an RGB document `tol` is a 0–255 Euclidean distance between +/// the display RGB values; in a CMYK document it is a 0–100 Euclidean distance between the CMYK +/// percentages (a CMYK color's own values, any other color converted to CMYK). Non-solid paints +/// must match exactly. +pub fn similar_paint(a: &Paint, b: &Paint, tol: f64, mode: ColorMode) -> bool { match (a.color(), b.color()) { (Some(x), Some(y)) => { - let (x, y) = (x.to_rgb(), y.to_rgb()); - let d: f64 = (0..3).map(|i| ((x[i] - y[i]) as f64 * 255.0).powi(2)).sum::().sqrt(); - d <= tol + 1e-6 + let (d, margin) = match mode { + ColorMode::Rgb => { + let (x, y) = (x.to_rgb(), y.to_rgb()); + ((0..3).map(|i| ((x[i] - y[i]) as f64 * 255.0).powi(2)).sum::().sqrt(), 1e-6) + } + // CMYK components are f32 fractions, so a distance of exactly `tol` points can come + // out a few millionths over. + ColorMode::Cmyk => { + let (x, y) = (x.to_cmyk(), y.to_cmyk()); + ((0..4).map(|i| ((x[i] - y[i]) as f64 * 100.0).powi(2)).sum::().sqrt(), 1e-4) + } + }; + d <= tol + margin } _ => a == b, } } impl WandSettings { - /// Does `n` match `reference` on every enabled attribute? - pub fn matches(&self, reference: &Node, n: &Node) -> bool { + /// The settings in effect in a document of `mode`: the color tolerances are capped at that + /// mode's maximum, so a larger value set in an RGB document applies as 100 in a CMYK one and + /// comes back in an RGB one. + pub fn effective(&self, mode: ColorMode) -> WandSettings { + let max = color_tolerance_max(mode); + WandSettings { fill_tolerance: self.fill_tolerance.min(max), stroke_tolerance: self.stroke_tolerance.min(max), ..self.clone() } + } + + /// Does `n` match `reference` on every enabled attribute, comparing colors as in a document of + /// `mode`? + pub fn matches(&self, reference: &Node, n: &Node, mode: ColorMode) -> bool { + let w = self.effective(mode); let (rs, rw) = stroke_of(reference); let (ns, nw) = stroke_of(n); - (!self.fill_color || similar_paint(&fill_of(reference), &fill_of(n), self.fill_tolerance)) - && (!self.stroke_color || similar_paint(&rs, &ns, self.stroke_tolerance)) + (!w.fill_color || similar_paint(&fill_of(reference), &fill_of(n), w.fill_tolerance, mode)) + && (!w.stroke_color || similar_paint(&rs, &ns, w.stroke_tolerance, mode)) && (!self.stroke_weight || (rw - nw).abs() <= self.weight_tolerance + 1e-9) && (!self.opacity || ((reference.opacity - n.opacity).abs() as f64 * 100.0) <= self.opacity_tolerance + 1e-6) && (!self.blending_mode || reference.blend == n.blend) @@ -156,12 +215,13 @@ fn magic_wand(s: &mut Session, p: &Value) -> Result { let st = s.doc()?; let reference = st.doc.node(id).ok_or(EngineError::NoNode(id))?.clone(); let w = s.menu.wand.clone(); + let mode = st.doc.color_mode; // In isolation mode only the isolated group's contents can be picked, as for Select Same. let inside = st.isolation.map(|iso| selectable_ids(&st.doc, Some(iso))); let hits: Vec = paintable(&st.doc) .into_iter() .filter(|i| inside.as_ref().is_none_or(|set| set.contains(i))) - .filter(|i| st.doc.node(*i).is_some_and(|n| w.matches(&reference, n))) + .filter(|i| st.doc.node(*i).is_some_and(|n| w.matches(&reference, n, mode))) .collect(); let ids: Vec = match str_param(p, "mode").unwrap_or("set") { "add" => st.selection.objects.iter().copied().chain(hits.iter().copied().filter(|h| !st.selection.objects.contains(h))).collect(), @@ -232,6 +292,136 @@ mod tests { assert_eq!(selected(&s), [b]); } + /// A 10 × 10 rectangle at `x` filled and stroked with the given colors (JSON color values). + fn painted(s: &mut Session, x: f64, fill: Value, stroke: Value) -> u64 { + let id = s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({ "color": fill })).unwrap(); + s.execute("paint.setStroke", &json!({ "color": stroke })).unwrap(); + id + } + + fn cmyk(c: f64, m: f64, y: f64, k: f64) -> Value { + json!({"model": "cmyk", "c": c, "m": m, "y": y, "k": k}) + } + + #[test] + fn cmyk_document_compares_fill_and_stroke_colors_in_cmyk() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 200, "colorMode": "cmyk"})).unwrap(); + let white = cmyk(0.0, 0.0, 0.0, 0.0); + let a = painted(&mut s, 0.0, cmyk(0.1, 0.0, 0.0, 0.0), white.clone()); + let b = painted(&mut s, 20.0, cmyk(0.0, 0.0, 0.0, 0.0), white.clone()); + let c = painted(&mut s, 40.0, cmyk(0.0, 0.1, 0.0, 0.0), white.clone()); + // a to b is 10 points of cyan; a to c is 10 points of cyan and 10 of magenta (14.1). + s.execute("magicWand.set", &json!({"fillTolerance": 10})).unwrap(); + s.execute("select.magicWand", &json!({"id": a})).unwrap(); + assert_eq!(selected(&s), [a, b]); + s.execute("magicWand.set", &json!({"fillTolerance": 9.9})).unwrap(); + s.execute("select.magicWand", &json!({"id": a})).unwrap(); + assert_eq!(selected(&s), [a]); + s.execute("magicWand.set", &json!({"fillTolerance": 14.2})).unwrap(); + s.execute("select.magicWand", &json!({"id": a})).unwrap(); + assert_eq!(selected(&s), [a, b, c]); + // Stroke Color alone, the same rule: d's stroke is 5 points of black from a's. + let d = painted(&mut s, 60.0, cmyk(1.0, 1.0, 1.0, 1.0), cmyk(0.0, 0.0, 0.0, 0.05)); + s.execute("magicWand.set", &json!({"fillColor": false, "strokeColor": true, "strokeTolerance": 5})).unwrap(); + s.execute("select.magicWand", &json!({"id": d})).unwrap(); + assert_eq!(selected(&s), [a, b, c, d]); + s.execute("magicWand.set", &json!({"strokeTolerance": 4.9})).unwrap(); + s.execute("select.magicWand", &json!({"id": d})).unwrap(); + assert_eq!(selected(&s), [d]); + } + + #[test] + fn cmyk_document_compares_gray_as_black_ink() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 200, "colorMode": "cmyk"})).unwrap(); + let none = cmyk(0.0, 0.0, 0.0, 0.0); + let a = painted(&mut s, 0.0, json!({"gray": 0.5}), none.clone()); + let b = painted(&mut s, 20.0, cmyk(0.0, 0.0, 0.0, 0.5), none.clone()); + let c = painted(&mut s, 40.0, cmyk(0.0, 0.0, 0.0, 0.6), none); + s.execute("magicWand.set", &json!({"fillTolerance": 0})).unwrap(); + s.execute("select.magicWand", &json!({"id": a})).unwrap(); + assert_eq!(selected(&s), [a, b]); + s.execute("magicWand.set", &json!({"fillTolerance": 10})).unwrap(); + s.execute("select.magicWand", &json!({"id": a})).unwrap(); + assert_eq!(selected(&s), [a, b, c]); + } + + #[test] + fn rgb_document_keeps_the_rgb_distance() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap(); + let a = rect(&mut s, 0.0, "#000000", 1.0); + let b = rect(&mut s, 20.0, "#0a0000", 1.0); + s.execute("magicWand.set", &json!({"fillTolerance": 10})).unwrap(); + s.execute("select.magicWand", &json!({"id": a})).unwrap(); + assert_eq!(selected(&s), [a, b]); + s.execute("magicWand.set", &json!({"fillTolerance": 9.9})).unwrap(); + s.execute("select.magicWand", &json!({"id": a})).unwrap(); + assert_eq!(selected(&s), [a]); + assert_eq!(s.execute("magicWand.set", &json!({"fillTolerance": 255})).unwrap()["fillTolerance"], 255.0); + } + + #[test] + fn set_rejects_tolerances_out_of_range_and_changes_nothing() { + let mut s = Session::new(); + // With no document the color range is the RGB one. + assert!(s.execute("magicWand.set", &json!({"fillTolerance": 256})).is_err()); + s.execute("magicWand.set", &json!({"fillTolerance": 200})).unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 200, "colorMode": "cmyk"})).unwrap(); + s.execute("magicWand.set", &json!({"fillTolerance": 40, "strokeTolerance": 50})).unwrap(); + let before = s.execute("magicWand.options", &json!({})).unwrap(); + for bad_value in [ + json!({"fillTolerance": 101}), + json!({"strokeTolerance": 100.5}), + json!({"fillTolerance": -1}), + json!({"fillTolerance": "40"}), + json!({"weightTolerance": 1001}), + json!({"opacityTolerance": -0.5}), + json!({"fillColor": "yes"}), + json!({"fillTolerance": null}), + json!({"strokeColor": null}), + json!({"reset": true, "fillTolerance": 101}), + json!({"fillColor": false, "strokeTolerance": 101}), + ] { + let e = s.execute("magicWand.set", &bad_value).unwrap_err().to_string(); + assert!(e.contains("magicWand.set"), "{bad_value}: {e}"); + assert_eq!(s.execute("magicWand.options", &json!({})).unwrap(), before, "{bad_value} changed the settings"); + } + assert!(s.execute("magicWand.set", &json!({"fillTolerance": 101})).unwrap_err().to_string().contains("from 0 to 100")); + assert_eq!(s.execute("magicWand.set", &json!({"fillTolerance": 100})).unwrap()["fillTolerance"], 100.0); + // An omitted value keeps its setting. + assert_eq!(s.execute("magicWand.set", &json!({"strokeColor": true})).unwrap()["strokeTolerance"], 50.0); + } + + #[test] + fn a_larger_rgb_tolerance_applies_as_100_in_a_cmyk_document_and_comes_back() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap(); + s.execute("magicWand.set", &json!({"fillTolerance": 200, "strokeTolerance": 60})).unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 200, "colorMode": "cmyk"})).unwrap(); + let o = s.execute("magicWand.options", &json!({})).unwrap(); + assert_eq!((o["fillTolerance"].as_f64(), o["strokeTolerance"].as_f64()), (Some(100.0), Some(60.0))); + // Setting another field does not overwrite the stored fill tolerance. + assert_eq!(s.execute("magicWand.set", &json!({"opacity": true})).unwrap()["fillTolerance"], 100.0); + // 100 applies: two colors 100 points apart in one channel match, 100 apart in two do not. + let none = cmyk(0.0, 0.0, 0.0, 0.0); + let a = painted(&mut s, 0.0, cmyk(0.0, 0.0, 0.0, 0.0), none.clone()); + let b = painted(&mut s, 20.0, cmyk(1.0, 0.0, 0.0, 0.0), none.clone()); + let c = painted(&mut s, 40.0, cmyk(1.0, 1.0, 0.0, 0.0), none); + s.execute("magicWand.set", &json!({"opacity": false})).unwrap(); + s.execute("select.magicWand", &json!({"id": a})).unwrap(); + assert_eq!(selected(&s), [a, b]); + assert!(!selected(&s).contains(&c)); + s.execute("document.activate", &json!({"index": 0})).unwrap(); + assert_eq!(s.execute("magicWand.options", &json!({})).unwrap()["fillTolerance"], 200.0); + // Reset gives 32 in either mode. + s.execute("document.activate", &json!({"index": 1})).unwrap(); + let o = s.execute("magicWand.set", &json!({"reset": true})).unwrap(); + assert_eq!((o["fillTolerance"].as_f64(), o["strokeTolerance"].as_f64()), (Some(32.0), Some(32.0))); + } + #[test] fn isolation_mode_limits_the_wand_to_the_isolated_group() { let mut s = Session::new(); diff --git a/crates/ui-egui/src/panels/magic_wand.rs b/crates/ui-egui/src/panels/magic_wand.rs index c2895e19f1..934cb04d48 100644 --- a/crates/ui-egui/src/panels/magic_wand.rs +++ b/crates/ui-egui/src/panels/magic_wand.rs @@ -4,6 +4,7 @@ use egui::Ui; use serde_json::{Value, json}; +use vectorcraft_engine::cmd::wand::color_tolerance_max; use super::{pstate, set_pstate}; use crate::VectorcraftApp; @@ -47,12 +48,18 @@ fn row(app: &mut VectorcraftApp, ui: &mut Ui, o: &Value, label: &str, flag: &str }); } +/// The largest color tolerance in the active document: 100 in a CMYK document, else 255. +fn color_max(app: &VectorcraftApp) -> f64 { + color_tolerance_max(app.session.active().map(|d| d.doc.color_mode).unwrap_or_default()) +} + pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let o = options(app); - row(app, ui, &o, tl!("Fill Color"), "fillColor", Some(("fillTolerance", Tol::Plain(""), 255.0))); + let cmax = color_max(app); + row(app, ui, &o, tl!("Fill Color"), "fillColor", Some(("fillTolerance", Tol::Plain(""), cmax))); if !pstate::(ui.ctx(), "wand-hide-stroke") { widgets::divider(ui); - row(app, ui, &o, tl!("Stroke Color"), "strokeColor", Some(("strokeTolerance", Tol::Plain(""), 255.0))); + row(app, ui, &o, tl!("Stroke Color"), "strokeColor", Some(("strokeTolerance", Tol::Plain(""), cmax))); row(app, ui, &o, tl!("Stroke Weight"), "strokeWeight", Some(("weightTolerance", Tol::Weight, 1000.0))); } if !pstate::(ui.ctx(), "wand-hide-transparency") { @@ -93,4 +100,16 @@ mod tests { out.textures_delta.clear(); } } + + #[test] + fn color_tolerance_fields_go_to_100_in_a_cmyk_document() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + assert_eq!(color_max(&app), 255.0); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + assert_eq!(color_max(&app), 255.0); + app.session.execute("magicWand.set", &json!({"fillTolerance": 200})).unwrap(); + app.session.execute("file.new", &json!({"width": 100, "height": 100, "colorMode": "cmyk"})).unwrap(); + assert_eq!(color_max(&app), 100.0); + assert_eq!(options(&mut app)["fillTolerance"], 100.0); + } } diff --git a/docs/mcp.md b/docs/mcp.md index c7aa202d3f..83989407b6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2956,6 +2956,16 @@ records no undo step. among the objects beside it in its group or layer, passing over hidden and locked objects and sublayers. When there is no such object, the selection stays as it is. +`select.magicWand` compares fill and stroke colors by the active document's color mode. In an RGB document +`fillTolerance` and `strokeTolerance` run from 0 to 255 and measure the Euclidean distance between the display RGB +values. In a CMYK document they run from 0 to 100 and measure the Euclidean distance between the C, M, Y and K +percentages: a CMYK color's own values, and RGB, Gray and Lab colors converted to CMYK. Ten points of one ink matches +at 10, and ten points of each of two inks does not. A tolerance above 100 set in an RGB document is kept and applies +as 100 while a CMYK document is active; `magicWand.options` and `magicWand.set` report that value. `magicWand.set` +returns an error and changes no setting, `reset` included, when a given tolerance is not a number or is out of its +range (the color tolerances by the active document, 0 to 255 with no document open; `weightTolerance` 0 to 1000 pt; +`opacityTolerance` 0 to 100 %). An omitted value keeps its setting. + `select.same.textFillAndStrokeColor` (Select › Same › Text Fill & Stroke Color) selects the type objects that have characters whose fill and stroke both match the first character of the first selected type, and returns `{count}`. `select.same.textFillColor` and `select.same.textStrokeColor` compare the fill or the stroke alone. In type with diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..60afe345b7 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1169,6 +1169,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur `css.export` refuses a `scope` or `path` that is not a string (`5`, `true`, `["all"]`, `null`) before writing anything, instead of exporting the selection or returning the CSS as data; a left-out `scope` still exports the selection, and a left-out `path` still returns the CSS. `css.generate` and `css.export {scope: "all"}` refuse a malformed `ids` or `id`, which they do not use, as the selection's export does. Agents read the key object: `select.key` returns it, and `document.inspect` and the `ui.pointer` and `pointer_gesture` replies report it as `key`. `select.key` with an id that isn't a selected top-level object returns an error and leaves the key unchanged. The Select menu's Same commands, its Object commands that select art, Next Object Above and Below, saved selections and the Magic Wand (#2655) select only objects that Select All selects and objects inside them: nothing hidden or locked, nothing in a hidden or locked group, layer or sublayer, nothing on a template layer, and in isolation mode nothing outside the isolated group or layer. In isolation mode Select All, All on Active Artboard and Inverse select nothing while the isolated group or layer, or a group or layer it is in, is hidden, locked or a template layer. + In a CMYK document the Magic Wand's Fill Color and Stroke Color tolerances run from 0 to 100 and compare the colors' CMYK values; in an RGB document they run from 0 to 255 and compare RGB values, as the [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf) gives the two ranges. The distance is VectorCraft's own: the Euclidean distance between the C, M, Y and K percentages, with RGB, Gray and Lab colors converted to CMYK. A tolerance above 100 set in an RGB document applies as 100 in a CMYK document and comes back in an RGB one. `magicWand.set` refuses a tolerance out of its range and changes nothing (`cmyk_document_compares_fill_and_stroke_colors_in_cmyk`, `set_rejects_tolerances_out_of_range_and_changes_nothing`). Select ▸ Object ▸ Bristle Brush Strokes selects the objects whose topmost stroke has a bristle brush, whatever the brush is named, and leaves out objects whose brush is of another type, also when its name has "Bristle" in it. Select ▸ Object ▸ Not Aligned to Pixel Grid (`select.object.notAlignedToPixelGrid`) selects the paths and compound paths whose pixel-aligned property is off, whatever their coordinates, and leaves out guides, type, images, groups and the paths inside a compound path ([help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=185); `tests::pixelalign::not_aligned_to_pixel_grid_selects_paths_without_the_property`, `not_aligned_to_pixel_grid_leaves_out_what_cant_be_selected`). It also leaves out symbol instances, area type, type on a path, gradient meshes and placed documents, and the paths on template layers, in hidden or locked sublayers and on locked artboards; it selects the paths in clip groups, blends, envelopes, repeats and Intertwine groups and paths with effects (`not_aligned_to_pixel_grid_leaves_out_images_symbol_instances_and_type`, `not_aligned_to_pixel_grid_leaves_out_template_layers_locked_sublayers_and_locked_artboards`, `not_aligned_to_pixel_grid_selects_clipping_paths_and_paths_with_effects`, `not_aligned_to_pixel_grid_selects_the_paths_of_blends_envelopes_repeats_and_intertwines`, `not_aligned_to_pixel_grid_leaves_out_meshes_placed_documents_and_guides_but_takes_live_shapes`, `not_aligned_to_pixel_grid_takes_a_compound_path_by_its_own_property`). Align and Distribute Spacing keep a compound path or selected group that contains the key object in place, as they keep the key object itself. From 3a3bafd00631fddd683da1c79b0d8e1724988716 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 05:29:10 -0800 Subject: [PATCH 11/19] Layers: a target circle dropped on Delete Selection reduces the item to basic appearance Dropping a layer, group or object's target circle on the Layers panel's Delete Selection button now runs Reduce to Basic Appearance on that item instead of Clear Appearance. The item keeps its topmost visible fill and stroke, loses its other rows and its effects, and is not deleted. A drop that changes nothing records no undo step. The help page describes this drag as the alternative to Reduce To Basic Appearance: https://helpx.adobe.com/illustrator/using/appearance-attributes.html Before this change the drop also removed the remaining fill and stroke and reset the object's opacity and blend mode. --- crates/ui-egui/src/panels/layers.rs | 2 +- crates/ui-egui/src/panels/layers/controls.rs | 7 +-- crates/ui-egui/src/panels/layers/tests.rs | 49 +++++++++++++++++--- docs/mcp.md | 2 +- docs/target-app-parity.md | 1 + 5 files changed, 49 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index 1b0c664d2f..eed20e12cb 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -33,7 +33,7 @@ //! - Double-clicking a name renames it; double-clicking elsewhere on a row opens its options. //! - A target circle targets its layer, group or object (`layer.target`); dragging it onto another //! row's circle moves the appearance there (Alt copies it, `appearance.transfer`) and dropping it -//! on the trash clears it. +//! on the trash reduces it to basic appearance (`appearance.reduceToBasic`) without deleting it. //! - Search All and the Filter button at its right (`ui.layersFilter`, lit while a filter is on) //! narrow the rows, and every row that holds others shows open while they do. A row stays when //! its name holds the text typed, it is one of the object kinds ticked under By Object and it is diff --git a/crates/ui-egui/src/panels/layers/controls.rs b/crates/ui-egui/src/panels/layers/controls.rs index 381d0a65b1..4cea41db75 100644 --- a/crates/ui-egui/src/panels/layers/controls.rs +++ b/crates/ui-egui/src/panels/layers/controls.rs @@ -55,13 +55,14 @@ pub(super) fn bottom_bar(app: &mut VectorcraftApp, ui: &mut Ui, view: &View, doc let m = ui.input(|i| i.modifiers); let mut child = ui.new_child(egui::UiBuilder::new().max_rect(bar).layout(egui::Layout::right_to_left(egui::Align::Center))); let trash = widgets::icon_button(&mut child, "trash-2", tl!("Delete Selection"), false, 24.0); - // A target circle dropped on the trash clears that appearance (dragged rows: below). Peek at - // the payload's type before taking it: egui's take drops a payload of another type. + // A target circle dropped on the trash reduces that appearance to one fill and one stroke + // (dragged rows: below). Peek at the payload's type before taking it: egui's take drops a + // payload of another type. if trash.dnd_hover_payload::().is_some() && let Some(d) = trash.dnd_release_payload::() && let PanelDrag::Appearance(id) = *d { - actions.push(("appearance.clear".into(), json!({"ids": [id.0]}))); + actions.push(("appearance.reduceToBasic".into(), json!({"ids": [id.0]}))); } else if trash.clicked() { // With no row highlighted, the selected art and ruler guides go. if view.rows.is_empty() && app.session.active().is_some_and(|d| d.selection.has_objects_or_guides()) { diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index 123a9aacd1..a4cd26ac50 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -409,7 +409,7 @@ fn clicking_a_target_circle_targets_the_layer() { } #[test] -fn dragging_a_target_circle_moves_or_copies_the_appearance_and_the_trash_clears_it() { +fn dragging_a_target_circle_moves_or_copies_the_appearance() { let (mut app, layer, [a, b]) = two_rects(); app.session.execute("transparency.set", &json!({"ids": [a.0], "opacity": 30})).unwrap(); let ctx = egui::Context::default(); @@ -421,14 +421,49 @@ fn dragging_a_target_circle_moves_or_copies_the_appearance_and_the_trash_clears_ // A plain drag onto the layer's circle moves it there. drag(&mut app, &ctx, c[1], c[0], false); assert!((opacity(&app, layer) - 0.3).abs() < 1e-6 && opacity(&app, b) == 1.0); - // Dropped on the trash, the layer's appearance is cleared (and nothing is deleted). - let st = app.session.active().unwrap(); - let count = st.doc.node_count(); +} + +/// A target circle dropped on the trash reduces that item's own appearance to its topmost visible +/// fill and stroke in one undo step, and deletes nothing; dropped again, it changes nothing and +/// adds no undo step. A layer keeps only the rows it had, and its art is left as it is. +#[test] +fn dropping_a_target_circle_on_the_trash_reduces_it_to_basic_appearance() { + let (mut app, layer, [a, _]) = two_rects(); + let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap(); + // [Fill green, Stroke, Fill red, Stroke 5 pt], with an effect on the object. + run(&mut app, "appearance.addFill", json!({"ids": [a.0]})); + run(&mut app, "appearance.setItem", json!({"ids": [a.0], "index": 0, "color": "#00ff00"})); + run(&mut app, "appearance.setItem", json!({"ids": [a.0], "index": 2, "color": "#ff0000"})); + run(&mut app, "appearance.addStroke", json!({"ids": [a.0]})); + run(&mut app, "appearance.setItem", json!({"ids": [a.0], "index": 3, "weight": 5})); + run(&mut app, "effect.apply", json!({"ids": [a.0], "effect": "stylize.dropShadow", "item": null})); + let ctx = egui::Context::default(); + let (c, _) = frame(&mut app, &ctx, vec![], false); let trash = trash_pos(&mut app, &ctx); + let node = |app: &VectorcraftApp, id: NodeId| app.session.active().unwrap().doc.node(id).unwrap().clone(); + let undo = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let (original, count, before) = (node(&app, a), app.session.active().unwrap().doc.node_count(), undo(&app)); + // The bottom rectangle's circle (rows: the layer, the top rectangle, the bottom one). + drag(&mut app, &ctx, c[2], trash, false); + let n = node(&app, a); + assert!(n.appearance.is_basic(), "{:?}", n.appearance); + assert_eq!(n.appearance.items.len(), 2); + assert_eq!(n.appearance.fill().unwrap().paint.color().unwrap().to_hex(), "#ff0000"); + assert_eq!(n.appearance.stroke().unwrap().width, 5.0); + assert_eq!((app.session.active().unwrap().doc.node_count(), undo(&app)), (count, before + 1)); + // Dropped again, nothing changes and no undo step is made. + drag(&mut app, &ctx, c[2], trash, false); + assert_eq!((node(&app, a), undo(&app)), (n, before + 1)); + run(&mut app, "edit.undo", json!({})); + assert_eq!(node(&app, a), original, "one undo step restores the whole stack"); + // The layer's own fill stays and its effect goes; the art on it keeps its appearance. + run(&mut app, "appearance.addFill", json!({"ids": [layer.0]})); + run(&mut app, "effect.apply", json!({"ids": [layer.0], "effect": "stylize.dropShadow", "item": null})); drag(&mut app, &ctx, c[0], trash, false); - let st = app.session.active().unwrap(); - assert_eq!(st.doc.node(layer).unwrap().opacity, 1.0); - assert_eq!(st.doc.node_count(), count); + let l = node(&app, layer); + assert_eq!((l.appearance.items.len(), l.appearance.effects.len()), (1, 0), "{:?}", l.appearance); + assert!(l.appearance.fill().is_some()); + assert_eq!(node(&app, a), original); } /// The trash button: the bottom bar's rightmost button. diff --git a/docs/mcp.md b/docs/mcp.md index c7aa202d3f..53938339b9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5407,7 +5407,7 @@ layer (its opacity, its own fills and effects, an opacity mask on the whole laye selected. `document.inspect` reports it as `target`, and any other selection change ends it. `appearance.transfer {source, target, copy?}` is dragging a target circle onto another: the target gets the source's fills, strokes, effects and transparency, and the source is cleared unless `copy` (Alt-drag). Dropping a circle on the -panel's trash is `appearance.clear {ids: [id]}`. Masked objects' names have a dashed underline; while an opacity mask +panel's trash is `appearance.reduceToBasic {ids: [id]}` (Reduce to Basic Appearance; nothing is deleted). Masked objects' names have a dashed underline; while an opacity mask is edited the panel lists only an `` entry and the document tab says `(/Opacity Mask)`. ```json diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..394d7ff700 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1733,6 +1733,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The [About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) page describes up to five Pattern brush tiles: sides, inner corner, outer corner, beginning and end. The archived [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page says to add pattern tiles to the Swatches panel and select a swatch from the scroll list for each tile. Pattern Brush Options offers document pattern swatches in all five tile menus, including swatches named like built-in choices. The brush copies each swatch's whole art and tile frame. Side requires art; explicit None on a corner prevents fallback to the other corner's art. After a swatch is deleted, the brush keeps drawing its copied art and shows it as Original. The cited pages do not describe copying the whole art, requiring Side, suppressing corner fallback after explicit None, or showing deleted swatch art as Original. `brush.options` accepts swatch names and an object form for names that match built-in choices, and rejects unknown patterns before editing. Evidence: `tests::brushsym::pattern_tile_choices_copy_whole_swatch_art_and_reject_invalid_side` and `tests::brushsym::pattern_tile_object_selects_reserved_swatch_names` (vectorcraft-engine), `tests::pattern_corner_source_none_leaves_that_kind_of_corner_empty` (vectorcraft-brush), and `dialogs::brush_options::tests::pattern_tile_menus_use_document_patterns_and_side_none_keeps_dialog_open`, `dialogs::brush_options::tests::pattern_options_borrowed_swatch_corner_keeps_its_frame`, and `dialogs::brush_options::tests::pattern_options_selects_swatches_with_reserved_names` (vectorcraft-ui-egui). - **Appearance:** the Appearance panel's selected row drives every paint, stroke, gradient and transparency edit (`item` on the commands); effects apply to one fill or stroke; per-item Opacity popups, whose blend-mode list and opacity slider stay open inside them (#430; the Control bar's Stroke popover too); Mixed Appearances, Layers target dots and basic-appearance rules. Effects can be reordered, moved between items and copied by dragging; Show All Hidden Attributes; clicking an effect edits it in place; the object thumbnail drags onto art; effects render on type, images, symbols, blends, envelopes, meshes and repeats, and per-item raster effects export. Groups, layers and type have their own fills, strokes and effects (Contents and Characters rows); the Layers panel's target circles target layers, groups and objects; Expand Appearance turns fills, strokes, effects and brushes into objects. Fill and stroke paint (Fill, Stroke, None, Apply Last Color and Apply Last Gradient, also on characters selected with the Type tool), the Stroke panel's options, gradient and freeform point edits, Swap Fill and Stroke, Default Fill and Stroke, the Eyedropper, and the Appearance panel's item edits, Clear Appearance, Reduce to Basic Appearance, Remove Item, item reordering and Move Appearance record no undo step when they change nothing. + A Layers panel target circle dropped on the panel's Delete Selection button reduces that layer, group or object to basic appearance (`appearance.reduceToBasic`) in one undo step and deletes nothing, as the [Appearance attributes](https://helpx.adobe.com/illustrator/using/appearance-attributes.html) help page describes for that drag. Which fill and stroke stay (the topmost visible ones), that a layer or group keeps only the rows it had, and that the object's opacity and blend mode stay are VectorCraft's own rules (`panels::layers` test `dropping_a_target_circle_on_the_trash_reduces_it_to_basic_appearance`). The Add New Effect popup (Appearance panel, Properties), the Appearance panel's swatch picker, the Gradient panel's gradient swatches menu and the Image Trace button's list of presets stop at the bottom of a short window, and the mouse wheel or the scroll bar reaches their last rows. A list that fits does not scroll (`a_long_swatch_picker_scrolls_inside_a_short_window`). An image's own fills and strokes draw the shape that a Convert to Shape or Outline Object effect on them gives them (the image's box, or the outline of the image's opaque area or its frame, reshaped by the effects after it), under or over the image as its Contents row says, on the canvas, in exports and through Expand Appearance; new fills and strokes on an image go under it. Without one of those effects they draw nothing, and Use Preview Bounds then measures an image by its frame. Outline Object on an image's own fill or stroke follows the outline of the image's opaque area, and the image's frame when the image has no transparency. Path effects apply to a fill or stroke added to a bitmap object ([archived reference manual, page 561](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=561)), and with Outline Object such a stroke follows the boundary of the art when the image has transparent areas and the image's frame when it has none ([CreativePro article on strokes for placed images](https://web.archive.org/web/20250815214529/https://creativepro.com/add-strokes-placed-images-illustrator/)). VectorCraft's own rules: the opaque area is the pixels at least 50% opaque, and its outline is traced as Image Trace's Black and White mode traces at threshold 128 and fitted with curves. Evidence: `tests::imageoutline` (vectorcraft-effects), `opaque::tests` (vectorcraft-trace), `tests::containers::an_images_stroke_with_outline_object_follows_its_opaque_area` and `tests::containers::an_images_outline_object_stroke_exports_selects_and_measures_along_its_opaque_area` (vectorcraft-engine), `tests::objectfx::an_images_outline_object_stroke_follows_new_pixels_under_the_same_key` (vectorcraft-render). From 69b4f3ae968ae074895f96d4563642874a0c004c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 05:34:43 -0800 Subject: [PATCH 12/19] Shape tools: Backtick held at the press measures the first copy from there A drag that starts with Backtick already down set the copy spacing origin at the first drag event, so a short first stretch of the drag could leave no copy. The press now sets it. --- crates/tools/src/shape.rs | 4 ++++ crates/tools/src/shape/tests.rs | 15 +++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index b185de4c27..5d51fd8f61 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -676,6 +676,10 @@ impl Tool for ShapeTool { self.inner = None; self.before_drag = None; self.clear_copies(); + // Backtick already held at the press: the copies are measured from there. + if ev.backquote { + self.copy_from = Some(ev.pos); + } vec![] } PointerKind::Drag => { diff --git a/crates/tools/src/shape/tests.rs b/crates/tools/src/shape/tests.rs index 494ed226c1..842c0cc070 100644 --- a/crates/tools/src/shape/tests.rs +++ b/crates/tools/src/shape/tests.rs @@ -1433,6 +1433,21 @@ fn backtick_drag_leaves_copies_of_the_rectangle_being_drawn() { assert_eq!(previewed_widths(&t.pointer(&c, "e_drag(50.0, 30.0, false))), (false, vec![40.0])); } +/// Backtick already held at the press measures the first copy from the pressed spot: the first +/// drag 10 pt away leaves one, and 5 pt more leaves none. +#[test] +fn backtick_held_at_the_press_measures_copies_from_there() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let c = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ShapeTool::new("rectangle"); + t.pointer(&c, &PointerEvent { backquote: true, ..PointerEvent::new(PointerKind::Down, 0.0, 0.0) }); + assert_eq!(previewed_widths(&t.pointer(&c, "e_drag(10.0, 10.0, true))), (true, vec![10.0])); + assert_eq!(previewed_widths(&t.pointer(&c, "e_drag(15.0, 10.0, true))), (true, vec![10.0, 15.0])); + assert_eq!(t.pointer(&c, &PointerEvent { backquote: true, ..PointerEvent::new(PointerKind::Up, 15.0, 10.0) }), vec![Action::Commit]); +} + /// Every shape tool leaves copies of its own shape, drawn with the modifiers held when each copy /// was left: Shift's square stays square, and Alt's from the centre stays centred. #[test] From c6046dacec7d19724423153a23fc8c560d9a1193 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 05:37:33 -0800 Subject: [PATCH 13/19] Graphic Styles: the white fill of a no-paint preview covers type's characters A style with no fill and no stroke whose Characters row sits above some of its rows showed its type preview with the characters' own fill over the white backing when Override Character Color was off. The backing now puts every row above the contents, so the white fill covers the characters. --- crates/ui-egui/src/panels/graphic_styles.rs | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index 7e459e6544..b99f9ec25b 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -88,10 +88,12 @@ fn paints_nothing(g: &GraphicStyle) -> bool { g.appearance.items.iter().all(|i| i.paint().is_none()) } -/// `g` with a white fill below its rows and a black stroke `width` wide above them: the shape a +/// `g` with a white fill below its rows and a black stroke `width` wide above them, and every row +/// above the contents, so the white fill also covers type's own character colors: the shape a /// style with no fill and no stroke is shown on, with the style's effects and transparency. fn backing(g: &GraphicStyle, width: f64) -> GraphicStyle { let mut g = g.clone(); + g.appearance.contents_index = None; g.appearance.items.insert(0, AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::WHITE)))); g.appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), width))); g @@ -1084,6 +1086,23 @@ mod tests { assert_eq!(px(&img, 30, 30), Color32::from_rgb(0, 0, 255)); } + /// The white fill of a style with no fill and no stroke paints above type's characters even + /// when the style puts its Characters row above some of its rows and Override Character Color + /// is off: the type preview looks the same as for the style without that row order. + #[test] + fn the_white_fill_of_a_style_with_no_paint_covers_the_characters_whatever_its_contents_row() { + let mut app = app(); + app.session.prefs.override_char_color = false; + let d = app.session.active().unwrap().doc.clone(); + let image = |g: &GraphicStyle| render(&app, Paints::of(&d), g, Preview::Text, 40).unwrap(); + let plain = GraphicStyle::new("Nones", Appearance::basic(Paint::None, Paint::None, 1.0)); + let mut above = plain.clone(); + above.appearance.set_contents_at(1); + assert_eq!(above.appearance.contents_index, Some(1)); + assert!(paints_nothing(&above)); + assert!(image(&above).pixels == image(&plain).pixels, "the characters' own fill shows through the white fill"); + } + /// A style with only a fill, or only a stroke, shows its own paint; a hidden fill or one with /// zero opacity still counts as a fill, so its thumbnail shows no slash. #[test] From 70fdab8445a0a172107bf38f1d9903a3b16786d1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 05:50:00 -0800 Subject: [PATCH 14/19] Export for Screens: Single file PDFs are refused for assets, layers and each object With `pdfs: "single"` and several assets, layers or selected objects (`selection: "each"`), document.exportForScreens wrote one PDF named after the document holding only the first item's art, and every other item's PDF was left out. Single file puts artboards on the pages of one PDF; each asset, layer or object is cut out of the document with its own art, so the export now refuses that combination before it writes any file, and the Example line refuses it too. `pdfs: "multiple"` still writes a PDF of each item, and `selection: "one"` writes one PDF either way. Docs: params text, docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/fileio/commands.rs | 2 +- crates/engine/src/cmd/fileio/screens.rs | 12 +++++-- crates/engine/src/cmd/fileio/tests_screens.rs | 35 +++++++++++++++++++ docs/mcp.md | 3 +- docs/target-app-parity.md | 1 + 5 files changed, 48 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index ca4a2b1c83..ccd3439730 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Export for Screens", ["File", "Export"], None, - "{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with for the document, for the artboard, asset, layer or object, from 1, #### for the counter zero-padded to the run of #, , , (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, ,