From c49d45c8266308eb92273a40c8da8599a7940f0b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 17:01:23 -0800 Subject: [PATCH 01/31] 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/31] 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/31] 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/31] 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 0f4cc60018a33c3678833b44e9938ad56d32b966 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 22:30:25 -0800 Subject: [PATCH 05/31] Actions: Reset Actions restores the default set The Actions panel menu has Reset Actions. It asks first: OK replaces every set in the panel with the built-in Default Actions set, which becomes current and selected, and Append adds the built-in set after the sets there are, with the next free number when its name is in use (Default Actions 2). Cancel changes nothing. The item is off while an action records or plays, and the reset records no undo step. - ui.actionSet.reset {mode?: "replace" | "append"} runs it; omitted params count as {}, and another type, key or mode is an error. - Replace clears the panel's selected action and step, expanded actions and a dragged step, and closes an open dialog that holds a set index. On the built-in set already shown that way it changes nothing. - New strings have rows in every catalog. Three French messages about tangents get the no-break space before the colon that fr.tsv uses. Docs: docs/mcp.md, docs/ui-parity.md, docs/target-app-parity.md. --- crates/mcp/src/ui_catalog.rs | 6 + crates/ui-egui/src/dialogs.rs | 1 + crates/ui-egui/src/dialogs/confirm.rs | 22 ++ crates/ui-egui/src/dialogs/tests.rs | 33 +++ crates/ui-egui/src/i18n/bg.tsv | 4 + crates/ui-egui/src/i18n/bs.tsv | 4 + crates/ui-egui/src/i18n/ca.tsv | 4 + crates/ui-egui/src/i18n/cs.tsv | 4 + crates/ui-egui/src/i18n/da.tsv | 4 + crates/ui-egui/src/i18n/de.tsv | 4 + crates/ui-egui/src/i18n/el.tsv | 4 + crates/ui-egui/src/i18n/es.tsv | 4 + crates/ui-egui/src/i18n/fi.tsv | 4 + crates/ui-egui/src/i18n/fr.tsv | 10 +- crates/ui-egui/src/i18n/gu.tsv | 4 + crates/ui-egui/src/i18n/hi.tsv | 4 + crates/ui-egui/src/i18n/hu.tsv | 4 + crates/ui-egui/src/i18n/id.tsv | 4 + crates/ui-egui/src/i18n/it.tsv | 4 + crates/ui-egui/src/i18n/ja.tsv | 4 + crates/ui-egui/src/i18n/ka.tsv | 4 + crates/ui-egui/src/i18n/ko.tsv | 4 + crates/ui-egui/src/i18n/nl.tsv | 4 + crates/ui-egui/src/i18n/pl.tsv | 4 + crates/ui-egui/src/i18n/pt-br.tsv | 4 + crates/ui-egui/src/i18n/ru.tsv | 4 + crates/ui-egui/src/i18n/sv.tsv | 4 + crates/ui-egui/src/i18n/tr.tsv | 4 + crates/ui-egui/src/i18n/uk.tsv | 4 + crates/ui-egui/src/i18n/vi.tsv | 4 + crates/ui-egui/src/i18n/zh-hans.tsv | 4 + crates/ui-egui/src/i18n/zh-hant.tsv | 4 + crates/ui-egui/src/menus/run.rs | 1 + crates/ui-egui/src/menus/ui_commands.rs | 6 + crates/ui-egui/src/panels/actions.rs | 243 +++++++++++++++++++++ crates/ui-egui/src/panels/actions/files.rs | 2 +- docs/mcp.md | 11 + docs/target-app-parity.md | 1 + docs/ui-parity.md | 3 +- 39 files changed, 442 insertions(+), 5 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 0e3d6df203..f81ea2f7f9 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1647,6 +1647,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{set?: index, action?: index} copy the Actions panel's action at action in set (0 is the top set) to right after it in the same set; without action, copy set with all its actions to right after it (default: the current set). The copy is named after the original with \" copy\" added, a copied set gets an id of its own, and the copy is selected. The panel menu's Duplicate runs this for the selected action, else the current set. An index past the last set or action, or a copy that would give its set more than 1,000 actions or an action set file larger than 8 MiB, is an error and copies nothing → {set, action?}", ), + ( + "ui.actionSet.reset", + "Reset Actions", + "", + "{mode?: \"replace\" | \"append\"} Reset Actions. replace (the default) replaces every set in the Actions panel with a new copy of the built-in Default Actions set, makes it current and selected, clears the panel's selected action and step and its expanded actions, and closes an open Set Options, New Action, Batch or step dialog that names a set; when the panel already shows only the built-in set as it comes in that state, nothing changes, the sets keep their ids and changed is false. append adds a new copy of the built-in set after the sets there are, with the next free number when its name is in use (Default Actions 2), and keeps the current set and the selection. Omitted params count as {}. Params of another type, another key, another mode, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Reset Actions asks first (dialog `resetActions`): OK runs this with replace, Append with append → {changed, mode, set: the first built-in set's index}", + ), ("file.showPackage", "Show Package", "", "{folder} show a package folder (file.package's folder) in the file manager → {folder}"), ( "docInfo.save", diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index da1062838f..30b02e4380 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -339,6 +339,7 @@ registry! { Replace: [confirm::REPLACE] => confirm::REPLACE_SPEC, ReplaceFiles: [confirm::REPLACE_FILES] => confirm::REPLACE_FILES_SPEC, ResetPreferences: [confirm::RESET_PREFS] => confirm::RESET_PREFS_SPEC, + ResetActions: [confirm::RESET_ACTIONS] => confirm::RESET_ACTIONS_SPEC, NewSwatch: [new_swatch::KIND] => new_swatch::SPEC, NewColorGroup: [new_color_group::KIND] => new_color_group::SPEC, GraphData: [graph_data::KIND] => graph_data::SPEC, diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index 6f51be44d9..15b28c2d27 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -134,6 +134,28 @@ fn reset_prefs(app: &mut VectorcraftApp, d: &Dialog) -> Result { Ok(Value::Null) } +/// The dialog kind of the question Reset Actions asks in the Actions panel menu +/// ([`ask_reset_actions`]). Fields: `message`, `detail`, `append` (set by Append). +pub const RESET_ACTIONS: &str = "resetActions"; + +pub(super) const RESET_ACTIONS_SPEC: DialogSpec = DialogSpec { confirm: reset_actions, alternate: Some(("Append", "append")), ..SPEC }; + +/// Ask whether to replace the Actions panel's sets with the built-in set. OK replaces them, Append +/// adds the built-in set after them ([`crate::panels::actions::reset`]), and Cancel or Escape +/// changes nothing. +pub(crate) fn ask_reset_actions(app: &mut VectorcraftApp) { + let message = tl!("Replace the current actions with the default set?"); + let detail = tl!("Append adds the default set after the current sets instead."); + app.ui.dialog = Some(Dialog::new(RESET_ACTIONS, json!({"message": message, "detail": detail, "append": false}))); +} + +/// OK or Append on [`ask_reset_actions`]: closes, then resets the action sets. +fn reset_actions(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let mode = if d.fields.get("append").and_then(Value::as_bool) == Some(true) { "append" } else { "replace" }; + app.ui.dialog = None; + app.run(crate::panels::actions::RESET, json!({ "mode": mode })) +} + /// Most messages kept for later while a dialog is open ([`tell`]). const MAX_WAITING: usize = 16; diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 3ce5455437..201b34171d 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -2524,6 +2524,39 @@ fn flare_options_alt_turns_cancel_into_reset() { ); } +/// Reset Actions' question: OK replaces the action sets with the built-in set, Append adds the +/// built-in set after them, and Cancel or Escape (`cancel`) leaves them as they are. +#[test] +fn reset_actions_ok_replaces_append_adds_and_cancel_keeps_the_sets() { + use crate::panels::actions::{ActionSet, default_sets}; + let names = |app: &VectorcraftApp| app.ui.action_sets.iter().map(|s| s.name.clone()).collect::>(); + let mut app = app(); + app.ui.action_sets.push(ActionSet::new("Mine", vec![])); + app.ui.action_set = Some(1); + let mut f = Frames::new(); + for (answer, want, current) in [ + (Some("Cancel"), vec!["Default Actions", "Mine"], Some(1)), + (None, vec!["Default Actions", "Mine"], Some(1)), + (Some("Append"), vec!["Default Actions", "Mine", "Default Actions 2"], Some(1)), + (Some("OK"), vec!["Default Actions"], Some(0)), + ] { + crate::dialogs::confirm::ask_reset_actions(&mut app); + match answer { + Some(label) => { + let at = f.button(&mut app, label); + f.press(&mut app, at, true); + f.press(&mut app, at, false); + } + None => cancel(&mut app), + } + assert!(app.ui.dialog.is_none(), "{answer:?} closes the question"); + assert_eq!(names(&app), want, "{answer:?}"); + assert_eq!(app.ui.action_set, current, "{answer:?}"); + } + let saved = |sets: &[ActionSet]| serde_json::to_value(sets).unwrap(); + assert_eq!(saved(&app.ui.action_sets), saved(&default_sets()), "OK leaves the built-in set as it comes"); +} + /// The slider that screen readers name `label` in `out`'s tree: its node id, number and text. fn slider_node(out: &egui::FullOutput, label: &str) -> (egui::accesskit::NodeId, Option, Option) { let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 71e443a399..994edf40ff 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2571,6 +2571,10 @@ font-technology Variable Променливи Play Current Selection Изпълнение на текущия избор Save Actions… Запазване на действия… Load Actions… Зареждане на действия… + Reset Actions Нулиране на действия + Replace the current actions with the default set? Да се заменят ли текущите действия с набора по подразбиране? + Append adds the default set after the current sets instead. С „Добавяне“ наборът по подразбиране се добавя след текущите набори. + Append Добавяне Plug-in Info Информация за приставката Plug-ins Приставки Plug-in… Приставка… diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 883d6dd387..8c0e37094a 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1502,6 +1502,10 @@ lighting Light Svjetlo Play Current Selection Reprodukuj trenutni odabir Save Actions… Sačuvaj akcije… Load Actions… Učitaj akcije… + Reset Actions Vrati akcije na početno + Replace the current actions with the default set? Zamijeniti trenutne akcije zadanim skupom? + Append adds the default set after the current sets instead. Dugme Dodaj umjesto toga dodaje zadani skup iza trenutnih skupova. + Append Dodaj Reflect Horizontal Odrazi vodoravno Rotate 90° CW Rotiraj za 90° u smjeru kazaljke Set 1 Skup 1 diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a8a63cbf55..e5b3ac903b 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -3329,6 +3329,10 @@ digits Malayalam Malaiàlam Play Current Selection Reprodueix la selecció actual Save Actions… Desa les accions… Load Actions… Carrega accions… + Reset Actions Restableix les accions + Replace the current actions with the default set? Voleu reemplaçar les accions actuals pel conjunt predeterminat? + Append adds the default set after the current sets instead. Amb Afegeix, el conjunt predeterminat s’afegeix després dels conjunts actuals. + Append Afegeix Play: Reprodueix: Plug-in Info Informació del complement Plug-ins Complements diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 569b1347ec..03d2d0903e 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1530,6 +1530,10 @@ lighting Light Světlo Play Current Selection Přehrát aktuální výběr Save Actions… Uložit akce… Load Actions… Načíst akce… + Reset Actions Obnovit akce + Replace the current actions with the default set? Nahradit aktuální akce výchozí sadou? + Append adds the default set after the current sets instead. Tlačítko Připojit místo toho přidá výchozí sadu za aktuální sady. + Append Připojit Reflect Horizontal Zrcadlit vodorovně Rotate 90° CW Otočit o 90° po směru hodin Set 1 Sada 1 diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 4578e4efc1..29db307e85 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4103,6 +4103,10 @@ lighting Light Lys Play Current Selection Afspil aktuel markering Save Actions… Gem handlinger… Load Actions… Indlæs handlinger… + Reset Actions Nulstil handlinger + Replace the current actions with the default set? Vil du erstatte de aktuelle handlinger med standardsættet? + Append adds the default set after the current sets instead. Tilføj tilføjer i stedet standardsættet efter de aktuelle sæt. + Append Tilføj Reflect Horizontal Spejl vandret Rotate 90° CW Rotér 90° med uret Set 1 Sæt 1 diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c943c89dd2..9206418420 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2617,6 +2617,10 @@ diagnostics ui Oberfläche Play Current Selection Aktuelle Auswahl abspielen Save Actions… Aktionen speichern… Load Actions… Aktionen laden… + Reset Actions Aktionen zurücksetzen + Replace the current actions with the default set? Aktuelle Aktionen durch den Standardsatz ersetzen? + Append adds the default set after the current sets instead. Mit „Anhängen“ wird der Standardsatz stattdessen nach den aktuellen Sätzen hinzugefügt. + Append Anhängen Plug-in Info Plug-in-Informationen Plug-ins Plug-ins Plug-in… Plug-in… diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 906640aa0a..76d5a30fba 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3525,6 +3525,10 @@ theme Appearance Εμφάνιση Play Current Selection Αναπαραγωγή τρέχουσας επιλογής Save Actions… Αποθήκευση ενεργειών… Load Actions… Φόρτωση ενεργειών… + Reset Actions Επαναφορά ενεργειών + Replace the current actions with the default set? Να αντικατασταθούν οι τρέχουσες ενέργειες με το προεπιλεγμένο σύνολο; + Append adds the default set after the current sets instead. Η Προσάρτηση προσθέτει αντί γι’ αυτό το προεπιλεγμένο σύνολο μετά τα τρέχοντα σύνολα. + Append Προσάρτηση Plug-in Info Πληροφορίες προσθέτου Plug-in… Πρόσθετο… Point Text Objects Αντικείμενα κειμένου σημείου diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9239c93a73..7653ca26ef 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2660,6 +2660,10 @@ font-technology Variable Variables Play Current Selection Reproducir la selección actual Save Actions… Guardar acciones… Load Actions… Cargar acciones… + Reset Actions Restablecer acciones + Replace the current actions with the default set? ¿Reemplazar las acciones actuales por el conjunto predeterminado? + Append adds the default set after the current sets instead. Añadir agrega en su lugar el conjunto predeterminado después de los conjuntos actuales. + Append Añadir Plug-in Info Información del plugin Plug-ins Plugins Plug-in… Plugin… diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 423703e5c1..5d9baaf716 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1504,6 +1504,10 @@ lighting Light Valo Play Current Selection Toista nykyinen valinta Save Actions… Tallenna toiminnot… Load Actions… Lataa toiminnot… + Reset Actions Palauta toiminnot + Replace the current actions with the default set? Korvataanko nykyiset toiminnot oletussarjalla? + Append adds the default set after the current sets instead. Lisää-painike lisää sen sijaan oletussarjan nykyisten sarjojen perään. + Append Lisää Reflect Horizontal Peilaa vaakasuunnassa Rotate 90° CW Kierrä 90° myötäpäivään Set 1 Sarja 1 diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8af602785b..34482ccebc 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2648,6 +2648,10 @@ font-technology Variable Variables Play Current Selection Exécuter la sélection actuelle Save Actions… Enregistrer les scripts… Load Actions… Charger des scripts… + Reset Actions Réinitialiser les scripts + Replace the current actions with the default set? Remplacer les scripts actuels par le jeu par défaut ? + Append adds the default set after the current sets instead. Le bouton Ajouter ajoute plutôt le jeu par défaut après les jeux actuels. + Append Ajouter Plug-in Info Informations sur le module externe Plug-ins Modules externes Plug-in… Module externe… @@ -7464,9 +7468,9 @@ breakText Glyphs Glyphes @msg a selected path has no area un tracé sélectionné n’a pas de surface @msg a selected path has more than 10000 segments un tracé sélectionné a plus de 10000 segments @msg the two paths have the same outline les deux tracés ont le même contour -@msg One path lies inside the other, so they have no common tangents Un tracé se trouve à l’intérieur de l’autre : ils n’ont donc aucune tangente commune -@msg The paths overlap, so they have no internal tangents Les tracés se chevauchent : ils n’ont donc aucune tangente interne -@msg One path lies inside the other, so they have no internal tangents Un tracé se trouve à l’intérieur de l’autre : ils n’ont donc aucune tangente interne +@msg One path lies inside the other, so they have no common tangents Un tracé se trouve à l’intérieur de l’autre : ils n’ont donc aucune tangente commune +@msg The paths overlap, so they have no internal tangents Les tracés se chevauchent : ils n’ont donc aucune tangente interne +@msg One path lies inside the other, so they have no internal tangents Un tracé se trouve à l’intérieur de l’autre : ils n’ont donc aucune tangente interne # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Décomposer les tirets en tracés @msg select paths with dashed strokes to expand sélectionnez des tracés à contour pointillé à décomposer diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 4eed343e3d..b2909ced84 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -2051,6 +2051,10 @@ Live curve fitting લાઇવ કર્વ ફિટિંગ Live preview લાઇવ પૂર્વાવલોકન Load Actions… ઍક્શન લોડ કરો… + Reset Actions ઍક્શન રીસેટ કરો + Replace the current actions with the default set? વર્તમાન ઍક્શનને ડિફૉલ્ટ સેટથી બદલવા છે? + Append adds the default set after the current sets instead. ઉમેરો તેના બદલે ડિફૉલ્ટ સેટને વર્તમાન સેટ પછી ઉમેરે છે. + Append ઉમેરો Load All Styles બધી સ્ટાઇલ લોડ કરો Load All Styles… બધી સ્ટાઇલ લોડ કરો… Load Character Styles કેરેક્ટર સ્ટાઇલ લોડ કરો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index de33cdbd92..3db6e28401 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -2756,6 +2756,10 @@ antiAlias Sharp शार्प Live Shape लाइव आकार Live Shape Properties लाइव शेप प्रॉपर्टीज़ Load Actions… एक्शन्स लोड करें… + Reset Actions एक्शन्स रीसेट करें + Replace the current actions with the default set? मौजूदा एक्शन्स को डिफ़ॉल्ट सेट से बदलें? + Append adds the default set after the current sets instead. जोड़ें इसके बजाय डिफ़ॉल्ट सेट को मौजूदा सेट के बाद जोड़ता है। + Append जोड़ें Load Color Profile… लोड कलर प्रोफ़ाइल… Load EPS into Clipboard ईपीएस को क्लिपबोर्ड में लोड करें Load Image into Clipboard क्लिपबोर्ड में इमेज लोड करें diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index f869e7d07b..b94721a1a0 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3206,6 +3206,10 @@ diagnostics ui felület Play Current Selection Kijelölt művelet lejátszása Save Actions… Műveletek mentése… Load Actions… Műveletek betöltése… + Reset Actions Műveletek visszaállítása + Replace the current actions with the default set? Lecseréled az aktuális műveleteket az alapértelmezett készletre? + Append adds the default set after the current sets instead. A Hozzáfűzés ehelyett az aktuális készletek után adja hozzá az alapértelmezett készletet. + Append Hozzáfűzés Plug-in Info Bővítmény adatai Plug-ins Bővítmények Plug-in… Bővítmény… diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c5f865e69b..3c111424a3 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1429,6 +1429,10 @@ lighting Light Cahaya Play Current Selection Putar seleksi saat ini Save Actions… Simpan tindakan… Load Actions… Muat tindakan… + Reset Actions Atur ulang tindakan + Replace the current actions with the default set? Ganti tindakan saat ini dengan set default? + Append adds the default set after the current sets instead. Tambahkan justru menambahkan set default setelah set saat ini. + Append Tambahkan Reflect Horizontal Pencerminan horizontal Rotate 90° CW Putar 90° searah jarum jam Set 1 Set 1 diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 08cefdbed7..8754acf7e0 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2698,6 +2698,10 @@ diagnostics ui interfaccia Play Current Selection Esegui selezione corrente Save Actions… Salva azioni… Load Actions… Carica azioni… + Reset Actions Ripristina azioni + Replace the current actions with the default set? Sostituire le azioni correnti con il set predefinito? + Append adds the default set after the current sets instead. Aggiungi aggiunge invece il set predefinito dopo i set correnti. + Append Aggiungi Plug-in Info Informazioni plug-in Plug-ins Plug-in Plug-in… Plug-in… diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 59c7628f40..d0b04c7878 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -2784,6 +2784,10 @@ diagnostics ui UI Play Current Selection 選択項目を再生 Save Actions… アクションを保存… Load Actions… アクションを読み込み… + Reset Actions アクションをリセット + Replace the current actions with the default set? 現在のアクションを初期設定のセットで置き換えますか? + Append adds the default set after the current sets instead. 「追加」を選ぶと、初期設定のセットを現在のセットの後に追加します。 + Append 追加 Plug-in Info プラグイン情報 Plug-in… プラグイン… Points ポイント diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 9393433cdb..6de2e02ead 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3453,6 +3453,10 @@ lighting Light სინათლე Play Current Selection მიმდინარე მონიშნულის შესრულება Save Actions… მოქმედებების შენახვა… Load Actions… მოქმედებების ჩატვირთვა… + Reset Actions მოქმედებების ჩამოყრა + Replace the current actions with the default set? ჩანაცვლდეს მიმდინარე მოქმედებები ნაგულისხმევი ნაკრებით? + Append adds the default set after the current sets instead. დამატება ამის ნაცვლად ნაგულისხმევ ნაკრებს მიმდინარე ნაკრებების შემდეგ ამატებს. + Append დამატება Reflect Horizontal ჰორიზონტალურად არეკვლა Rotate 90° CW 90°-ით შემობრუნება საათის ისრის მიმართულებით Set 1 ნაკრები 1 diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 49d5e10dc1..7650d7ffe0 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -2774,6 +2774,10 @@ diagnostics ui UI Play Current Selection 현재 선택 항목 재생 Save Actions… 액션 저장… Load Actions… 액션 불러오기… + Reset Actions 액션 재설정 + Replace the current actions with the default set? 현재 액션을 기본 세트로 바꾸시겠습니까? + Append adds the default set after the current sets instead. 추가를 누르면 대신 기본 세트를 현재 세트 뒤에 추가합니다. + Append 추가 Plug-in Info 플러그인 정보 Plug-in… 플러그인… Points 포인트 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index f071ebd0e2..e405ea5eca 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1997,6 +1997,10 @@ lighting Light Licht Play Current Selection Huidige selectie afspelen Save Actions… Acties opslaan… Load Actions… Acties laden… + Reset Actions Acties opnieuw instellen + Replace the current actions with the default set? De huidige acties vervangen door de standaardset? + Append adds the default set after the current sets instead. Toevoegen voegt in plaats daarvan de standaardset toe na de huidige sets. + Append Toevoegen Reflect Horizontal Horizontaal spiegelen Rotate 90° CW 90° met de klok mee draaien Set 1 Set 1 diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 2477c73abd..c00b790dc4 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1443,6 +1443,10 @@ lighting Light Światło Play Current Selection Odtwórz bieżące zaznaczenie Save Actions… Zapisz operacje… Load Actions… Wczytaj operacje… + Reset Actions Resetuj operacje + Replace the current actions with the default set? Zastąpić bieżące operacje zestawem domyślnym? + Append adds the default set after the current sets instead. Dołącz dodaje zamiast tego zestaw domyślny po bieżących zestawach. + Append Dołącz Reflect Horizontal Odbij w poziomie Rotate 90° CW Obróć o 90° w prawo Set 1 Zestaw 1 diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 333351b9af..7aa71576ca 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2194,6 +2194,10 @@ antiAlias Sharp Nítido Play Current Selection Reproduzir Seleção Atual Save Actions… Salvar Ações… Load Actions… Carregar Ações… + Reset Actions Redefinir Ações + Replace the current actions with the default set? Substituir as ações atuais pelo conjunto padrão? + Append adds the default set after the current sets instead. Anexar adiciona o conjunto padrão depois dos conjuntos atuais. + Append Anexar Plug-in Info Informações do Plug-in Plug-ins Plug-ins Plug-in… Plug-in… diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ae33aa0d55..942cb3b44c 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2687,6 +2687,10 @@ diagnostics ui интерфейс Play Current Selection Воспроизвести текущее выделение Save Actions… Сохранить действия… Load Actions… Загрузить действия… + Reset Actions Сбросить действия + Replace the current actions with the default set? Заменить текущие действия набором по умолчанию? + Append adds the default set after the current sets instead. Кнопка «Добавить» вместо этого добавляет набор по умолчанию после текущих наборов. + Append Добавить Plug-in Info Сведения о модуле Plug-ins Модули Plug-in… Модуль… diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1bd4fd0692..58b4194a69 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -2591,6 +2591,10 @@ font-technology Variable Variabla Play Current Selection Spela upp aktuell markering Save Actions… Spara åtgärder… Load Actions… Läs in åtgärder… + Reset Actions Återställ åtgärder + Replace the current actions with the default set? Vill du ersätta de aktuella åtgärderna med standarduppsättningen? + Append adds the default set after the current sets instead. Lägg till lägger i stället till standarduppsättningen efter de aktuella uppsättningarna. + Append Lägg till Plug-in Info Information om plugin Plug-ins Plugins Plug-in… Plugin… diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index a2a38c679a..eed24053b8 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2432,6 +2432,10 @@ shape Open Açık Play Current Selection Geçerli Seçimi Oynat Save Actions… Eylemleri Kaydet… Load Actions… Eylemleri Yükle… + Reset Actions Eylemleri Sıfırla + Replace the current actions with the default set? Geçerli eylemler varsayılan setle değiştirilsin mi? + Append adds the default set after the current sets instead. Ekle bunun yerine varsayılan seti geçerli setlerin sonuna ekler. + Append Ekle Plug-in Info Eklenti Bilgisi Plug-ins Eklentiler Plug-in… Eklenti… diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 17c673885d..648ff247eb 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2690,6 +2690,10 @@ diagnostics ui інтерфейс Play Current Selection Відтворити поточне виділення Save Actions… Зберегти дії… Load Actions… Завантажити дії… + Reset Actions Скинути дії + Replace the current actions with the default set? Замінити поточні дії набором за умовчанням? + Append adds the default set after the current sets instead. Кнопка «Додати» натомість додає набір за умовчанням після поточних наборів. + Append Додати Plug-in Info Відомості про модуль Plug-ins Модулі Plug-in… Модуль… diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index da89525314..ca7e0ed76e 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3006,6 +3006,10 @@ diagnostics ui giao diện Play Current Selection Phát vùng chọn hiện tại Save Actions… Lưu hành động… Load Actions… Tải hành động… + Reset Actions Đặt lại hành động + Replace the current actions with the default set? Thay thế các hành động hiện tại bằng bộ mặc định? + Append adds the default set after the current sets instead. Nối thêm sẽ thêm bộ mặc định vào sau các bộ hiện tại. + Append Nối thêm Plug-in Info Thông tin plug-in Plug-ins Plug-in Plug-in… Phần bổ trợ… diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5f612cb0d4..e69508653b 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2551,6 +2551,10 @@ diagnostics ui 界面 Play Current Selection 播放当前选择项目 Save Actions… 存储动作… Load Actions… 载入动作… + Reset Actions 重置动作 + Replace the current actions with the default set? 要用默认动作组替换当前动作吗? + Append adds the default set after the current sets instead. “追加”会改为将默认动作组添加到当前动作组之后。 + Append 追加 Plug-in Info 插件信息 Plug-ins 增效工具 Plug-in… 增效工具… diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e0b5a13ee2..11b0b8b9c8 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -3822,6 +3822,10 @@ diagnostics ui 介面 Play Current Selection 播放目前選取項目 Save Actions… 儲存動作… Load Actions… 載入動作… + Reset Actions 重設動作 + Replace the current actions with the default set? 要用預設動作組取代目前的動作嗎? + Append adds the default set after the current sets instead. 「附加」會改為將預設動作組加到目前動作組之後。 + Append 附加 Plug-in Info 增效模組資訊 Plug-ins 增效模組 Plug-in… 增效模組… diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 495e606d6c..b4e1c668ac 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -1004,6 +1004,7 @@ fn run_ui_part11(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::panels::actions::load_set(app, p), crate::panels::actions::DELETE_SETS => crate::panels::actions::delete_sets(app, p), crate::panels::actions::DUPLICATE => crate::panels::actions::duplicate(app, p), + crate::panels::actions::RESET => crate::panels::actions::reset(app, p), "ui.shortcutImportDialog" => crate::dialogs::shortcut_import::command(app, p), _ => return None, }; diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index ced961e32c..2b285c704b 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1648,6 +1648,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{set?: index, action?: index} copy the Actions panel's action at action in set (0 is the top set) to right after it in the same set; without action, copy set with all its actions to right after it (default: the current set). The copy is named after the original with \" copy\" added, a copied set gets an id of its own, and the copy is selected. The panel menu's Duplicate runs this for the selected action, else the current set. An index past the last set or action, or a copy that would give its set more than 1,000 actions or an action set file larger than 8 MiB, is an error and copies nothing → {set, action?}", ), + ( + crate::panels::actions::RESET, + "Reset Actions", + "", + "{mode?: \"replace\" | \"append\"} Reset Actions. replace (the default) replaces every set in the Actions panel with a new copy of the built-in Default Actions set, makes it current and selected, clears the panel's selected action and step and its expanded actions, and closes an open Set Options, New Action, Batch or step dialog that names a set; when the panel already shows only the built-in set as it comes in that state, nothing changes, the sets keep their ids and changed is false. append adds a new copy of the built-in set after the sets there are, with the next free number when its name is in use (Default Actions 2), and keeps the current set and the selection. Omitted params count as {}. Params of another type, another key, another mode, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Reset Actions asks first (dialog `resetActions`): OK runs this with replace, Append with append → {changed, mode, set: the first built-in set's index}", + ), ("file.showPackage", "Show Package", "", "{folder} show a package folder (file.package's folder) in the file manager → {folder}"), ( "docInfo.save", diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 1c5509e9ae..8786b477f3 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -2145,6 +2145,81 @@ pub fn duplicate(app: &mut VectorcraftApp, p: &Value) -> Result { Ok(result) } +/// The command that puts the built-in action set back ([`reset`]). +pub const RESET: &str = "ui.actionSet.reset"; + +/// `ui.actionSet.reset {mode?: "replace" | "append"}`: Reset Actions. `replace` (the default) +/// replaces every set in the panel with a new copy of the built-in sets ([`default_sets`]), makes +/// the first one current and selected, clears the panel's selected action and step, its expanded +/// actions and a step being dragged, and closes an open Set Options, New Action, Batch or step +/// dialog that names a set. When the panel already shows the built-in sets that way, nothing +/// changes and the sets keep their ids. `append` adds a new copy of the built-in sets after the +/// sets there are, a name already in use getting the next free number (`Default Actions 2`), and +/// keeps the current set and the selection. Omitted params (`null`) count as `{}`. Params of another +/// type, another key, or another `mode` is an error, and so is a reset while an action records or +/// plays (also while it waits at a stop); then nothing changes. No undo step is recorded. +/// → {changed, mode, set: the index of the first built-in set} +pub fn reset(app: &mut VectorcraftApp, p: &Value) -> Result { + const SELECTED: &str = "actions-selected"; + const EXPANDED: &str = "actions-expanded"; + let append = match p { + Value::Null => false, + Value::Object(m) => { + if let Some(key) = m.keys().find(|k| *k != "mode") { + let keys = "mode"; + return Err(format!("unknown parameter `{key}`; the command takes: {keys}")); + } + match m.get("mode").map(Value::as_str) { + None | Some(Some("replace")) => false, + Some(Some("append")) => true, + Some(_) => return Err("mode must be replace or append".into()), + } + } + got => return Err(format!("the params must be an object, not {got}")), + }; + if app.ui.recording.is_some() { + return Err("an action is already recording".into()); + } + if app.ui.action_playing.is_some() { + return Err("an action is already playing".into()); + } + let sets = default_sets(); + if append { + let first = app.ui.action_sets.len(); + for mut set in sets { + set.name = files::free_set_name(&app.ui.action_sets, &set.name); + app.ui.action_sets.push(set); + } + return Ok(json!({ "changed": true, "mode": "append", "set": first })); + } + let ctx = app.ui_ctx.clone(); + let panel_clear = ctx.as_ref().is_none_or(|ctx| { + pstate::>(ctx, SELECTED).is_none() + && pstate::>(ctx, SELECTED_STEP).is_none() + && pstate::>(ctx, DRAGGED_STEP).is_none() + && pstate::>(ctx, EXPANDED).is_empty() + }); + // The ids are not saved, so two lists that save alike hold the same sets. + let built_in = serde_json::to_value(&app.ui.action_sets).is_ok_and(|now| serde_json::to_value(&sets).is_ok_and(|new| new == now)); + let shown_as_reset = app.ui.action_set == Some(0) && app.ui.action_sets_selected == [0] && !app.ui.dialog.as_ref().is_some_and(holds_set); + if built_in && shown_as_reset && panel_clear { + return Ok(json!({ "changed": false, "mode": "replace", "set": 0 })); + } + app.ui.action_sets = sets; + app.ui.action_set = Some(0); + app.ui.action_sets_selected = vec![0]; + if app.ui.dialog.as_ref().is_some_and(holds_set) { + app.ui.dialog = None; + } + if let Some(ctx) = ctx { + set_pstate::>(&ctx, SELECTED, None); + set_pstate::>(&ctx, SELECTED_STEP, None); + set_pstate::>(&ctx, DRAGGED_STEP, None); + set_pstate(&ctx, EXPANDED, BTreeSet::::new()); + } + Ok(json!({ "changed": true, "mode": "replace", "set": 0 })) +} + /// The panel's (≡) menu. pub fn menu(app: &mut VectorcraftApp, ui: &mut egui::Ui) { // Button Mode is off while an action records, so the Stop button the list shows stays in reach. @@ -2239,6 +2314,10 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut egui::Ui) { app.status(e); } } + // Asks first: OK replaces the sets with the built-in set, Append adds it after them. + if widgets::menu_item(ui, tl!("Reset Actions"), !recording && app.ui.action_playing.is_none(), false) { + crate::dialogs::confirm::ask_reset_actions(app); + } } fn inclusion_box( @@ -3744,6 +3823,170 @@ mod tests { assert_eq!(app.ui.dialog.as_ref().map(|d| d.fields["set"].clone()), Some(json!(3)), "Set Options still on Other"); } + /// The sets as Save Actions… writes them, without the ids. + fn saved_sets(sets: &[ActionSet]) -> Value { + serde_json::to_value(sets).unwrap() + } + + /// A click on the panel menu's Reset Actions. + fn menu_reset(ctx: &egui::Context, app: &mut VectorcraftApp) { + use super::super::tests_appearance::{click, frame_events}; + let texts = frame_events(ctx, app, vec![], menu); + let item = texts.iter().find(|(s, _)| s.trim() == "Reset Actions").map(|(_, r)| *r).expect("Reset Actions in the menu"); + click(ctx, app, item.center(), menu); + } + + /// The panel menu's Reset Actions asks before it changes anything, also with no current set, + /// and does nothing while an action records or plays, waiting at a stop included. + #[test] + fn the_panel_menus_reset_actions_asks_first_and_is_off_while_an_action_runs() { + let mut app = app_with_sets(); + let ctx = egui::Context::default(); + let before = saved_sets(&app.ui.action_sets); + menu_reset(&ctx, &mut app); + let d = app.ui.dialog.as_ref().expect("Reset Actions asks first, with no current set too"); + assert_eq!((d.kind.as_str(), d.bool("append")), (crate::dialogs::confirm::RESET_ACTIONS, false)); + assert_eq!(saved_sets(&app.ui.action_sets), before, "asking changes no set"); + app.ui.dialog = None; + + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run(START_RECORDING, json!({})).unwrap(); + menu_reset(&ctx, &mut app); + assert!(app.ui.dialog.is_none(), "off while an action records"); + app.run(STOP_RECORDING, json!({})).unwrap(); + + let (mut app, _) = app_with_a_stop(true); + play(&mut app, 0, 0).unwrap(); + assert!(waiting_at_stop(&app)); + app.ui.dialog = None; + menu_reset(&ctx, &mut app); + assert!(app.ui.dialog.is_none(), "off while playback waits at a stop"); + } + + /// `ui.actionSet.reset` replaces every set, edited ones included, with the built-in set, makes it + /// current and selected, clears the panel's selected action and step, expanded actions and a + /// dragged step, closes a dialog that holds a set index, and records no undo step. + #[test] + fn reset_replaces_every_set_with_the_built_in_set_and_clears_what_named_the_old_ones() { + let mut app = app_with_sets(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let undo = undo_steps(&app); + app.ui.action_sets[0].name = "Renamed".into(); + app.ui.action_sets[0].actions.pop(); + app.ui.action_set = Some(2); + app.ui.action_sets_selected = vec![1, 2]; + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + let nudge = app.ui.action_sets[1].actions[1].id; + set_pstate::>(&ctx, "actions-selected", Some((1, 1))); + set_pstate::>(&ctx, SELECTED_STEP, Some((nudge, 0))); + set_pstate(&ctx, "actions-expanded", BTreeSet::from([nudge])); + let dragged: DraggedStep = (nudge, 0, std::sync::Arc::new((vec![], BTreeSet::new()))); + set_pstate::>(&ctx, DRAGGED_STEP, Some(dragged)); + crate::dialogs::action_batch::open(&mut app, 1, 1).unwrap(); + + assert_eq!(app.run(RESET, json!({})).unwrap(), json!({"changed": true, "mode": "replace", "set": 0})); + assert_eq!(saved_sets(&app.ui.action_sets), saved_sets(&default_sets()), "only the built-in set, as it comes"); + assert_eq!((app.ui.action_set, app.ui.action_sets_selected.clone()), (Some(0), vec![0]), "it is current and selected"); + assert_eq!(pstate::>(&ctx, "actions-selected"), None); + assert_eq!(pstate::>(&ctx, SELECTED_STEP), None); + assert!(pstate::>(&ctx, "actions-expanded").is_empty()); + assert!(pstate::>(&ctx, DRAGGED_STEP).is_none()); + assert!(app.ui.dialog.is_none(), "the Batch dialog of a replaced set closes"); + assert_eq!(undo_steps(&app), undo, "no undo step"); + + app.ui.action_sets.clear(); + app.ui.action_set = None; + assert_eq!(app.run(RESET, Value::Null).unwrap(), json!({"changed": true, "mode": "replace", "set": 0}), "from no sets"); + assert_eq!(saved_sets(&app.ui.action_sets), saved_sets(&default_sets())); + assert_eq!(app.ui.action_set, Some(0)); + } + + /// Reset Actions on the built-in set as it comes still makes it current when no set is, and + /// changes nothing, ids included, once the panel shows it as a reset leaves it. + #[test] + fn reset_on_the_built_in_set_makes_it_current_then_changes_nothing() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + assert_eq!(app.ui.action_set, None, "a new app has no current set"); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + assert_eq!(app.run(RESET, json!({"mode": "replace"})).unwrap()["changed"], true, "the set becomes current"); + assert_eq!((app.ui.action_set, app.ui.action_sets_selected.clone()), (Some(0), vec![0])); + let ids = (app.ui.action_sets[0].id, app.ui.action_sets[0].actions.iter().map(|a| a.id).collect::>()); + assert_eq!(app.run(RESET, json!({})).unwrap(), json!({"changed": false, "mode": "replace", "set": 0})); + assert_eq!((app.ui.action_sets[0].id, app.ui.action_sets[0].actions.iter().map(|a| a.id).collect()), ids, "the ids stay"); + set_pstate(&ctx, "actions-expanded", BTreeSet::from([ids.1[0]])); + assert_eq!(app.run(RESET, json!({})).unwrap()["changed"], true, "an expanded action is collapsed"); + crate::dialogs::action_set_options::open(&mut app, 0); + assert_eq!(app.run(RESET, json!({})).unwrap()["changed"], true, "Set Options for the set closes"); + assert!(app.ui.dialog.is_none()); + } + + /// Append adds a copy of the built-in set after the sets there are, with the first free number, + /// and keeps every set, the current set, the selection and an open dialog as they are. + #[test] + fn reset_append_adds_the_built_in_set_with_a_free_number_and_keeps_the_rest() { + let mut app = app_with_sets(); + app.ui.action_sets[0].actions.pop(); + app.ui.action_sets[2].name = "Default Actions 3".into(); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + set_pstate::>(&ctx, "actions-selected", Some((1, 1))); + let before = saved_sets(&app.ui.action_sets); + assert_eq!(app.run(RESET, json!({"mode": "append"})).unwrap(), json!({"changed": true, "mode": "append", "set": 3})); + assert_eq!(set_names(&app), ["Default Actions", "Mine", "Default Actions 3", "Default Actions 2"]); + assert_eq!(saved_sets(&app.ui.action_sets[..3]), before, "the sets there were stay as they were"); + assert_eq!(saved_sets(&app.ui.action_sets[3..])[0]["actions"], saved_sets(&default_sets())[0]["actions"], "the built-in actions"); + assert_eq!(app.ui.action_set, None, "still no current set"); + assert_eq!(pstate::>(&ctx, "actions-selected"), Some((1, 1)), "the selection stays"); + app.ui.action_set = Some(1); + app.ui.action_sets_selected = vec![1]; + crate::dialogs::action_batch::open(&mut app, 1, 0).unwrap(); + assert_eq!(app.run(RESET, json!({"mode": "append"})).unwrap()["set"], 4); + assert_eq!(set_names(&app)[4], "Default Actions 4"); + assert_eq!((app.ui.action_set, app.ui.action_sets_selected.clone()), (Some(1), vec![1]), "the current set stays"); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.kind == crate::dialogs::action_batch::KIND), "the Batch dialog stays open"); + } + + /// `ui.actionSet.reset` refuses params that are not an object, another key or mode, and a reset + /// while an action records or plays, waiting at a stop included, and then changes nothing. + #[test] + fn reset_refuses_bad_params_and_a_running_action_and_changes_nothing() { + let mut app = app_with_sets(); + let before = saved_sets(&app.ui.action_sets); + for (p, error) in [ + (json!(1), "the params must be an object, not 1"), + (json!("append"), "the params must be an object, not \"append\""), + (json!([]), "the params must be an object, not []"), + (json!({"mode": null}), "mode must be replace or append"), + (json!({"mode": 1}), "mode must be replace or append"), + (json!({"mode": "clear"}), "mode must be replace or append"), + (json!({"mode": "append", "set": 0}), "unknown parameter `set`; the command takes: mode"), + ] { + assert_eq!(app.run(RESET, p.clone()).unwrap_err(), error, "{p}"); + assert_eq!(saved_sets(&app.ui.action_sets), before, "{p} changes nothing"); + assert_eq!(app.ui.action_set, None); + } + + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run(START_RECORDING, json!({})).unwrap(); + for mode in ["replace", "append"] { + assert_eq!(app.run(RESET, json!({ "mode": mode })).unwrap_err(), "an action is already recording"); + } + assert_eq!(saved_sets(&app.ui.action_sets), before, "a recording keeps its set"); + app.run(STOP_RECORDING, json!({})).unwrap(); + + let (mut app, _) = app_with_a_stop(true); + let before = saved_sets(&app.ui.action_sets); + play(&mut app, 0, 0).unwrap(); + assert!(waiting_at_stop(&app)); + for mode in ["replace", "append"] { + assert_eq!(app.run(RESET, json!({ "mode": mode })).unwrap_err(), "an action is already playing"); + } + assert_eq!(saved_sets(&app.ui.action_sets), before, "the playing set stays"); + } + /// A recording keeps its steps when a canceled undo group drops journal entries made before the /// recording began. #[test] diff --git a/crates/ui-egui/src/panels/actions/files.rs b/crates/ui-egui/src/panels/actions/files.rs index 5bdd0b9a98..d6ca465275 100644 --- a/crates/ui-egui/src/panels/actions/files.rs +++ b/crates/ui-egui/src/panels/actions/files.rs @@ -275,7 +275,7 @@ pub fn read_set(text: &str, name: &str) -> Result { } /// `name`, else `name 2`, `name 3` … : the first that no set in `sets` has. -fn free_set_name(sets: &[ActionSet], name: &str) -> String { +pub(super) fn free_set_name(sets: &[ActionSet], name: &str) -> String { let taken = |n: &str| sets.iter().any(|s| s.name == n); if !taken(name) { return name.to_string(); diff --git a/docs/mcp.md b/docs/mcp.md index c7aa202d3f..cad6802efa 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3957,6 +3957,17 @@ already walks Image Trace. Short agent entry points: " copy" added, a copied set gets an id of its own, and the copy is selected. An index past the last set or action is an error, and so is a copy that would give its set more than 1,000 actions or a file larger than 8 MiB; then nothing is copied. The panel menu's Duplicate runs this for the selected action, else the current set. + `ui.actionSet.reset {mode?: "replace" | "append"}` is Reset Actions, and returns `{changed, mode, set}` (`set` is + the index of the first built-in set). `replace`, the default, replaces every set in the panel with a new copy of + VectorCraft's built-in Default Actions set, makes it current and selected, clears the panel's selected action and + step and its expanded actions, and closes an open Set Options, New Action, Batch or step dialog that names a set; + when the panel already shows only the built-in set as it comes in that state, nothing changes, the sets keep their + ids and `changed` is false. `append` adds a new copy of the built-in set after the sets there are, with the + next free number when its name is in use (`Default Actions 2`), and keeps the current set and the selection. + Omitted params count as `{}`. Params of another type, another key, another `mode`, or a reset while an action + records or plays (also while it waits at a stop) is an error and changes nothing. Reset records no undo step. The panel menu's Reset + Actions is disabled while an action records or plays; it opens a `resetActions` question (fields `message`, + `detail`, `append`): OK runs this with `replace`, Append with `append`, and `ui.dialog.cancel` changes nothing. - Image Trace: `imageTrace.presets`, `imageTrace.make {id?, preset?, params?, view?}` (or `imageTrace.makeAndExpand`), `imageTrace.setView`, `imageTrace.expand`, `imageTrace.release`. A key inside `params` that is not one of the trace settings, such as `colours`, is an error that names it and the nearest setting (`colors`), as for a command's own keys. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..54c6d5a3e8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -845,6 +845,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Actions panel: the panel menu's Select Object… opens Set Selection, where the note typed names the objects to select, and adds a step to the recording in progress, after the selected step, or at the end of the selected action; playback selects the objects whose Attributes note matches it, and the steps after it act on them ([Insert non-recordable tasks into actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/insert-non-recordable-tasks-into-actions.html); `ui.action.insertSelectObject`, `select.byNote`). VectorCraft's own rules, which the page does not cover: the note matches anywhere and in any letter case unless Case Sensitive or Whole Word is checked, hidden and locked objects are left out, the objects found replace the selection, a step that finds none stops the playback with an error, and the note is at most 1,024 bytes. Action sets with the step save as version 4. - Actions panel: Delete Selection deletes the selected action set with its actions and keeps the other sets ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html); `ui.actionSet.delete`). VectorCraft's own rules, which the overview does not cover: deleting a set asks first, Shift-click on a set's name selects a range of sets to delete together, the panel menu's Delete does the same, and Default Actions and the last set can be deleted. Undo does not bring a deleted set back. - Actions panel: the panel menu's Duplicate copies the selected action, else the current action set with all its actions ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html); `ui.actionSet.duplicate`). VectorCraft's own rules, which the overview does not cover: the copy goes right after the original, is named after it with " copy" added and is selected. + - Actions panel: the panel menu's Reset Actions asks first; OK replaces the sets in the panel with the default set, and Append adds the default set after them ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/manage-a-set-of-actions.html); `ui.actionSet.reset`). VectorCraft's own rules, which the page does not cover: the default set is VectorCraft's own Default Actions set; after OK it is current and selected, and no action or step is selected; Append names its copy with the next free number (`Default Actions 2`) and keeps the current set; Cancel changes nothing; the item is off while an action records or plays, waiting at a stop included; Undo does not bring the old sets back. Tests `panels::actions::tests::{the_panel_menus_reset_actions_asks_first_and_is_off_while_an_action_runs, reset_replaces_every_set_with_the_built_in_set_and_clears_what_named_the_old_ones, reset_on_the_built_in_set_makes_it_current_then_changes_nothing, reset_append_adds_the_built_in_set_with_a_free_number_and_keeps_the_rest, reset_refuses_bad_params_and_a_running_action_and_changes_nothing}`, `dialogs::tests::reset_actions_ok_replaces_append_adds_and_cancel_keeps_the_sets`. - Batch… over data sets names each file after the document and the data set (`action.batch`). It writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds `-2`, `-3`… to a name an earlier data set used. - Batch… offers File + Number, File + Data Set Name, and Data Set Name for a Data Sets source. The dialog defaults to File + Number; `action.batch` without `datasetFileNaming` keeps File + Data Set Name. An output already in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix. [Batch options](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/batch-options.html). - The Batch dialog shows its data set File Name row only when Destination is Folder, and keeps the choice while another destination is picked. With None or Save and Close it does not send `datasetFileNaming`. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 8e06948b33..c499df1e1a 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -418,7 +418,8 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Live trace result bounds and selection highlights exclude the retained bitmap; source-image views retain it | done | All TraceView modes and rotated result bounds regression-covered; ordinary hidden group behavior retained | | Image Trace panel: the Preview checkbox before Trace chooses whether a setting change traces the selected Image Trace object again at once | done | Per the public documentation, Preview shows the result of the current settings and Trace traces with them (). Preview is on by default and kept with the UI preferences; Reset to Default leaves it. Off, changes wait in the panel until Trace applies them as one undo step, or until Preview is turned on again. Changes stay with the object they were made for while another object is selected, and come back when it is selected again. `imageTrace.preview {on?}`, `ui.set {imageTracePreview}`; `panels/image_trace.rs` headless tests (`with_preview_off_a_slider_change_waits_for_trace`, `turning_preview_on_traces_the_changes_that_waited`, `preview_turned_on_with_nothing_selected_traces_when_the_object_is_selected_again`, `settings_that_wait_stay_with_their_object`, `settings_that_wait_come_back_when_their_object_is_selected_again`, `settings_that_wait_are_dropped_when_their_object_changed_since`, `preview_is_kept_with_the_preferences_and_reset_to_default_leaves_it`) | | Toolbar without group labels by default, one or two columns; All Tools drawer by flyout group with shortcuts, its menu (Reset, Basic, Advanced) and Show section | done | #1751; a preference brings the labels back; `toolbar.show` sets the Fill/Stroke, Coloring, Draw Mode and Screen Mode controls | -| Actions panel: ≡ › Save Actions… saves the current set with all its actions to a file and ≡ › Load Actions… adds a saved set ([Manage a set of actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/manage-a-set-of-actions.html)) | partial | `ui.actionSet.save`, `ui.actionSet.load`; `panels/actions.rs` tests. The file is VectorCraft's own `.vcactions` JSON; Reset, Clear and Replace Actions remain | +| Actions panel: ≡ › Save Actions… saves the current set with all its actions to a file and ≡ › Load Actions… adds a saved set ([Manage a set of actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/manage-a-set-of-actions.html)) | partial | `ui.actionSet.save`, `ui.actionSet.load`; `panels/actions.rs` tests. The file is VectorCraft's own `.vcactions` JSON; Clear and Replace Actions remain | +| Actions panel: ≡ › Reset Actions asks first; OK replaces the sets in the panel with the default set and Append adds the default set after them ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/manage-a-set-of-actions.html)) | done | `ui.actionSet.reset`; `panels/actions.rs` and `dialogs/tests.rs` tests. The default set is VectorCraft's own Default Actions set | | Actions panel: ≡ › Load Actions… also reads action sets saved as `.aia` files ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | partial | `actionSet.read`, `ui.actionSet.load`; `tests/actionset.rs`, `panels/actions.rs` tests, `import_fuzz`. Steps with a label and no recorded values come in as menu commands that run with no values and open no dialog, matched by label, and Set Selection steps come in as Select Object steps; the other steps, recorded menu items included, are left out and counted | | Actions panel: ≡ › Action Options… renames the selected action and sets its function key and color ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | partial | `ui.action.options`; `panels/actions.rs` tests (part of #1629). Button Mode shows the color | | Actions panel: ≡ › Button Mode shows each action by name as a button in its Action Options color, without sets or steps; a click on a button plays the action, and choosing Button Mode again shows the list ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | done | `ui.action.buttonMode`, `ui.action.playAt`; `panels/actions.rs` tests. VectorCraft's own rules: every set's actions show in set order, an action without a color is an ordinary button, the mode is kept with the UI preferences, and it cannot be turned on while an action records | From d738e7f0c0816fc3ce86f0f81cb11e082121d67e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 21:31:37 -0800 Subject: [PATCH 06/31] 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 42001569145960e05374e2d4422afd0dfb905517 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 23:18:17 -0800 Subject: [PATCH 07/31] Repeat: a selected Radial Repeat has handles for its instances and radius With one radial repeat selected, the Selection tool shows a handle below it and a handle on its circle between the first two instances. Dragging the first one down adds an instance for every 16 px and dragging it up removes them (1 to 1,000). Dragging the second one outward or inward makes the radius larger or smaller (0 or more); only the part of the drag along the line from the center counts. Each drag previews and commits object.repeat.options as one undo step, Escape cancels it, and a drag that ends where it began leaves no undo step. The handles hide with the edges or the bounding box and for a locked or hidden repeat, and bounding-box handles keep priority where they meet, as with Grid Repeat. --- crates/tools/src/lib.rs | 1 + crates/tools/src/repeat_radial.rs | 436 +++++++++++++++++++++ crates/tools/src/select.rs | 40 +- crates/ui-egui/src/canvas.rs | 3 +- crates/ui-egui/src/canvas/tests.rs | 96 +++++ crates/ui-egui/src/canvas/tool_overlays.rs | 26 ++ docs/gaps.md | 2 +- docs/target-app-parity.md | 1 + docs/ui-parity.md | 2 +- 9 files changed, 602 insertions(+), 5 deletions(-) create mode 100644 crates/tools/src/repeat_radial.rs diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index a168c28396..07579cd456 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -34,6 +34,7 @@ pub mod pie; pub mod place; pub mod printtiling; pub mod repeat_grid; +pub mod repeat_radial; pub mod rulerguide; pub mod select; pub mod settings; diff --git a/crates/tools/src/repeat_radial.rs b/crates/tools/src/repeat_radial.rs new file mode 100644 index 0000000000..05eafc8d1b --- /dev/null +++ b/crates/tools/src/repeat_radial.rs @@ -0,0 +1,436 @@ +//! Radial Repeat's on-canvas handles: a handle below the repeat adds or removes instances, and a +//! handle on the circle the instances sit on sets its radius, as the public "Create radial +//! repeats" page describes. Drawing and hit testing share the document-space geometry of +//! [`RadialHandles::of`]; a drag previews the existing Repeat Options command and commits as one +//! undo step. +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, NodeId, NodeKind, OrientedBox, RepeatKind, Selection}; +use vectorcraft_geom::{Affine, Point, Rect, Vec2}; + +use crate::bbox::Handle; +use crate::{Action, Cursor, Mods, ToolContext}; + +/// The radius of the instances and radius handles (screen points). +pub const HANDLE_RADIUS: f32 = 5.0; + +/// How far (screen points) the instances handle sits below the bounding box, clear of its own +/// handles and rotate zones. +pub const HANDLE_GAP: f64 = 22.0; + +/// How far (screen points) the instances handle is dragged for each instance it adds or removes. +pub const INSTANCE_STEP: f64 = 16.0; + +/// How near (screen points) a press must come to a handle to take it. +const REACH: f64 = 8.0; + +/// The most instances a radial repeat has (as `object.repeat.options` accepts them). +const MAX_INSTANCES: f64 = 1000.0; + +/// A control of [`RadialHandles`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RadialPart { + /// Below the repeat: drag down for more instances, up for fewer. + Instances, + /// On the circle, between the first two instances: drag outward for a larger radius, inward + /// for a smaller one. + Radius, +} + +/// The controls of a selected radial repeat, in document space. +#[derive(Clone, Copy, Debug)] +pub struct RadialHandles { + pub id: NodeId, + instances: u32, + /// The circle the instances' centers sit on. + pub center: Point, + pub radius: f64, + /// The unit direction from the center to the radius handle. + out: Vec2, + /// Document points of drag for each instance. + step: f64, + pub instances_at: Point, + pub radius_at: Point, +} + +impl RadialHandles { + /// The controls of a single editable radial repeat selected whole, the instances handle placed + /// below `frame` (the bounding box the Selection tool shows; its geometric bounds without one) + /// at `zoom`. + pub fn of(doc: &Document, selection: &Selection, frame: Option, zoom: f64) -> Option { + let [id] = selection.objects.as_slice() else { return None }; + if !selection.anchors.is_empty() || !selection.segments.is_empty() || !doc.is_editable(*id) || !zoom.is_finite() || zoom <= 0.0 { + return None; + } + let n = doc.node(*id)?; + let NodeKind::Repeat(spec) = &n.kind else { return None }; + let RepeatKind::Radial { instances, radius, center, start_angle, end_angle, .. } = spec.kind else { return None }; + if ![radius, center.x, center.y, start_angle, end_angle].iter().all(|v| v.is_finite()) { + return None; + } + let source = spec.source_bounds()?; + if !finite(source.center()) { + return None; + } + // As `repeat_transforms` lays the instances out: the first one at `start_angle` from the + // source's own direction, the rest a step apart. + let instances = instances.clamp(1, 1000); + let mut d = source.center() - center; + if d.hypot() < 1e-9 { + d = Vec2::new(0.0, -1.0); + } + let sweep = end_angle - start_angle; + let full = (sweep.abs() - 360.0).abs() < 1e-9; + let step = if full || instances == 1 { sweep / f64::from(instances) } else { sweep / f64::from(instances - 1) }; + // Halfway between the first two instances (opposite the only one of a full turn). + let out = (Affine::rotate((start_angle + step / 2.0).to_radians()) * d.normalize().to_point()).to_vec2(); + let radius = radius.max(0.0); + let frame = match frame { + Some(f) => aabb(f.corners())?, + None => n.geometric_bounds_with(&doc.symbol_boxes())?, + }; + let h = Self { + id: *id, + instances, + center, + radius, + out, + step: INSTANCE_STEP / zoom, + instances_at: Point::new(frame.center().x, frame.y1 + HANDLE_GAP / zoom), + radius_at: center + out * radius, + }; + (finite(h.instances_at) && finite(h.radius_at) && h.step.is_finite() && h.step > 0.0).then_some(h) + } + + /// Both controls with where they are. + pub fn parts(&self) -> [(RadialPart, Point); 2] { + [(RadialPart::Instances, self.instances_at), (RadialPart::Radius, self.radius_at)] + } + + /// The control under `p` (the nearer within reach) and the repeat's controls, unless a + /// bounding-box handle is there, which keeps its scaling. + fn hit(cx: &ToolContext, p: Point) -> Option<(Self, RadialPart)> { + if !cx.show_bbox || !finite(p) { + return None; + } + let h = Self::of(cx.doc, cx.selection, crate::select::selection_box(cx), cx.zoom)?; + let reach = cx.tol(REACH); + let (part, _) = + h.parts().into_iter().map(|(part, q)| (part, q.distance(p))).filter(|(_, d)| *d <= reach).min_by(|a, b| a.1.total_cmp(&b.1))?; + (!crate::select::bbox_handle_at(cx, p)).then_some((h, part)) + } + + /// The Repeat Options that dragging `part` by `d` (document points) from the press gives; + /// none when the drag is too far to measure. + fn options(&self, part: RadialPart, d: Vec2) -> Option { + match part { + RadialPart::Instances => { + let n = f64::from(self.instances) + (d.y / self.step).round(); + // NaN only comes from an infinite drag; the clamp keeps a huge one at the limit. + (!n.is_nan()).then(|| json!({ "instances": n.clamp(1.0, MAX_INSTANCES) as u32 })) + } + RadialPart::Radius => { + // Only the part of the drag along the line from the center moves the circle. + let r = ((self.radius + d.dot(self.out)).max(0.0) * 100.0).round() / 100.0; + r.is_finite().then(|| json!({ "radius": r })) + } + } + } + + /// The direction (counter-clockwise degrees) in which the radius handle moves the circle out. + fn out_angle(&self) -> f64 { + (-self.out.y).atan2(self.out.x).to_degrees() + } +} + +/// The page-square bounds of `corners`. +fn aabb(corners: [Point; 4]) -> Option { + let r = corners.iter().skip(1).fold(Rect::from_points(corners[0], corners[0]), |r, p| r.union_pt(*p)); + [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()).then_some(r) +} + +fn finite(p: Point) -> bool { + p.x.is_finite() && p.y.is_finite() +} + +/// The resize cursor of `part`, turned with the view: up and down for the instances handle, along +/// the line from the center for the radius handle. +fn part_cursor(cx: &ToolContext, h: &RadialHandles, part: RadialPart) -> Cursor { + match part { + RadialPart::Instances => crate::select::handle_cursor(Handle::Bottom, -cx.view_angle()), + RadialPart::Radius => crate::select::handle_cursor(Handle::Right, h.out_angle() - cx.view_angle()), + } +} + +/// The cursor over a radial repeat's control at `p`, if one is there. +pub fn cursor(cx: &ToolContext, p: Point) -> Option { + let (h, part) = RadialHandles::hit(cx, p)?; + Some(part_cursor(cx, &h, part)) +} + +/// A drag of one of a radial repeat's controls. +#[derive(Clone, Debug)] +pub struct RadialDrag { + handles: RadialHandles, + part: RadialPart, + start: Point, + /// The options the press found, and the last ones previewed. + from: Value, + last: Option, +} + +impl RadialDrag { + pub fn hit(cx: &ToolContext, p: Point, mods: Mods) -> Option { + if mods.cmd || mods.ctrl || mods.alt { + return None; + } + let (handles, part) = RadialHandles::hit(cx, p)?; + let from = handles.options(part, Vec2::ZERO)?; + Some(Self { handles, part, start: p, from, last: None }) + } + + /// Whether the drag has changed the repeat (and so previews it). + pub fn adjusting(&self) -> bool { + self.last.is_some() + } + + pub fn cursor(&self, cx: &ToolContext) -> Cursor { + part_cursor(cx, &self.handles, self.part) + } + + /// Preview the options the pointer at `p` gives, when they change; the first change opens + /// the undo step. + pub fn drag(&mut self, p: Point) -> Vec { + if !finite(p) { + return vec![]; + } + let Some(v) = self.handles.options(self.part, p - self.start) else { return vec![] }; + if self.last.as_ref().unwrap_or(&self.from) == &v { + return vec![]; + } + let mut out = vec![]; + if self.last.is_none() { + out.push(Action::Begin("Repeat Options".into())); + } + out.push(Action::Preview("object.repeat.options".into(), v.clone())); + self.last = Some(v); + out + } + + /// Commit the drag; one that ends where it began leaves no undo step. + pub fn finish(self) -> Vec { + match self.last { + Some(v) if v == self.from => vec![Action::Cancel], + Some(_) => vec![Action::Commit], + None => vec![], + } + } + + pub fn cancel(self) -> Vec { + if self.last.is_some() { vec![Action::Cancel] } else { vec![] } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testutil::{cx, doc_with_rect, paint}; + use std::sync::Arc; + use vectorcraft_doc::pattern::RepeatSpec; + + /// [`doc_with_rect`]'s 100 × 100 square at (100, 100) as a radial repeat of eight instances + /// with a radius of 100 pt about (150, 250), selected. The instances span (0, 100)–(300, 400). + fn radial() -> (Document, Selection) { + let (mut doc, id) = doc_with_rect(); + let mut source = doc.node(id).unwrap().clone(); + source.id = doc.alloc_id(); + doc.node_mut(id).unwrap().kind = NodeKind::Repeat(RepeatSpec::radial(vec![Arc::new(source)], 8, Some(100.0))); + let mut selection = Selection::default(); + selection.set([id]); + (doc, selection) + } + + fn set(doc: &mut Document, selection: &Selection, f: impl FnOnce(&mut u32, &mut f64, &mut f64, &mut f64)) { + let NodeKind::Repeat(spec) = &mut doc.node_mut(selection.objects[0]).unwrap().kind else { panic!("a repeat") }; + let RepeatKind::Radial { instances, radius, start_angle, end_angle, .. } = &mut spec.kind else { panic!("a radial repeat") }; + f(instances, radius, start_angle, end_angle); + } + + fn near(a: Point, b: Point) -> bool { + a.distance(b) < 1e-6 + } + + fn preview(out: &[Action]) -> Option<&Value> { + out.iter().find_map(|a| match a { + Action::Preview(cmd, v) if cmd == "object.repeat.options" => Some(v), + _ => None, + }) + } + + #[test] + fn the_handles_sit_below_the_repeat_and_on_its_circle_at_every_zoom() { + let (doc, selection) = radial(); + // Halfway between the first instance (straight up from the center) and the second, 45° + // clockwise from it. + let half = 22.5_f64.to_radians(); + let on_circle = Point::new(150.0 + 100.0 * half.sin(), 250.0 - 100.0 * half.cos()); + for zoom in [0.02, 1.0, 4.0] { + let h = RadialHandles::of(&doc, &selection, None, zoom).unwrap(); + assert!(near(h.instances_at, Point::new(150.0, 400.0 + HANDLE_GAP / zoom)), "{zoom}: {:?}", h.instances_at); + assert!(near(h.radius_at, on_circle), "{zoom}: {:?}", h.radius_at); + assert_eq!((h.center, h.radius), (Point::new(150.0, 250.0), 100.0)); + } + // Placed below the bounding box the Selection tool shows. + let frame = OrientedBox::aligned(Rect::new(-10.0, 90.0, 310.0, 410.0)); + let h = RadialHandles::of(&doc, &selection, Some(frame), 1.0).unwrap(); + assert!(near(h.instances_at, Point::new(150.0, 410.0 + HANDLE_GAP))); + } + + #[test] + fn the_radius_handle_follows_the_instances_angles() { + let (mut doc, selection) = radial(); + // One instance: opposite it. + set(&mut doc, &selection, |n, _, _, _| *n = 1); + let h = RadialHandles::of(&doc, &selection, None, 1.0).unwrap(); + assert!(near(h.radius_at, Point::new(150.0, 350.0)), "{:?}", h.radius_at); + // Three instances over a quarter turn from 90°: between those at 90° and 135°. + set(&mut doc, &selection, |n, _, a, b| (*n, *a, *b) = (3, 90.0, 180.0)); + let h = RadialHandles::of(&doc, &selection, None, 1.0).unwrap(); + let a = 112.5_f64.to_radians(); + assert!(near(h.radius_at, Point::new(150.0 + 100.0 * a.sin(), 250.0 - 100.0 * a.cos())), "{:?}", h.radius_at); + // A radius of 0: at the center, still apart from the instances handle. + set(&mut doc, &selection, |_, r, _, _| *r = 0.0); + let h = RadialHandles::of(&doc, &selection, None, 1.0).unwrap(); + assert!(near(h.radius_at, Point::new(150.0, 250.0))); + assert!(h.radius_at.distance(h.instances_at) > 2.0 * REACH); + } + + #[test] + fn no_handles_without_a_single_valid_radial_repeat() { + let (mut doc, mut selection) = radial(); + for zoom in [0.0, -1.0, f64::NAN, f64::INFINITY] { + assert!(RadialHandles::of(&doc, &selection, None, zoom).is_none(), "{zoom}"); + } + let paint = paint(); + let h = RadialHandles::of(&doc, &selection, None, 1.0).unwrap(); + { + let mut c = cx(&doc, &selection, &paint); + assert!(cursor(&c, h.instances_at).is_some()); + c.show_bbox = false; + assert!(cursor(&c, h.instances_at).is_none(), "the bounding box is hidden"); + } + let id = selection.objects[0]; + doc.node_mut(id).unwrap().locked = true; + assert!(RadialHandles::of(&doc, &selection, None, 1.0).is_none(), "a locked repeat"); + doc.node_mut(id).unwrap().locked = false; + doc.node_mut(id).unwrap().visible = false; + assert!(RadialHandles::of(&doc, &selection, None, 1.0).is_none(), "a hidden repeat"); + doc.node_mut(id).unwrap().visible = true; + for bad in [f64::NAN, f64::INFINITY] { + set(&mut doc, &selection, |_, r, _, _| *r = bad); + assert!(RadialHandles::of(&doc, &selection, None, 1.0).is_none(), "radius {bad}"); + set(&mut doc, &selection, |_, r, a, _| (*r, *a) = (100.0, bad)); + assert!(RadialHandles::of(&doc, &selection, None, 1.0).is_none(), "start angle {bad}"); + set(&mut doc, &selection, |_, _, a, _| *a = 0.0); + } + let other = doc.alloc_id(); + let mut second = doc.node(id).unwrap().clone(); + second.id = other; + let layer = doc.layers[0].id; + doc.insert(Some(layer), 1, second).unwrap(); + selection.set([id, other]); + assert!(RadialHandles::of(&doc, &selection, None, 1.0).is_none(), "two objects selected"); + selection.set([id]); + let NodeKind::Repeat(spec) = &mut doc.node_mut(id).unwrap().kind else { panic!("a repeat") }; + spec.kind = RepeatKind::Grid { + h_spacing: 10.0, + v_spacing: 10.0, + rows: 3, + cols: 3, + grid_type: Default::default(), + flip_rows: false, + flip_cols: false, + }; + assert!(RadialHandles::of(&doc, &selection, None, 1.0).is_none(), "a grid repeat"); + } + + #[test] + fn dragging_the_instances_handle_steps_the_count() { + let (doc, selection) = radial(); + let paint = paint(); + let mut c = cx(&doc, &selection, &paint); + let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), 1.0).unwrap(); + let mut d = RadialDrag::hit(&c, h.instances_at, Mods::default()).unwrap(); + assert!(d.drag(h.instances_at + Vec2::new(0.0, 7.0)).is_empty(), "less than half a step changes nothing"); + assert!(!d.adjusting()); + // Two steps down, a little sideways: ten instances, one undo step. + let out = d.drag(h.instances_at + Vec2::new(5.0, 32.0)); + assert!(matches!(out.first(), Some(Action::Begin(l)) if l == "Repeat Options"), "{out:?}"); + assert_eq!(preview(&out), Some(&json!({"instances": 10}))); + assert!(d.drag(h.instances_at + Vec2::new(0.0, 36.0)).is_empty(), "the same count isn't previewed again"); + assert!(d.adjusting()); + assert!(matches!(d.finish().as_slice(), [Action::Commit])); + // Far up: one instance at least; far down: 1,000 at most. + let mut d = RadialDrag::hit(&c, h.instances_at, Mods::default()).unwrap(); + assert_eq!(preview(&d.drag(h.instances_at - Vec2::new(0.0, 900.0))), Some(&json!({"instances": 1}))); + assert_eq!(preview(&d.drag(h.instances_at + Vec2::new(0.0, 1e300))), Some(&json!({"instances": 1000}))); + assert!(d.drag(Point::new(f64::NAN, 0.0)).is_empty(), "a non-finite pointer"); + // Back where it began: no undo step. + assert_eq!(preview(&d.drag(h.instances_at)), Some(&json!({"instances": 8}))); + assert!(matches!(d.finish().as_slice(), [Action::Cancel])); + // The step is the same on screen at every zoom: 16 px is a quarter point at 64. + c.zoom = 64.0; + let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), c.zoom).unwrap(); + let mut d = RadialDrag::hit(&c, h.instances_at, Mods::default()).unwrap(); + assert_eq!(preview(&d.drag(h.instances_at - Vec2::new(0.0, 0.25))), Some(&json!({"instances": 7}))); + assert!(matches!(d.cancel().as_slice(), [Action::Cancel])); + // Alt, Cmd and Ctrl keep the Selection tool's own gestures. + assert!(RadialDrag::hit(&c, h.instances_at, Mods { alt: true, ..Mods::default() }).is_none()); + } + + #[test] + fn dragging_the_radius_handle_moves_the_circle_in_and_out() { + let (doc, selection) = radial(); + let paint = paint(); + let c = cx(&doc, &selection, &paint); + let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), 1.0).unwrap(); + let out = (h.radius_at - h.center) / 100.0; + let across = Vec2::new(-out.y, out.x); + let mut d = RadialDrag::hit(&c, h.radius_at, Mods::default()).unwrap(); + // 25 pt out and 40 pt across: only the outward part counts. + let o = d.drag(h.radius_at + out * 25.0 + across * 40.0); + assert!(matches!(o.first(), Some(Action::Begin(l)) if l == "Repeat Options"), "{o:?}"); + assert_eq!(preview(&o), Some(&json!({"radius": 125.0}))); + assert!(d.drag(h.radius_at + across * 30.0).iter().any(|a| matches!(a, Action::Preview(_, v) if v == &json!({"radius": 100.0})))); + // Past the center: a radius of 0. + assert_eq!(preview(&d.drag(h.radius_at - out * 250.0)), Some(&json!({"radius": 0.0}))); + // Too far to measure: nothing previewed. + assert!(d.drag(Point::new(f64::MAX, -f64::MAX)).is_empty()); + assert!(matches!(d.finish().as_slice(), [Action::Commit])); + // Escape before any change leaves nothing to undo. + let d = RadialDrag::hit(&c, h.radius_at, Mods::default()).unwrap(); + assert!(d.cancel().is_empty()); + } + + #[test] + fn a_bounding_box_handle_wins_where_they_overlap() { + let (doc, selection) = radial(); + let paint = paint(); + let mut c = cx(&doc, &selection, &paint); + // Zoomed far out (the 300 pt repeat 6 px across), the radius handle lies on a + // bounding-box handle, which keeps its scaling; the instances handle stays clear of the box. + c.zoom = 0.02; + let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), c.zoom).unwrap(); + assert!(crate::select::bbox_handle_at(&c, h.radius_at)); + assert!(RadialDrag::hit(&c, h.radius_at, Mods::default()).is_none()); + assert!(cursor(&c, h.radius_at).is_none()); + assert!(!crate::select::bbox_handle_at(&c, h.instances_at)); + assert!(RadialDrag::hit(&c, h.instances_at, Mods::default()).is_some()); + // At full size both are the repeat's, with resize cursors along their drags. + c.zoom = 1.0; + let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), c.zoom).unwrap(); + assert!(RadialDrag::hit(&c, h.radius_at, Mods::default()).is_some()); + assert_eq!(cursor(&c, h.instances_at), Some(Cursor::ResizeV)); + // The radius handle points 22.5° clockwise from straight up: the up-and-down cursor. + assert_eq!(cursor(&c, h.radius_at), Some(Cursor::ResizeV)); + } +} diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 8a755395dc..543f9c7bb1 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -147,6 +147,8 @@ enum State { Mirror(crate::mirror::MirrorDrag), /// Drag a grid repeat's row, column or corner handle or a spacing slider. GridRepeat(crate::repeat_grid::GridDrag), + /// Drag a radial repeat's instances or radius handle. + RadialRepeat(crate::repeat_radial::RadialDrag), /// Dragging a bracket of type on a path. Bracket(BracketDrag), /// Dragging a 9-slice guide of the symbol being edited. @@ -826,6 +828,12 @@ impl Tool for SelectionTool { { return d.cancel(); } + if key == ToolKey::Escape + && matches!(self.state, State::RadialRepeat(_)) + && let State::RadialRepeat(d) = std::mem::take(&mut self.state) + { + return d.cancel(); + } if key == ToolKey::Escape && matches!(self.state, State::NineSlice(_)) && let State::NineSlice(d) = std::mem::take(&mut self.state) @@ -875,7 +883,7 @@ impl Tool for SelectionTool { State::Marquee { .. } => key == ToolKey::Letter('e'), State::Corner(_) => matches!(key, ToolKey::Up | ToolKey::Down), State::BlendWidget(_) => matches!(key, ToolKey::Up | ToolKey::Down | ToolKey::Left | ToolKey::Right), - State::Loaded { .. } | State::Mirror(_) | State::GridRepeat(_) | State::NineSlice(_) => key == ToolKey::Escape, + State::Loaded { .. } | State::Mirror(_) | State::GridRepeat(_) | State::RadialRepeat(_) | State::NineSlice(_) => key == ToolKey::Escape, _ => false, } } @@ -917,6 +925,7 @@ impl Tool for SelectionTool { State::Bracket(b) => b.adjusting(), State::Mirror(d) => d.adjusting(), State::GridRepeat(d) => d.adjusting(), + State::RadialRepeat(d) => d.adjusting(), _ => false, } } @@ -1228,6 +1237,9 @@ impl Tool for SelectionTool { if let State::GridRepeat(d) = &self.state { return d.cursor(cx); } + if let State::RadialRepeat(d) = &self.state { + return d.cursor(cx); + } if matches!(self.state, State::NineSlice(_)) || (matches!(self.state, State::Idle) && crate::nineslice::over_guide(cx, p)) { return Cursor::Move; } @@ -1235,7 +1247,8 @@ impl Tool for SelectionTool { && !m.cmd && !m.ctrl && !m.alt - && let Some(cursor) = crate::mirror::cursor(cx, p).or_else(|| crate::repeat_grid::cursor(cx, p)) + && let Some(cursor) = + crate::mirror::cursor(cx, p).or_else(|| crate::repeat_grid::cursor(cx, p)).or_else(|| crate::repeat_radial::cursor(cx, p)) { return cursor; } @@ -1553,6 +1566,21 @@ impl SelectionTool { _ => return Some(vec![]), } } + if let State::RadialRepeat(mut d) = self.state.clone() { + match ev.kind { + PointerKind::Drag | PointerKind::Up => { + let mut out = d.drag(ev.pos); + if ev.kind == PointerKind::Up { + out.extend(d.finish()); + self.state = State::Idle; + } else { + self.state = State::RadialRepeat(d); + } + return Some(out); + } + _ => return Some(vec![]), + } + } if matches!(self.state, State::Idle) && ev.kind == PointerKind::Down && let Some(d) = crate::mirror::MirrorDrag::hit(cx, ev.pos, ev.mods) @@ -1569,6 +1597,14 @@ impl SelectionTool { self.hover = None; return Some(vec![]); } + if matches!(self.state, State::Idle) + && ev.kind == PointerKind::Down + && let Some(d) = crate::repeat_radial::RadialDrag::hit(cx, ev.pos, ev.mods) + { + self.state = State::RadialRepeat(d); + self.hover = None; + return Some(vec![]); + } None } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 847b60fd87..ba72946d38 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -78,7 +78,7 @@ use tool_overlays::{DIAL_RADIUS, HiddenMarks}; pub use tool_overlays::{HiddenChars, SpellingMarks}; use tool_overlays::{ grid_repeat_overlay, hidden_chars_overlay, live_paint_gap_overlays, mirror_axis_overlay, nine_slice_overlay, original_path_overlay, - print_tiling_overlay, rotate_view_dial, shaper_widget_overlay, slice_overlay, spelling_overlay, thread_overlays, + print_tiling_overlay, radial_repeat_overlay, rotate_view_dial, shaper_widget_overlay, slice_overlay, spelling_overlay, thread_overlays, }; pub(crate) use view::animated_zoom; pub(crate) use view::drag_rotation; @@ -1347,6 +1347,7 @@ fn selection_visuals( draw_inside_overlay(app, painter, xf); mirror_axis_overlay(app, painter, xf); grid_repeat_overlay(app, painter, xf); + radial_repeat_overlay(app, painter, xf); if app.ui.view.text_threads { // Under the tools' overlays: a selected frame's own ports are drawn over its thread's. let mut threads = thread_overlays(app, xf.zoom); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 9a5d7fc0b3..4f01911a26 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -4722,6 +4722,102 @@ fn grid_repeat_handles_set_rows_and_spacing_in_one_undo_step_each() { assert_eq!((grid(&app).0, grid(&app).2), (5, 10.0), "the spacing's own undo step"); } +/// A selected radial repeat draws its instances handle and its radius handle (none with the +/// bounding box hidden). In a zoomed view turned 30°, dragging the instances handle two steps down +/// adds two instances without scaling the source, and dragging the radius handle 20 pt outward +/// makes the circle 20 pt larger, as one undo step each; Escape puts a drag back. +#[test] +fn radial_repeat_handles_set_instances_and_radius_in_one_undo_step_each() { + use vectorcraft_tools::repeat_radial::{HANDLE_RADIUS, INSTANCE_STEP, RadialHandles}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 180, "y": 40, "width": 40, "height": 40})).unwrap(); + app.run("object.repeat.radial", json!({"instances": 6, "radius": 60})).unwrap(); + app.ui.task_bar = false; + app.ui.view.rulers = false; + let ctx = egui::Context::default(); + // The first frame fits the artboard in the window; then zoom to 1.5 px a point and turn 30°. + frame(&mut app, &ctx, vec![]); + app.view_mut().unwrap().zoom = 1.5; + app.view_mut().unwrap().rotation = 30.0; + frame(&mut app, &ctx, vec![]); + // Instances, radius and the source's bounds. + let radial = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + let n = st.doc.node(st.selection.objects[0]).unwrap(); + let vectorcraft_doc::NodeKind::Repeat(spec) = &n.kind else { panic!("a repeat") }; + let vectorcraft_doc::RepeatKind::Radial { instances, radius, .. } = spec.kind else { panic!("a radial repeat") }; + (instances, radius, spec.source_bounds().unwrap()) + }; + let handles = |app: &mut VectorcraftApp| { + let frame = app.selection_box(); + let st = app.session.active().unwrap(); + RadialHandles::of(&st.doc, &st.selection, frame, app.view().unwrap().zoom).unwrap() + }; + let before = radial(&app); + assert_eq!((before.0, before.1), (6, 60.0)); + let h = handles(&mut app); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let circle_at = + |drawn: &[Shape], at: Pos2| drawn.iter().any(|s| matches!(s, Shape::Circle(c) if c.center.distance(at) < 0.01 && c.radius == HANDLE_RADIUS)); + let drawn = shapes(&mut app, &ctx); + assert!(circle_at(&drawn, xf.to_screen(h.instances_at)), "the instances handle is drawn"); + assert!(circle_at(&drawn, xf.to_screen(h.radius_at)), "the radius handle is drawn"); + app.ui.view.bounding_box = false; + let drawn = shapes(&mut app, &ctx); + assert!(!circle_at(&drawn, xf.to_screen(h.instances_at)) && !circle_at(&drawn, xf.to_screen(h.radius_at)), "hidden with the bounding box"); + app.ui.view.bounding_box = true; + frame(&mut app, &ctx, vec![]); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let drag = |app: &mut VectorcraftApp, from: Pos2, to: Pos2| { + frame(app, &ctx, vec![egui::Event::PointerMoved(from), button(from, true)]); + for k in 1..=4 { + frame(app, &ctx, vec![egui::Event::PointerMoved(from + (to - from) * k as f32 / 4.0)]); + } + }; + let release = |app: &mut VectorcraftApp, at: Pos2| frame(app, &ctx, vec![button(at, false)]); + // 2.2 steps down the page (the screen's down turned 30°): two more instances. + let to = xf.to_screen(h.instances_at + vectorcraft_geom::Vec2::new(0.0, 2.2 * INSTANCE_STEP / 1.5)); + drag(&mut app, xf.to_screen(h.instances_at), to); + assert_eq!(radial(&app).0, 8, "the drag previews"); + release(&mut app, to); + let after = radial(&app); + assert_eq!((after.0, after.1), (8, 60.0)); + assert_eq!(after.2, before.2, "the source keeps its size"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(radial(&app).0, 6, "one undo step"); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(radial(&app).0, 8); + // 20 pt outward from the center. + frame(&mut app, &ctx, vec![]); + let h = handles(&mut app); + let out = (h.radius_at - h.center) / h.radius; + let to = xf.to_screen(h.radius_at + out * 20.0); + drag(&mut app, xf.to_screen(h.radius_at), to); + release(&mut app, to); + assert_eq!((radial(&app).0, radial(&app).1), (8, 80.0)); + assert_eq!(radial(&app).2, before.2, "the source keeps its size"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!((radial(&app).0, radial(&app).1), (8, 60.0), "the radius's own undo step"); + // Escape during a drag puts the radius back and leaves no undo step. + frame(&mut app, &ctx, vec![]); + let h = handles(&mut app); + drag(&mut app, xf.to_screen(h.radius_at), xf.to_screen(h.radius_at + out * 30.0)); + assert_eq!(radial(&app).1, 90.0, "the drag previews"); + let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); + let mut full = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events: vec![escape], ..Default::default() }, |ui| { + crate::shortcuts::handle(&mut app, ui.ctx()); + show(&mut app, ui) + }); + full.textures_delta.clear(); + assert_eq!(radial(&app).1, 60.0); + release(&mut app, xf.to_screen(h.radius_at + out * 30.0)); + assert_eq!(radial(&app).1, 60.0, "the release after Escape changes nothing"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(radial(&app).0, 6, "the instances step is the one before"); +} + /// While a symbol with 9-slice guides is edited, the canvas draws its four guides dotted across /// its art, with ruler guides hidden too, and none once the mode ends. Dragging the left guide in /// a zoomed view moves that guide alone, as one undo step. diff --git a/crates/ui-egui/src/canvas/tool_overlays.rs b/crates/ui-egui/src/canvas/tool_overlays.rs index 67f6ac861a..b05259f8f6 100644 --- a/crates/ui-egui/src/canvas/tool_overlays.rs +++ b/crates/ui-egui/src/canvas/tool_overlays.rs @@ -535,6 +535,32 @@ pub(super) fn grid_repeat_overlay(app: &mut VectorcraftApp, p: &egui::Painter, x } } +/// A selected radial repeat's circle with its radius handle on it, and its instances handle below +/// it, at the places the Selection tool's hit testing finds them. +pub(super) fn radial_repeat_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: &Xf) { + use vectorcraft_tools::repeat_radial::{HANDLE_RADIUS, RadialHandles}; + if app.session.tool_id() != "selection" || !app.ui.view.bounding_box { + return; + } + let frame = app.selection_box(); + let Some(st) = app.session.active() else { return }; + let Some(h) = RadialHandles::of(&st.doc, &st.selection, frame, xf.zoom) else { return }; + let t = Tokens::get(p.ctx()); + // The circle the instances' centers sit on, while it is a sensible size on screen. + let (c, r) = (xf.to_screen(h.center), (h.radius * xf.zoom) as f32); + if c.is_finite() && r.is_finite() && r > 0.5 && r < 20_000.0 { + p.circle_stroke(c, r, Stroke::new(3.0, t.measure_bg)); + p.circle_stroke(c, r, Stroke::new(1.0, t.selection)); + } + for (_, at) in h.parts() { + let c = xf.to_screen(at); + if c.is_finite() { + p.circle_filled(c, HANDLE_RADIUS, t.measure_bg); + p.circle_stroke(c, HANDLE_RADIUS, Stroke::new(2.0, t.selection)); + } + } +} + /// The radius of the Rotate View dial, in screen points. pub(super) const DIAL_RADIUS: f32 = 40.0; diff --git a/docs/gaps.md b/docs/gaps.md index eda7bb21dd..088912552d 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -139,7 +139,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Done:** the selection tools take a clipping path (a clip group's or a layer's clipping mask) on its outline, within the selection tolerance, before the art it clips, so Direct Selection reshapes a mask where the art covers its edge; Select Behind lists the same, and the eyedropper and the tools that act on what is drawn are unchanged. Broader G1 estimates unchanged. - **Done:** one selected clip group's Properties panel has Edit Clipping Path and Edit Contents at its top, which select its clipping path or its clipped art for the selection tools (public doc cited in target-app-parity.md). Broader G1 estimates unchanged. - **Done:** the Properties panel has the additional contextual controls of the public Properties panel overview: Blend Options in Quick Actions for one blend with the Blend tool, Merge Live Paint for a Live Paint group selected with more paths to merge (Live Paint Make and Merge refuse type, images and other objects that aren't paths, which used to vanish among the group's sources), the Width Profile list in Appearance with the Width tool or a variable-width stroke, an applied effect's Delete icon beside fx (with several effects it opens the Appearance panel), and Corner and Corner Radius for corners selected with Direct Selection (public doc cited in target-app-parity.md). Broader G1 estimates unchanged. -- **Done (#2691):** a selected Grid Repeat ([public page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html)) shows a handle below the grid, one right of it and one past its bottom-right corner: dragging them adds or removes rows, columns or both (1 to 500). A slider between the first two columns and one between the first two rows set the horizontal and vertical spacing, staying halfway across the gap under the pointer. Each drag is one undo step through `object.repeat.options` and Escape cancels it; the controls hide with the edges or the bounding box, and bounding-box handles keep priority where they meet. Radial Repeat handles remain. Estimates unchanged. +- **Done (#2691):** a selected Grid Repeat ([public page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html)) shows a handle below the grid, one right of it and one past its bottom-right corner: dragging them adds or removes rows, columns or both (1 to 500). A slider between the first two columns and one between the first two rows set the horizontal and vertical spacing, staying halfway across the gap under the pointer. Each drag is one undo step through `object.repeat.options` and Escape cancels it; the controls hide with the edges or the bounding box, and bounding-box handles keep priority where they meet. A selected Radial Repeat ([public page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/create-radial-repeats.html)) shows a handle below it, dragged down for more instances and up for fewer (16 px each, 1 to 1,000), and a handle on its circle between the first two instances, dragged outward or inward for a larger or smaller radius (0 or more); the same undo, Escape, visibility and priority rules apply. The radial splitter remains. Estimates unchanged. - **Done (#2651):** Object › Repeat › Options… for a Grid Repeat has a Preview checkbox ([public page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html)): while it is on the repeat on the canvas follows the fields, Cancel puts the original back without a history step and OK keeps the previewed values as one undo step. Radial and Mirror Repeat Options have none, as their public pages list none. Estimate unchanged. - **Done (#2877):** a selected Mirror Repeat shows its axis: drag the line or the center handle to move it, an end handle to rotate it (Shift: 45°); each drag is one undo step and Escape cancels it. Bounding-box handles take priority over the axis line; the center and end handles keep their actions. Broader G1 estimates unchanged. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..3222960ef2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -641,6 +641,7 @@ since 2026-10-01. - **Graph legend swatches have their series' stroke:** a default legend swatch of a stacked column, stacked bar, area or pie series has the thin white stroke of the series' marks (VectorCraft's own rule), beside the plot or across the top, and a stroke kept on the series is on the swatch too. Each series' group then paints with one stroke, so a stacked column or area graph the graph tools draw is saved to `.ai` with its data and settings and opens again as a live graph; a stacked bar graph is still written as its art, as the reader has no type for it. Evidence: `cmd::graph::tests::a_legend_swatch_has_the_stroke_of_its_series_marks`, `cmd::graph::tests::a_drawn_stacked_column_graph_saved_as_ai_opens_as_a_graph_that_takes_new_data`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`. Scores unchanged. - **Graph section in the Properties panel:** with one graph selected, or series of one graph picked with Group Selection, the Properties panel shows a Graph section. Its Graph Type… button opens the dialog of Object › Graph › Type… ([Format pie graphs](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/format-pie-graphs.html)). Its Graph Data… button opens the dialog of Object › Graph › Data…; this button is VectorCraft's own. Column… shows when every series it would change draws columns or bars, and Marker… when every one draws lines, scatter points or radar lines; this is VectorCraft's own rule. Regression tests in `crates/ui-egui/src/panels/properties/tests.rs`. Scores unchanged. - **Selected Grid Repeat handles (#2691):** `tools/src/repeat_grid.rs` tests place the handles outside the grid at zoom 0.5, 1 and 4, preview rows, columns and spacing, leave no undo step for a drag that ends where it began, and give bounding-box handles priority; a headless canvas regression drags the row handle two tiles down in a zoomed view (3 → 5 rows, the source unchanged, one Undo back) and the column-spacing slider. Scores and hours unchanged. +- **Selected Radial Repeat handles:** `tools/src/repeat_radial.rs` tests place the instances handle below the repeat and the radius handle on its circle between the first two instances at zoom 0.02, 1 and 4 (opposite a single instance, at the center with a radius of 0), step the count by whole instances within 1 to 1,000, set the radius from the outward part of a drag and stop it at 0, hide the handles for a locked, hidden or invalid repeat, leave no undo step for a drag that ends where it began, and give bounding-box handles priority; a headless canvas regression in a zoomed view turned 30° drags the instances handle (6 → 8 instances, the source unchanged, one Undo back) and the radius handle (60 → 80 pt), and Escape puts a radius drag back. Scores and hours unchanged. - **Selected Mirror Repeat handles:** a headless canvas regression creates the default mirror repeat and drags its Top bounding-box handle where the axis crosses it; the repeat grows vertically while its width stays fixed. Existing mirror-axis checks cover center movement and end-handle hit priority. The focused UI mirror tests pass. Scores and hours unchanged. - **Transform effect options (#885):** Effect › Distort & Transform › Transform… has visible Transform Objects, Transform Patterns and Scale Strokes & Effects checkboxes (`distort.transform` params `objects`, `patterns`, `strokes`; files without them draw as before). With Transform Objects off the geometry stays and makes no copies; Scale Strokes & Effects scales stroke weights, dashes and the fills' and strokes' effect distances by the mean scale, and Transform Patterns moves pattern tiles, each copy `k` by the transformation `k` times. Such objects draw, export and expand through the same per-copy art, so the canvas and Expand Appearance agree (engine `tests_transformfx`, effects `tests_transformfx`, the dialog test). A Transform effect in a fill's or stroke's own effects applies the same options to that fill or stroke: its weight and dashes and its pattern follow the transformation, and with copies each copy is an object of its own; the canvas, export, Expand Appearance and Use Preview Bounds use the same art (effects `tests_transformfx`). The effects listed after it in that fill's or stroke's list keep their own distances and apply to the transformed art and to each copy, as an object's later effects do after the object's Transform effect: a Drop Shadow after it keeps its offset, an Offset Path after it offsets by its own distance, and an SVG filter after it keeps its scale and the origin of its user space. With Transform Objects off, the effects before it keep their distances too. Before, Scale Strokes & Effects scaled a fill's or stroke's later effects by the mean scale, so existing documents with such effects draw differently. Effects apply in the order they are listed ([Appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)); how the two options treat the effects after a fill's or stroke's own Transform effect is VectorCraft's own rule, following that order (effects `tests::rasterfollow::a_fills_own_transform_leaves_the_shadow_after_it`, `tests::rasterfollow::a_fills_own_transform_leaves_the_offset_after_it`, `tests::rasterfollow::a_fills_own_transform_leaves_the_svg_filter_after_it`, `tests::transformfx::a_fills_own_transform_with_scale_strokes_and_effects_leaves_its_later_effects`; engine `plugins::a_transform_after_a_painted_fill_effect_leaves_the_later_shadow_on_every_paint`). Public reference: [Scale objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html), [How to apply effects](https://helpx.adobe.com/illustrator/using/effects.html), [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html). Scores and hours unchanged. - **Raster effects before a Transform effect:** effects apply in the order they are listed ([Appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)). A Drop Shadow, glow, blur, Feather or pixel filter listed before a Transform effect in the same list (an object's effects, or a fill's or stroke's own) now follows that Transform effect: its sizes scale by the mean scale, and a Drop Shadow's offset turns, reflects and scales with the art. VectorCraft applies this rule with Scale Strokes & Effects on or off. Before, such an effect was drawn at its own distances around the transformed art. The canvas, export, Expand Appearance, Object › Expand, Outline Stroke and the 3D effects use the same values (effects `tests::rasterfollow`; render `a_transform_after_a_drop_shadow_scales_the_shadow_with_the_art`; engine `objexpand::a_shadow_before_a_transform_expands_as_the_canvas_draws_it`, `outlinestroke::a_shadow_before_a_transform_outlines_as_the_canvas_draws_it`). Not yet: a Transform effect that makes copies or moves at random leaves the raster effects before it as they are. The light direction of Underpainting, Rough Pastels, Conté Crayon, Bas Relief, Plaster and Texturizer and the stroke direction of Sprayed Strokes and Graphic Pen now turn and reflect with such a Transform effect, each set to the nearest of its menu's choices (at a tie, the one clockwise of it; VectorCraft's own rule), and Color Halftone's four screen angles turn and reflect with the art ([Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html); effects `tests::rasterfollow::bas_relief_light_follows_rotation_and_reflection` and the tests after it). Not yet: filters whose strokes or patterns run along fixed page axes without a direction setting (Angled Strokes, Crosshatch, Mezzotint's lines, Halftone Pattern's lines, Grain's horizontal and vertical types, De-Interlace) keep those axes, and an uneven scale or a shear sets a direction from the one vector it maps, not a skewed pattern. Scores and hours unchanged. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 8e06948b33..8c104ff5bc 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -395,7 +395,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Command search: Up and Down move through the results, Enter runs the highlighted one | done | #1798 (#1757) | | Learn panel: Window › Learn and Explore tutorials on the app bar open it; For you holds a Quick skill guide card, Skills lists VectorCraft's own skills with progress rings that fill and counts of tutorials finished, a tutorial shows its numbered steps with a check box each that marks the step done once its sample is open, a finished tutorial has a check mark, Back goes up a level; a tool's name in a step is a link that marks the tool where the toolbars show it (its button, its group's flyout, a torn-off strip, a toolbar made with New Toolbar or the All Tools drawer) without choosing it; View more opens the tutorial's practice sample as a new untitled document, Finish tutorial then marks it finished with all its steps, and Next Up shows the next tutorial in the same skill; Reset progress clears the progress (no video) | done | [the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html); `learn.list`, `learn.tab`, `learn.skills`, `learn.skill`, `learn.show`, `learn.back`, `learn.locateTool`, `learn.openSample`, `learn.markStep`, `learn.finish`, `learn.next`, `learn.resetProgress`; the mark's look and 3-second lifetime, marking steps by hand, keeping the progress in the preferences and Reset progress are VectorCraft's own rules; `panels::learn::tests`, `toolbar::tests` | | Pathfinder panel: a group selected alone counts its nested shapes, so an expanded stroked object keeps the Shape Modes enabled | done | #1642 (#1635) | -| Selected Grid Repeat shows row, column and corner handles and spacing sliders; bounding-box handles take priority where they meet | done | #2691, `tools/src/repeat_grid.rs`; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html); drags preview and commit `object.repeat.options` as one undo step, Escape cancels; Radial Repeat has no handles yet | +| Selected Grid Repeat shows row, column and corner handles and spacing sliders; bounding-box handles take priority where they meet | done | #2691, `tools/src/repeat_grid.rs`; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html); drags preview and commit `object.repeat.options` as one undo step, Escape cancels; a selected Radial Repeat shows an instances handle below it (16 px of drag per instance, 1 to 1,000) and a radius handle on its circle the same way (`tools/src/repeat_radial.rs`; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/create-radial-repeats.html)); its splitter has no handle yet | | Grid Repeat Options (Object › Repeat › Options…) has a Preview checkbox: the repeat on the canvas follows the fields while the dialog is open, Cancel puts the original back without a history step, OK keeps the previewed values as one undo step | done | #2651; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html) lists the Preview option for the grid options only, so Radial and Mirror Repeat Options have none; `dialogs/command.rs` tests | | Type on a Path Options (Type › Type on a Path › Type on a Path Options…, or a double-click on the Type on a Path tools) has a Preview checkbox, off when it opens: the selected type on a path follows Effect, Flip, Align to Path and Spacing while the dialog is open, Cancel puts it back without a history step, OK keeps the previewed values as one undo step | done | #5360; the [public page](https://helpx.adobe.com/illustrator/using/creating-type-path.html) lists the dialog's options, and public tutorials of the dialog show its Preview checkbox; `tests/pathtype.rs` | | Graph Type (Object › Graph › Type…, or a double-click on a graph tool) is a dialog of its own: a menu at the top shows Graph Options or the page of an axis; Graph Options has a button per graph type, Value Axis with Separate Scales, the Style checkboxes (Add Drop Shadow, Add Legend Across Top, First Row in Front, First Column in Front) and the options of the type picked (Column or Bar Width and Cluster Width; Mark Data Points, Connect Data Points, Edge-to-Edge Lines and Draw Filled Lines; a pie graph's Legend, Position and Sort); the Value Axis page (Left Axis and Right Axis with the value axis on both sides) has Tick Values with Override Calculated Values, Tick Marks and Add Labels, and the Category Axis page has Tick Marks with Draw Tick Marks Between Labels; with series picked by Group Selection the type and value axis go to those series | done | Public pages: [graph types](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/change-graph-types.html), [value axes](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/change-graph-value-axes.html), [columns, bars and lines](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/format-columns-bars-and-lines.html), [pie graphs](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/format-pie-graphs.html), [separate scales](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/assign-different-scales-to-value-axes.html), [combined types](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/combine-different-graph-types.html). The options dimmed for a type, the pages listed and the Legend checkbox are VectorCraft's own rules. Dialog `graphType`; `dialogs/graph_type.rs` and its tests | From 532d2ea6d775538d08e3a65e8b08b0544c3870f7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 01:04:30 -0800 Subject: [PATCH 08/31] Packaging Tools: Check Fold Lines finds the panels and hinges of a blank and lists what is wrong MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Object › Plug-ins › Packaging Tools › Check Fold Lines, and the Fold Lines panel's Check button, check the fold lines of the selection, or of the document while nothing is selected (`addon.packaging.check`). - Cut lines bound the material: each connected piece that encloses an area is one blank, its largest closed cut line is the outline, and a closed cut line inside it is a hole. A slot drawn as a rectangle across the outline leaves the same material as a notch drawn in it, and an outline drawn as several open cut lines works too. - Creases, partial cuts and perforations divide a blank into panels; the pieces between the same two panels form one hinge. - 15 issue codes, errors and warnings, each naming its lines; cut line ends within a tolerance (0.1 pt, 0.01 to 10) are joined and reported as a gap. With `select`, the lines the issues name are selected. - The panel lists the issues in the interface language, with a summary line; clicking an issue or its Select button selects its lines. The list is kept until the document changes. `vectorcraft_pathops::adjacency` maps paths as live_paint does and keeps, for each edge, every input it lies on and the faces on both sides; the blank model is `vectorcraft_three_d::fold::blanks`. The engine now depends on vectorcraft-three-d directly. Docs: docs/mcp.md (Check Fold Lines), crates/pathops/README.md, ROADMAP. --- Cargo.lock | 2 + ROADMAP.md | 1 + crates/engine/Cargo.toml | 2 + crates/engine/src/cmd/addons/packaging.rs | 8 +- .../engine/src/cmd/addons/packaging/check.rs | 176 +++ .../src/cmd/addons/packaging/check/tests.rs | 165 +++ .../engine/src/cmd/addons/packaging/roles.rs | 4 +- crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/tests/command_sweep.rs | 3 + crates/pathops/README.md | 8 + crates/pathops/src/lib.rs | 4 +- crates/pathops/src/planar.rs | 2 + crates/pathops/src/planar/adjacency.rs | 169 +++ crates/pathops/src/planar/adjacency/tests.rs | 200 +++ crates/pathops/src/planar/map.rs | 16 +- crates/three-d/Cargo.toml | 3 + crates/three-d/src/fold.rs | 1237 +++++++++++++++++ crates/three-d/src/fold/tests.rs | 740 ++++++++++ crates/three-d/src/lib.rs | 1 + crates/ui-egui/src/addons/packaging.rs | 144 +- crates/ui-egui/src/addons/packaging/tests.rs | 133 +- crates/ui-egui/src/i18n/bg.tsv | 19 + crates/ui-egui/src/i18n/bs.tsv | 19 + crates/ui-egui/src/i18n/ca.tsv | 19 + crates/ui-egui/src/i18n/cs.tsv | 19 + crates/ui-egui/src/i18n/da.tsv | 19 + crates/ui-egui/src/i18n/de.tsv | 19 + crates/ui-egui/src/i18n/el.tsv | 19 + crates/ui-egui/src/i18n/es.tsv | 19 + crates/ui-egui/src/i18n/fi.tsv | 19 + crates/ui-egui/src/i18n/fr.tsv | 19 + crates/ui-egui/src/i18n/gu.tsv | 19 + crates/ui-egui/src/i18n/hi.tsv | 19 + crates/ui-egui/src/i18n/hu.tsv | 19 + crates/ui-egui/src/i18n/id.tsv | 19 + crates/ui-egui/src/i18n/it.tsv | 19 + crates/ui-egui/src/i18n/ja.tsv | 19 + crates/ui-egui/src/i18n/ka.tsv | 19 + crates/ui-egui/src/i18n/ko.tsv | 19 + crates/ui-egui/src/i18n/nl.tsv | 19 + crates/ui-egui/src/i18n/pl.tsv | 19 + crates/ui-egui/src/i18n/pt-br.tsv | 19 + crates/ui-egui/src/i18n/ru.tsv | 19 + crates/ui-egui/src/i18n/sv.tsv | 19 + crates/ui-egui/src/i18n/tr.tsv | 19 + crates/ui-egui/src/i18n/uk.tsv | 19 + crates/ui-egui/src/i18n/vi.tsv | 19 + crates/ui-egui/src/i18n/zh-hans.tsv | 19 + crates/ui-egui/src/i18n/zh-hant.tsv | 19 + crates/ui-egui/src/menus/invoke.rs | 5 + docs/mcp.md | 56 +- 51 files changed, 3593 insertions(+), 19 deletions(-) create mode 100644 crates/engine/src/cmd/addons/packaging/check.rs create mode 100644 crates/engine/src/cmd/addons/packaging/check/tests.rs create mode 100644 crates/pathops/src/planar/adjacency.rs create mode 100644 crates/pathops/src/planar/adjacency/tests.rs create mode 100644 crates/three-d/src/fold.rs create mode 100644 crates/three-d/src/fold/tests.rs diff --git a/Cargo.lock b/Cargo.lock index 81946466b5..3b31ba9996 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6709,6 +6709,7 @@ dependencies = [ "vectorcraft-svg", "vectorcraft-testkit", "vectorcraft-text", + "vectorcraft-three-d", "vectorcraft-tools", "vectorcraft-trace", "wat", @@ -7017,6 +7018,7 @@ dependencies = [ name = "vectorcraft-three-d" version = "0.24.1" dependencies = [ + "proptest", "vectorcraft-geom 0.24.1", "vectorcraft-pathops 0.24.1", ] diff --git a/ROADMAP.md b/ROADMAP.md index 6471505555..f658cccb58 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -135,6 +135,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged. - 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged. - 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged. +- 2026-11-16: Check Fold Lines in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Check button): the fold lines of the selection or the document are split into blanks, panels and hinges (cut lines bound the material, and creases, partial cuts and perforations divide it into panels), and 15 kinds of issue are listed, errors and warnings, each naming its lines: cut lines that enclose nothing or end loose, gaps closed within a tolerance, a cut on top of a crease, duplicate lines, creases that end inside a panel, divide nothing, lie outside the blank or are not straight, gaps too narrow to map, fold lines in a hole, panels joined by no crease, and fold lines on a non-printing layer. The panel lists the issues in the interface language; clicking one selects its lines (`addon.packaging.check`). A VectorCraft addition: headline numbers unchanged. - 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). - 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index b46678804b..099f46c028 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -29,6 +29,8 @@ vectorcraft-tools = { workspace = true } vectorcraft-text = { workspace = true } vectorcraft-render = { workspace = true } vectorcraft-pathops = { workspace = true } +# The panels and hinges of a packaging blank (Packaging Tools' Check Fold Lines). +vectorcraft-three-d = { workspace = true } vectorcraft-brush = { workspace = true } vectorcraft-trace = { workspace = true } vectorcraft-svg = { workspace = true } diff --git a/crates/engine/src/cmd/addons/packaging.rs b/crates/engine/src/cmd/addons/packaging.rs index 7e262c3869..6099386b98 100644 --- a/crates/engine/src/cmd/addons/packaging.rs +++ b/crates/engine/src/cmd/addons/packaging.rs @@ -1,9 +1,11 @@ //! Packaging Tools (`addon.packaging.*`), a built-in add-on for the dielines of boxes and other //! folded packaging. A path is a fold line when its top stroke is painted with the swatch of a line //! role: Cut, Crease, Partial Cut or Perforation ([`roles`]). The document's role table maps each -//! role to its swatch, so every format that keeps the stroke's swatch keeps the role. Its submenu +//! role to its swatch, so every format that keeps the stroke's swatch keeps the role. Check Fold +//! Lines ([`check`]) finds the panels and hinges the lines make and what is wrong with them. Its submenu //! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's. +mod check; mod roles; pub(crate) use roles::{role_swatch_edited, role_swatches_merged}; @@ -11,7 +13,9 @@ pub(crate) use roles::{role_swatch_edited, role_swatches_merged}; use super::super::CommandSpec; pub fn specs() -> Vec { - roles::specs() + let mut v = roles::specs(); + v.extend(check::specs()); + v } #[cfg(test)] diff --git a/crates/engine/src/cmd/addons/packaging/check.rs b/crates/engine/src/cmd/addons/packaging/check.rs new file mode 100644 index 0000000000..59f195d4df --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/check.rs @@ -0,0 +1,176 @@ +//! Check Fold Lines (`addon.packaging.check`): the blanks the fold lines make, their panels and +//! hinges, and what is wrong with the lines, found by [`vectorcraft_three_d::fold::blanks`]. + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_geom::PathData; +use vectorcraft_three_d::fold::{FoldLine, IssueCode, LineKind, MAX_SEGMENTS, blanks}; + +use super::super::super::pathops::length_given; +use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or}; +use super::roles::{Role, RoleTable, can_carry, role_targets}; +use crate::{Result, Session}; + +const CHECK: &str = "addon.packaging.check"; + +/// How far apart the ends of two lines may be and still be joined, in points. +const TOLERANCE: (f64, f64, f64) = (0.01, 0.1, 10.0); + +pub fn specs() -> Vec { + vec![cmd!( + "addon.packaging.check", + "Check Fold Lines", + ["Object", "Plug-ins", "Packaging Tools"], + None, + "{ids?: [id…] (default: the selection), select?: bool (false), tolerance?: pt 0.01..10 (0.1)} check the fold lines (addon.packaging.roles) among the objects (through groups and clip groups), or, while nothing is selected and ids is left out, every fold line of the document that is shown. Cut lines bound the blanks: each connected piece of them that encloses material is one blank, its outline is its largest closed cut line, and a closed cut line inside it is a hole, so a slot drawn as a rectangle across the outline leaves the same material as a notch drawn in it; open cut lines that meet end to end count as one closed cut line. Crease, Partial Cut and Perforation lines divide a blank into panels; the pieces of them between two panels are that pair's hinge. A cut line end that comes within tolerance of another cut line is joined to it. Issues, in this order: noCut, open, looseEnd (errors), gap (a warning: the gap is closed), tooComplex (an error: more than 65,536 segments or 256 panels in a blank), cutOverCrease (an error), duplicate, danglingCrease, noSplit, outside, notStraight (it folds along the line through its longest piece), sliver, ambiguous, loosePanel (joined to the largest panel by no chain of hinges), nonPrinting (warnings). With select, the objects the issues name become the selection, unless no issue names one. Changes nothing in the document → {ok (no error), blanks, panels, hinges, holes, issues: [{severity: error|warning, code, message (English), ids, at?: [x, y]}], scope: ids|selection|document}", + has_doc, + check + )] +} + +/// The English message for an issue (the Fold Lines panel shows it in the interface language). +fn message(code: IssueCode, scope: &str) -> &'static str { + match code { + IssueCode::NoCut if scope == "document" => "No cut lines are in the document.", + IssueCode::NoCut => "No cut lines are in the selection.", + IssueCode::Open => "The cut lines do not enclose an area.", + IssueCode::LooseEnd => "A cut line ends without meeting another cut line.", + IssueCode::Gap => "A gap between cut lines was closed.", + IssueCode::TooComplex => "The fold lines are too complex to check.", + IssueCode::CutOverCrease => "A cut line and a crease lie on top of each other.", + IssueCode::Duplicate => "Two lines of the same role lie on top of each other.", + IssueCode::DanglingCrease => "A crease ends inside a panel.", + IssueCode::NoSplit => "A crease does not divide two panels.", + IssueCode::Outside => "A crease lies outside the cut outline.", + IssueCode::NotStraight => "A crease that is not straight is folded along one straight line.", + IssueCode::Sliver => "A gap between cut lines is too narrow to tell apart.", + IssueCode::Ambiguous => "A cut-out area holds other fold lines.", + IssueCode::LoosePanel => "A panel is not joined to the rest by a crease.", + IssueCode::NonPrinting => "A fold line is on a non-printing layer.", + } +} + +/// Every object of the document that can carry a role and is shown: on a shown layer, in shown +/// groups, and shown itself. +fn shown_targets(d: &Document) -> Vec { + fn walk(n: &Node, out: &mut Vec) { + if !n.visible { + return; + } + match &n.kind { + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, out)), + _ if can_carry(n) => out.push(n.id), + _ => {} + } + } + let mut out = vec![]; + d.layers.iter().for_each(|l| walk(l, &mut out)); + out +} + +/// The path of object `n` in document coordinates: a path's own, or a compound path's members'. +fn path_of(n: &Node) -> Option { + match &n.kind { + NodeKind::Path { path, .. } => Some(path.clone()), + NodeKind::Compound { children, .. } => Some(PathData::new( + children + .iter() + .filter_map(|c| match &c.kind { + NodeKind::Path { path, .. } => Some(path.subpaths.iter().cloned()), + _ => None, + }) + .flatten() + .collect(), + )), + _ => None, + } +} + +/// Whether object `id` is on a layer, or a sublayer, that does not print. +fn on_non_printing_layer(d: &Document, id: NodeId) -> bool { + d.ancestry(id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(|n| matches!(n.kind, NodeKind::Layer { printable: false, .. })) +} + +fn kind(role: Role) -> LineKind { + match role { + Role::Cut => LineKind::Cut, + Role::Crease => LineKind::Crease, + Role::PartialCut => LineKind::PartialCut, + Role::Perforation => LineKind::Perforation, + } +} + +fn check(s: &mut Session, p: &Value) -> Result { + let select = switch_or(p, "select", false, CHECK)?; + let tolerance = match length_given(p, "tolerance", CHECK)? { + None => TOLERANCE.1, + Some(t) if (TOLERANCE.0..=TOLERANCE.2).contains(&t) => t, + Some(_) => return Err(bad(CHECK, format!("`tolerance` must be from {} to {} pt", TOLERANCE.0, TOLERANCE.2))), + }; + let given = p.get("ids").is_some_and(|v| !v.is_null()); + let roots = checked_ids_or_selection(s, p, CHECK)?; + let d = &s.doc()?.doc; + let (scope, targets) = match (given, roots.is_empty()) { + (true, _) => ("ids", role_targets(d, &roots, false).0), + (false, false) => ("selection", role_targets(d, &roots, false).0), + (false, true) => ("document", shown_targets(d)), + }; + let table = RoleTable::of(d); + let mut lines = vec![]; + let mut non_printing = vec![]; + let mut segments = 0usize; + for id in targets { + // Once the lines have more segments than the check takes, it reports them as too complex: + // the rest are not copied. + if segments > MAX_SEGMENTS { + break; + } + let Some(n) = d.node(id) else { continue }; + let (Some(role), Some(path)) = (table.role_of(n), path_of(n)) else { continue }; + if on_non_printing_layer(d, id) { + non_printing.push(id.0); + } + segments = segments.saturating_add(path.subpaths.iter().map(|sp| sp.segment_count()).sum()); + lines.push(FoldLine { path, kind: kind(role), angle: None, key: id.0 }); + } + let (found, mut issues) = blanks(&lines, tolerance); + if !non_printing.is_empty() { + issues.push(vectorcraft_three_d::fold::Issue { code: IssueCode::NonPrinting, keys: non_printing, at: None }); + } + let ok = !issues.iter().any(|i| i.code.is_error()); + let rows: Vec = issues + .iter() + .map(|i| { + let mut row = json!({ + "severity": if i.code.is_error() { "error" } else { "warning" }, + "code": i.code.id(), + "message": message(i.code, scope), + "ids": i.keys, + }); + if let (Some(at), Some(o)) = (i.at, row.as_object_mut()) { + o.insert("at".into(), json!([at.x, at.y])); + } + row + }) + .collect(); + if select { + let mut ids: Vec = issues.iter().flat_map(|i| i.keys.iter().map(|k| NodeId(*k))).filter(|id| d.node(*id).is_some()).collect(); + ids.sort_unstable_by_key(|id| id.0); + ids.dedup(); + if !ids.is_empty() { + s.select(|_, sel| sel.set(ids.iter().copied()))?; + } + } + Ok(json!({ + "ok": ok, + "blanks": found.len(), + "panels": found.iter().map(|b| b.panels.len()).sum::(), + "hinges": found.iter().map(|b| b.hinges.len()).sum::(), + "holes": found.iter().map(|b| b.holes.len()).sum::(), + "issues": rows, + "scope": scope, + })) +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/addons/packaging/check/tests.rs b/crates/engine/src/cmd/addons/packaging/check/tests.rs new file mode 100644 index 0000000000..427656fc29 --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/check/tests.rs @@ -0,0 +1,165 @@ +//! Tests for Check Fold Lines: the blanks, panels, hinges and issues of fold lines drawn in a +//! document. + +use serde_json::{Value, json}; + +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap(); + s +} + +fn path(s: &mut Session, d: &str) -> u64 { + s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap() +} + +fn role(s: &mut Session, role: &str, ids: &[u64]) { + s.execute("addon.packaging.setRole", &json!({ "role": role, "ids": ids })).unwrap(); +} + +fn check(s: &mut Session, p: Value) -> Value { + s.execute("addon.packaging.check", &p).unwrap() +} + +fn codes(r: &Value) -> Vec<&str> { + r["issues"].as_array().unwrap().iter().map(|i| i["code"].as_str().unwrap()).collect() +} + +/// A tray blank: a 100 pt base with a 40 pt wall on each side, its outline a cut line and the +/// base's four sides creases → (outline, creases). +fn tray(s: &mut Session) -> (u64, Vec) { + let outline = path(s, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z"); + let creases = vec![path(s, "M140 140 L240 140"), path(s, "M240 140 L240 240"), path(s, "M240 240 L140 240"), path(s, "M140 240 L140 140")]; + role(s, "cut", &[outline]); + role(s, "crease", &creases); + s.execute("select.none", &json!({})).unwrap(); + (outline, creases) +} + +#[test] +fn a_tray_checks_clean_with_five_panels_and_four_hinges() { + let mut s = session(); + tray(&mut s); + let steps = s.doc().unwrap().history.undo.len(); + let r = check(&mut s, json!({})); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!((r["blanks"].as_u64(), r["panels"].as_u64(), r["hinges"].as_u64(), r["holes"].as_u64()), (Some(1), Some(5), Some(4), Some(0)), "{r}"); + assert!(codes(&r).is_empty(), "{r}"); + assert_eq!(r["scope"], "document"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "a check records no undo step"); +} + +#[test] +fn the_selection_or_ids_limit_the_check_to_their_lines() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + s.execute("select.set", &json!({ "ids": [creases[0]] })).unwrap(); + let r = check(&mut s, json!({})); + assert_eq!((r["scope"].as_str(), r["ok"].as_bool()), (Some("selection"), Some(false))); + assert_eq!(codes(&r), ["noCut"]); + assert_eq!(r["issues"][0]["message"], "No cut lines are in the selection."); + let r = check(&mut s, json!({ "ids": [outline] })); + assert_eq!((r["scope"].as_str(), r["ok"].as_bool(), r["panels"].as_u64()), (Some("ids"), Some(true), Some(1)), "{r}"); + // No fold lines at all in the document. + let mut s = session(); + let r = check(&mut s, json!({})); + assert_eq!(codes(&r), ["noCut"]); + assert_eq!(r["issues"][0]["message"], "No cut lines are in the document."); +} + +#[test] +fn issues_name_their_lines_and_select_selects_them() { + let mut s = session(); + let (_, creases) = tray(&mut s); + // A slit from the outline that stops in the middle of the base. + let slit = path(&mut s, "M190 100 L190 190"); + role(&mut s, "cut", &[slit]); + s.execute("select.none", &json!({})).unwrap(); + let r = check(&mut s, json!({})); + assert_eq!(r["ok"], false); + let loose = r["issues"].as_array().unwrap().iter().find(|i| i["code"] == "looseEnd").cloned().unwrap(); + assert_eq!((loose["severity"].as_str(), loose["ids"].clone()), (Some("error"), json!([slit])), "{r}"); + assert_eq!(loose["at"], json!([190.0, 190.0])); + assert!(s.doc().unwrap().selection.objects.is_empty(), "without select, the selection stays"); + let r = check(&mut s, json!({ "select": true })); + let named: std::collections::BTreeSet = + r["issues"].as_array().unwrap().iter().flat_map(|i| i["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap())).collect(); + let selected: std::collections::BTreeSet = s.doc().unwrap().selection.objects.iter().map(|id| id.0).collect(); + assert!(selected.contains(&slit) && selected == named, "{selected:?} {named:?}"); + assert!(!selected.contains(&creases[1])); +} + +#[test] +fn a_clean_check_with_select_leaves_the_selection_alone() { + let mut s = session(); + let (outline, _) = tray(&mut s); + s.execute("select.set", &json!({ "ids": [outline] })).unwrap(); + let r = check(&mut s, json!({ "ids": [outline], "select": true })); + assert!(codes(&r).is_empty(), "{r}"); + assert_eq!(s.doc().unwrap().selection.objects.iter().map(|id| id.0).collect::>(), [outline]); +} + +#[test] +fn tolerance_is_checked_and_joins_gaps_up_to_it() { + let mut s = session(); + tray(&mut s); + for bad in [json!(0.005), json!(10.5), json!("x"), json!(true)] { + let e = s.execute("addon.packaging.check", &json!({ "tolerance": bad })).unwrap_err().to_string(); + assert!(e.contains("tolerance"), "{e}"); + } + let e = s.execute("addon.packaging.check", &json!({ "select": 1 })).unwrap_err().to_string(); + assert!(e.contains("select"), "{e}"); + for edge in [json!(0.01), json!(10), json!("2 mm")] { + assert_eq!(check(&mut s, json!({ "tolerance": edge }))["ok"], true); + } + // A slit that stops 0.5 pt short of a crease: a gap at a tolerance of 1 pt, a loose end at 0.1 pt. + let mut s = session(); + tray(&mut s); + let slit = path(&mut s, "M190 100 L190 139.5"); + role(&mut s, "cut", &[slit]); + s.execute("select.none", &json!({})).unwrap(); + assert!(codes(&check(&mut s, json!({ "tolerance": 0.1 }))).contains(&"looseEnd")); + let near = check(&mut s, json!({ "tolerance": 1 })); + assert!(!codes(&near).contains(&"looseEnd"), "{near}"); +} + +#[test] +fn hidden_lines_are_left_out_and_lines_on_a_non_printing_layer_are_noted() { + let mut s = session(); + let (_, creases) = tray(&mut s); + // A hidden crease is not checked while nothing is selected: the tray has three hinges and a + // panel joined by none. + s.execute("layer.setProps", &json!({ "ids": [creases[0]], "visible": false })).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let r = check(&mut s, json!({})); + assert_eq!((r["panels"].as_u64(), r["hinges"].as_u64()), (Some(4), Some(3)), "{r}"); + // A cut line on a layer that does not print. + let mut s = session(); + s.execute("layer.new", &json!({ "printable": false })).unwrap(); + let (outline, _) = tray(&mut s); + let r = check(&mut s, json!({})); + assert_eq!(r["ok"], true, "a warning only"); + let note = r["issues"].as_array().unwrap().iter().find(|i| i["code"] == "nonPrinting").cloned().unwrap(); + assert_eq!(note["severity"], "warning"); + assert!(note["ids"].as_array().unwrap().contains(&json!(outline)), "{note}"); + assert_eq!(note["message"], "A fold line is on a non-printing layer."); +} + +#[test] +fn a_compound_path_and_a_grouped_line_are_checked() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + // A window: a closed cut line in the base, made a compound path with nothing else. + let window = path(&mut s, "M170 170 L210 170 L210 210 L170 210 Z"); + s.execute("select.set", &json!({ "ids": [window] })).unwrap(); + let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64(); + let window = compound.unwrap_or(window); + role(&mut s, "cut", &[window]); + s.execute("select.set", &json!({ "ids": [outline, creases[0], creases[1], creases[2], creases[3], window] })).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let r = check(&mut s, json!({})); + assert_eq!(r["scope"], "selection"); + assert_eq!((r["ok"].as_bool(), r["panels"].as_u64(), r["holes"].as_u64()), (Some(true), Some(5), Some(1)), "{r}"); +} diff --git a/crates/engine/src/cmd/addons/packaging/roles.rs b/crates/engine/src/cmd/addons/packaging/roles.rs index 010384c6c2..2b3c7696f3 100644 --- a/crates/engine/src/cmd/addons/packaging/roles.rs +++ b/crates/engine/src/cmd/addons/packaging/roles.rs @@ -186,7 +186,7 @@ fn free_role_name(d: &Document, table: &RoleTable, role: Role) -> String { /// Whether `n` can carry a role: a path (a live shape too) that is neither a clipping path nor a /// guide, or a compound path. -fn can_carry(n: &Node) -> bool { +pub(super) fn can_carry(n: &Node) -> bool { match &n.kind { NodeKind::Path { clipping, guide, .. } => !clipping && !guide, NodeKind::Compound { .. } => true, @@ -199,7 +199,7 @@ fn can_carry(n: &Node) -> bool { /// how many of `roots` and their members can't (text, images, symbol instances and other objects). /// With `editable`, objects that are locked or hidden, are in a locked or hidden group or layer, or /// are on a locked artboard are left out and counted as skipped. -fn role_targets(d: &Document, roots: &[NodeId], editable: bool) -> (Vec, usize) { +pub(super) fn role_targets(d: &Document, roots: &[NodeId], editable: bool) -> (Vec, usize) { fn walk(n: &Node, out: &mut Vec, skipped: &mut usize) { match &n.kind { NodeKind::Group { children, .. } => { diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 75313d4e4c..1338bb5776 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -40,6 +40,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.image.colorMask", "addon.image.removeBackground", "addon.image.removeColorMask", + "addon.packaging.check", "addon.packaging.roles", "addon.packaging.setRole", "addon.packaging.setRoleSwatch", diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index a4c6c1af40..d8c01c6545 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -1011,6 +1011,9 @@ fn structured_junk() { ("addon.packaging.roles", json!({"ids": [-1, 1e300]})), ("addon.packaging.setRoleSwatch", json!({"role": "perforation", "swatch": "[Registration]"})), ("addon.packaging.setRoleSwatch", json!({"role": "cut", "swatch": 5})), + ("addon.packaging.check", json!({"ids": [u64::MAX, -1], "select": "yes", "tolerance": 1e308})), + ("addon.packaging.check", json!({"tolerance": "-5 mm", "select": true})), + ("addon.packaging.check", json!({"ids": [], "tolerance": null})), // Smart Pen add-on. ("addon.pen.append", json!({"id": 2, "x": 1e308, "y": 0, "in": [1e308, -1e308]})), ("addon.pen.append", json!({"id": 2, "subpath": u64::MAX, "x": 0, "y": 0, "segment": "curved"})), diff --git a/crates/pathops/README.md b/crates/pathops/README.md index 08380830b2..2397045a84 100644 --- a/crates/pathops/README.md +++ b/crates/pathops/README.md @@ -61,6 +61,14 @@ Unlike `regions`, which splits the filled areas of closed shapes, `live_paint` t `shape_builder` gives the Shape Builder's regions. With closed paths only, they are the `regions`. Once an open path is among them, they are the `live_paint` faces, so a stroke-only line across a shape splits it and lines can enclose a region of their own. The second list holds the pieces of each path that has no closed subpath, keyed by its index, so the Shape Builder can delete them one by one. The caller closes any open path whose fill should count. Inputs with more than `SHAPE_BUILDER_MAX_SEGMENTS` segments fall back to the filled areas. +```rust +pub struct Adjacency { pub faces: Vec, pub edges: Vec, pub slivers: Vec, pub outlines: Vec } +pub struct MapEdge { pub path: PathData, pub sources: Vec, pub left: Option, pub right: Option, pub piece: usize } +pub fn adjacency(shapes: &[Shape], precision: f64) -> Option; +``` + +`adjacency` maps the paths as `live_paint` does and also reports, for each edge, every input it lies on and the faces on its left and right as it runs along its path (document coordinates, y down). A line drawn on top of another keeps both inputs on the edge, whatever the input order. A piece of line that ends inside a face has that face on both sides. Faces narrower than `precision` are listed as slivers, and `outlines` holds the outer boundary of each connected piece of the paths. It returns `None` for more than `SHAPE_BUILDER_MAX_SEGMENTS` segments, non-finite input or a `precision` that is not a positive number. + ## Offset / stroke ```rust diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index 49b7c051f1..d35050f70c 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -30,8 +30,8 @@ pub use fit::{fit_cubics, fit_cubics_through}; pub use offset::{Cap, Join, MAX_OFFSET_SEGMENT_PAIRS, offset_path, outline_stroke, stroke_region, try_offset_path}; pub use pathfinder::{FaceMerger, PathfinderOp, Region, Shape, merge_regions, pathfinder, pathfinder_with, region_at, regions, regions_within}; pub use planar::{ - BuilderArrangement, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_SEGMENTS, cut_out, encloses_area, find_gaps, has_open_path, interior_point, - live_paint, live_paint_with_gaps, run_around, shape_builder, shape_builder_with_gap, + Adjacency, BuilderArrangement, MapEdge, MapFace, MapOutline, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_SEGMENTS, adjacency, cut_out, + encloses_area, find_gaps, has_open_path, interior_point, live_paint, live_paint_with_gaps, run_around, shape_builder, shape_builder_with_gap, }; pub use trap::{TRAP_HEIGHT_WIDTH_RANGE, TRAP_MAX_WIDTH, TRAP_MIN_WIDTH, trap_band}; diff --git a/crates/pathops/src/planar.rs b/crates/pathops/src/planar.rs index 75234b3943..f702f993ed 100644 --- a/crates/pathops/src/planar.rs +++ b/crates/pathops/src/planar.rs @@ -26,12 +26,14 @@ use vectorcraft_geom::{FillRule, PathData, SubPath}; use crate::boolean::{DEFAULT_PRECISION, Seg, Tidy, eps_for, is_sliver, segs_to_subpath, snap_horizontals, tidy_segments, to_seg}; use crate::pathfinder::{Region, Shape}; +mod adjacency; mod graph; mod index; mod live_paint; mod map; mod shape_builder; +pub use adjacency::{Adjacency, MapEdge, MapFace, MapOutline, adjacency}; pub(crate) use graph::pin_ends; #[cfg(test)] use index::{Crossings, RectIndex, reference_budget, segment_footprint, work_done}; diff --git a/crates/pathops/src/planar/adjacency.rs b/crates/pathops/src/planar/adjacency.rs new file mode 100644 index 0000000000..52357a0d67 --- /dev/null +++ b/crates/pathops/src/planar/adjacency.rs @@ -0,0 +1,169 @@ +//! Which faces of a planar map each edge separates, and every input each edge lies on. +//! +//! [`live_paint`](super::live_paint) gives each edge under its front-most input only, and says +//! nothing about the faces on its sides. [`adjacency`] reads both from the same planar map, so a +//! caller can tell which faces a line divides and which lines lie on top of each other. + +use super::graph::{find, half_segs, twin, unshear}; +use super::index::RectIndex; +use super::map::{Map, map_with}; +use super::*; + +/// A planar map of some paths with each edge's sides and inputs ([`adjacency`]). +#[derive(Clone, Debug, Default)] +pub struct Adjacency { + pub faces: Vec, + pub edges: Vec, + /// Bounded areas left out as slivers: narrower than the precision on average, such as a thin + /// gap between two lines. + pub slivers: Vec, + /// The outer boundary of each connected piece of the paths. + pub outlines: Vec, +} + +/// A bounded face: its outline, then the outer boundaries of the pieces inside it (as holes), and +/// its area without them. +#[derive(Clone, Debug)] +pub struct MapFace { + pub path: PathData, + pub area: f64, + /// The connected piece of the paths whose edges bound it. + pub piece: usize, +} + +/// An edge: a piece of one or more inputs between two places where paths meet. +#[derive(Clone, Debug)] +pub struct MapEdge { + pub path: PathData, + /// Every input it lies on (indices into the inputs, ascending). + pub sources: Vec, + /// The faces on each side of it as it runs along `path`, seen on the page (document + /// coordinates, y down): `left` on the left. `None` outside every bounded face, or in a sliver. + /// A piece of line that ends loose inside a face has that face on both sides. + pub left: Option, + pub right: Option, + pub piece: usize, +} + +/// The outer boundary of a connected piece of the paths. +#[derive(Clone, Debug)] +pub struct MapOutline { + pub path: PathData, + pub piece: usize, +} + +/// The planar map of `shapes`, every path an edge as in [`live_paint`](super::live_paint), with +/// faces refit to `precision` and slivers narrower than it left out. `None` when the paths can't be +/// swept (non-finite, too degenerate, or more than [`SHAPE_BUILDER_MAX_SEGMENTS`] segments), when +/// `precision` is not a positive number, and when no path has two anchors. +pub fn adjacency(shapes: &[Shape], precision: f64) -> Option { + if !(precision.is_finite() && precision > 0.0) { + return None; + } + let segments: usize = shapes.iter().flat_map(|s| &s.path.subpaths).map(SubPath::segment_count).sum(); + if segments > SHAPE_BUILDER_MAX_SEGMENTS { + return None; + } + let m = map_with(shapes, false, precision)?; + Some(read(&m)) +} + +fn read(m: &Map) -> Adjacency { + let path = |cycle: &[usize], closed: bool| { + let segs: Vec = cycle.iter().flat_map(|&h| half_segs(&m.edges, h)).collect(); + segs_to_subpath(&tidy_segments(segs, closed, &m.tidy), closed) + }; + let unsheared = |subpaths: Vec| unshear(PathData::new(subpaths), &m.anchors, m.snap); + + // Connected pieces, by the vertices the edges join, numbered in the order they are first met. + let vertices = m.edges.iter().flat_map(|e| e.ends).max().map_or(0, |v| v + 1); + let mut parent: Vec = (0..vertices).collect(); + for e in &m.edges { + let (a, b) = (find(&mut parent, e.ends[0]), find(&mut parent, e.ends[1])); + if let Some(p) = parent.get_mut(a) { + *p = b; + } + } + let mut number: Vec> = vec![None; vertices]; + let mut pieces = 0; + let mut piece_of_vertex = |v: usize| { + let root = find(&mut parent, v); + match number.get_mut(root) { + Some(Some(n)) => *n, + Some(slot) => { + *slot = Some(pieces); + pieces += 1; + pieces - 1 + } + None => 0, + } + }; + let edge_pieces: Vec = m.edges.iter().map(|e| piece_of_vertex(e.ends[0])).collect(); + let piece_of = |cycle: &[usize]| cycle.first().and_then(|&h| edge_pieces.get(h / 2)).copied().unwrap_or(0); + + // The face on each half-edge's side: a face's own cycle, and the outer boundaries of the + // pieces inside it, bound it. + let mut face_of: Vec> = vec![None; 2 * m.edges.len()]; + let mut faces = Vec::with_capacity(m.faces.len()); + for (i, (cycle, _, area)) in m.faces.iter().enumerate() { + let holes: Vec<&(Vec, BezPath)> = m.face_holes.get(i).into_iter().flatten().filter_map(|&k| m.holes.get(k)).collect(); + for &h in cycle.iter().chain(holes.iter().flat_map(|(c, _)| c)) { + if let Some(f) = face_of.get_mut(h) { + *f = Some(i); + } + } + let mut subpaths: Vec = path(cycle, true).into_iter().collect(); + subpaths.extend(holes.iter().filter_map(|(c, _)| path(c, true))); + // A hole's outer boundary winds the other way: its area is negative. + let area = area + holes.iter().map(|(_, bp)| bp.area()).sum::(); + faces.push(MapFace { path: unsheared(subpaths), area, piece: piece_of(cycle) }); + } + + // A face walk leaves out the edges that end loose (spurs): such an edge lies inside the face + // around its middle, on both sides. + let mut on_cycle = vec![false; 2 * m.edges.len()]; + let cycles = m.faces.iter().map(|f| &f.0).chain(m.holes.iter().map(|h| &h.0)).chain(m.slivers.iter().map(|s| &s.0)); + for &h in cycles.flatten() { + if let Some(c) = on_cycle.get_mut(h) { + *c = true; + } + } + let spur = |e: usize| !on_cycle.get(2 * e).copied().unwrap_or(true) && !on_cycle.get(twin(2 * e)).copied().unwrap_or(true); + // The faces by their bounds, so that each spur tests only the faces whose bounds hold it; + // built only when there is a spur. + let bezpaths: Vec = if (0..m.edges.len()).any(spur) { faces.iter().map(|f| f.path.to_bezpath()).collect() } else { vec![] }; + let face_index = RectIndex::new(bezpaths.iter().enumerate().map(|(i, bp)| (bp.bounding_box(), i)).collect()); + let face_around = |p: Point| { + face_index + .at(p, 0.0) + .copied() + .filter(|&i| bezpaths.get(i).is_some_and(|bp| bp.winding(p) != 0)) + .min_by(|&a, &b| faces.get(a).map_or(f64::INFINITY, |f| f.area).total_cmp(&faces.get(b).map_or(f64::INFINITY, |f| f.area))) + }; + + // A face cycle winds so its face is on the side where the cross product of the half-edge's + // direction and the way to the face is positive: on the page, with y down, that is the right. + let edges = m + .edges + .iter() + .enumerate() + .filter_map(|(e, edge)| { + let sp = path(&[2 * e], false)?; + let path = unsheared(vec![sp]); + let (left, right) = if spur(e) { + let around = path.to_bezpath().segments().next().map(|s| s.eval(0.5)).and_then(face_around); + (around, around) + } else { + (face_of.get(twin(2 * e)).copied().flatten(), face_of.get(2 * e).copied().flatten()) + }; + Some(MapEdge { path, sources: edge.sources.clone(), left, right, piece: edge_pieces.get(e).copied().unwrap_or(0) }) + }) + .collect(); + let slivers = m.slivers.iter().filter_map(|(cycle, _)| path(cycle, true)).map(|sp| unsheared(vec![sp])).collect(); + let outlines = + m.holes.iter().filter_map(|(cycle, _)| Some(MapOutline { path: unsheared(vec![path(cycle, true)?]), piece: piece_of(cycle) })).collect(); + Adjacency { faces, edges, slivers, outlines } +} + +#[cfg(test)] +mod tests; diff --git a/crates/pathops/src/planar/adjacency/tests.rs b/crates/pathops/src/planar/adjacency/tests.rs new file mode 100644 index 0000000000..8677a7e11a --- /dev/null +++ b/crates/pathops/src/planar/adjacency/tests.rs @@ -0,0 +1,200 @@ +use super::*; +use kurbo::{ParamCurveNearest, Vec2}; +use proptest::prelude::*; +use vectorcraft_geom::{FillRule, Rect, shapes}; + +fn line(a: (f64, f64), b: (f64, f64)) -> Shape { + Shape::new(PathData::single(SubPath::polyline(&[Point::new(a.0, a.1), Point::new(b.0, b.1)], false)), FillRule::NonZero, 0) +} + +fn rect(x0: f64, y0: f64, x1: f64, y1: f64) -> Shape { + Shape::new(shapes::rectangle(Rect::new(x0, y0, x1, y1)), FillRule::NonZero, 0) +} + +fn inside(f: &MapFace, p: Point) -> bool { + f.path.to_bezpath().winding(p) != 0 +} + +/// The edges whose middle lies within 0.01 of `p`. +fn edges_at(a: &Adjacency, p: Point) -> Vec<&MapEdge> { + a.edges + .iter() + .filter(|e| { + let bp = e.path.to_bezpath(); + bp.segments().any(|s| { + let n = s.nearest(p, 1e-6); + n.distance_sq < 1e-4 + }) + }) + .collect() +} + +#[test] +fn a_line_across_a_rectangle_divides_two_faces_it_lies_between() { + let a = adjacency(&[rect(0.0, 0.0, 100.0, 50.0), line((40.0, -10.0), (40.0, 60.0))], DEFAULT_PRECISION).unwrap(); + assert_eq!(a.faces.len(), 2, "{:?}", a.faces); + let left_face = a.faces.iter().position(|f| inside(f, Point::new(20.0, 25.0))).unwrap(); + let right_face = a.faces.iter().position(|f| inside(f, Point::new(70.0, 25.0))).unwrap(); + assert_ne!(left_face, right_face); + assert!((a.faces[left_face].area - 2000.0).abs() < 1e-6 && (a.faces[right_face].area - 3000.0).abs() < 1e-6); + let shared = edges_at(&a, Point::new(40.0, 25.0)); + assert_eq!(shared.len(), 1, "{shared:?}"); + let e = shared[0]; + assert_eq!(e.sources, vec![1]); + let mut sides = [e.left.unwrap(), e.right.unwrap()]; + sides.sort_unstable(); + let mut want = [left_face, right_face]; + want.sort_unstable(); + assert_eq!(sides, want); + // The rectangle's own sides have a face on one side only; the line's ends stick out into no face. + let side = edges_at(&a, Point::new(70.0, 0.0)); + assert_eq!(side.len(), 1); + assert_eq!([side[0].left, side[0].right].iter().flatten().count(), 1); + let stub = edges_at(&a, Point::new(40.0, -5.0)); + assert_eq!((stub[0].left, stub[0].right), (None, None)); + assert!(a.faces.iter().all(|f| f.piece == 0) && a.edges.iter().all(|e| e.piece == 0)); +} + +#[test] +fn a_line_that_ends_inside_a_face_has_that_face_on_both_sides() { + let a = adjacency(&[rect(0.0, 0.0, 100.0, 50.0), line((50.0, 0.0), (50.0, 30.0)), line((20.0, 10.0), (30.0, 20.0))], DEFAULT_PRECISION).unwrap(); + assert_eq!(a.faces.len(), 1); + for at in [Point::new(50.0, 15.0), Point::new(25.0, 15.0)] { + let e = edges_at(&a, at); + assert_eq!(e.len(), 1, "{at:?}"); + assert_eq!((e[0].left, e[0].right), (Some(0), Some(0)), "{at:?}"); + } +} + +#[test] +fn loose_lines_in_many_faces_look_only_at_the_faces_near_them() { + // A 40 × 40 grid of separate squares, then the same with a loose line in each. + let squares: Vec = + (0..1600).map(|k| (f64::from(k % 40) * 20.0, f64::from(k / 40) * 20.0)).map(|(x, y)| rect(x, y, x + 10.0, y + 10.0)).collect(); + let started = super::super::index::work_done(); + assert_eq!(adjacency(&squares, DEFAULT_PRECISION).unwrap().faces.len(), 1600); + let plain = super::super::index::work_done() - started; + let mut all = squares.clone(); + all.extend((0..1600).map(|k| (f64::from(k % 40) * 20.0, f64::from(k / 40) * 20.0)).map(|(x, y)| line((x + 5.0, y), (x + 5.0, y + 5.0)))); + let started = super::super::index::work_done(); + let a = adjacency(&all, DEFAULT_PRECISION).unwrap(); + let work = super::super::index::work_done() - started - plain; + let loose: Vec<&MapEdge> = a.edges.iter().filter(|e| e.sources.len() == 1 && e.sources[0] >= 1600).collect(); + assert_eq!(loose.len(), 1600); + for e in loose { + let mid = e.path.to_bezpath().segments().next().unwrap().eval(0.5); + let face = a.faces.iter().position(|f| inside(f, mid)); + assert_eq!((e.left, e.right), (face, face)); + assert!(face.is_some()); + } + // Testing every face for each loose line would read 1,600 faces per line. + assert!(work <= 64 * 1600, "{work} reads"); +} + +#[test] +fn a_line_on_a_rectangle_side_keeps_both_inputs_in_either_order() { + for flip in [false, true] { + let (r, l) = (rect(0.0, 0.0, 100.0, 50.0), line((-10.0, 50.0), (110.0, 50.0))); + let shapes = if flip { vec![l, r] } else { vec![r, l] }; + let a = adjacency(&shapes, DEFAULT_PRECISION).unwrap(); + let on = edges_at(&a, Point::new(30.0, 50.0)); + assert_eq!(on.len(), 1, "flip {flip}: {on:?}"); + assert_eq!(on[0].sources, vec![0, 1], "flip {flip}"); + } +} + +#[test] +fn each_side_names_the_face_seen_on_that_side_of_the_edge() { + // A tray-like outline with a crease grid, edges drawn in every direction. + let a = adjacency( + &[ + rect(0.0, 0.0, 90.0, 60.0), + line((30.0, 0.0), (30.0, 60.0)), + line((60.0, 60.0), (60.0, 0.0)), + line((90.0, 20.0), (0.0, 20.0)), + line((0.0, 40.0), (90.0, 40.0)), + ], + DEFAULT_PRECISION, + ) + .unwrap(); + assert_eq!(a.faces.len(), 9); + let mut checked = 0; + for e in &a.edges { + let bp = e.path.to_bezpath(); + let Some(seg) = bp.segments().next() else { continue }; + let (p, d) = (seg.eval(0.5), seg.end() - seg.start()); + let n = d.normalize(); + // On the page (y down), the left of a direction (dx, dy) is (dy, -dx). + let (left_at, right_at) = (p + Vec2::new(n.y, -n.x) * 0.5, p + Vec2::new(-n.y, n.x) * 0.5); + for (side, at) in [(e.left, left_at), (e.right, right_at)] { + match side { + Some(f) => assert!(inside(&a.faces[f], at), "{e:?}"), + None => assert!(a.faces.iter().all(|f| !inside(f, at)), "{e:?}"), + } + checked += 1; + } + } + assert!(checked >= 24, "{checked}"); +} + +#[test] +fn a_slot_narrower_than_the_precision_is_a_sliver() { + let a = adjacency(&[rect(0.0, 0.0, 100.0, 50.0), rect(50.0, 10.0, 50.004, 40.0)], DEFAULT_PRECISION).unwrap(); + assert_eq!(a.slivers.len(), 1, "{:?}", a.slivers); + assert_eq!(a.faces.len(), 1); + let b = adjacency(&[rect(0.0, 0.0, 100.0, 50.0), rect(50.0, 10.0, 51.0, 40.0)], DEFAULT_PRECISION).unwrap(); + assert!(b.slivers.is_empty()); + assert_eq!(b.faces.len(), 2, "the slot is a face of its own"); +} + +#[test] +fn a_ring_is_a_face_with_a_hole_and_two_pieces() { + let a = adjacency(&[rect(0.0, 0.0, 100.0, 100.0), rect(30.0, 30.0, 70.0, 70.0)], DEFAULT_PRECISION).unwrap(); + assert_eq!(a.faces.len(), 2); + let ring = a.faces.iter().find(|f| inside(f, Point::new(10.0, 10.0))).unwrap(); + assert!(!inside(ring, Point::new(50.0, 50.0)), "the inner square is a hole in the ring"); + assert!((ring.area - 8400.0).abs() < 1e-6, "{}", ring.area); + assert_eq!(a.outlines.len(), 2); + assert_ne!(a.outlines[0].piece, a.outlines[1].piece); + let inner = a.faces.iter().find(|f| inside(f, Point::new(50.0, 50.0))).unwrap(); + assert_ne!(inner.piece, ring.piece); + let inner_side = edges_at(&a, Point::new(50.0, 30.0)); + let mut sides = [inner_side[0].left, inner_side[0].right]; + sides.sort_unstable(); + assert!(sides.iter().all(Option::is_some), "a ring face on one side, the inner square on the other: {sides:?}"); +} + +#[test] +fn bad_input_gives_no_map() { + assert!(adjacency(&[], DEFAULT_PRECISION).is_none()); + assert!(adjacency(&[line((0.0, 0.0), (f64::NAN, 1.0))], DEFAULT_PRECISION).is_none()); + assert!(adjacency(&[rect(0.0, 0.0, 10.0, 10.0)], 0.0).is_none()); + assert!(adjacency(&[rect(0.0, 0.0, 10.0, 10.0)], f64::INFINITY).is_none()); + let mut points: Vec = (0..=SHAPE_BUILDER_MAX_SEGMENTS + 1).map(|i| Point::new(i as f64, (i % 2) as f64)).collect(); + let open = Shape::new(PathData::single(SubPath::polyline(&points, false)), FillRule::NonZero, 0); + assert!(adjacency(&[open], DEFAULT_PRECISION).is_none(), "over the segment limit"); + points.truncate(64); + let open = Shape::new(PathData::single(SubPath::polyline(&points, false)), FillRule::NonZero, 0); + assert!(adjacency(&[open], DEFAULT_PRECISION).is_some()); +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(64))] + /// Random lines and boxes never panic, and every side an edge names is a face. + #[test] + fn random_lines_give_a_consistent_map( + segs in proptest::collection::vec((-50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0), 1..12), + boxed in any::(), + ) { + let mut shapes: Vec = segs.iter().map(|&(a, b, c, d)| line((a, b), (c, d))).collect(); + if boxed { + shapes.push(rect(-40.0, -40.0, 40.0, 40.0)); + } + if let Some(a) = adjacency(&shapes, DEFAULT_PRECISION) { + for e in &a.edges { + prop_assert!(e.left.is_none_or(|f| f < a.faces.len()) && e.right.is_none_or(|f| f < a.faces.len())); + prop_assert!(e.sources.iter().all(|&s| s < shapes.len())); + } + } + } +} diff --git a/crates/pathops/src/planar/map.rs b/crates/pathops/src/planar/map.rs index aa853b2469..a9b25d24b5 100644 --- a/crates/pathops/src/planar/map.rs +++ b/crates/pathops/src/planar/map.rs @@ -15,23 +15,23 @@ pub(crate) struct Rest { /// The planar graph of `shapes` (in the sweep's frame) with its faces walked: what [`build`] makes /// Live Paint faces and edges from, and what [`Map::merge`] merges faces in. pub(crate) struct Map { - edges: Vec, + pub(super) edges: Vec, around: Vec>, slot_of: Vec, /// Bounded faces: their cycle of half-edges, path and area; and, by their bounds, which can /// hold a point, so finding the face around one tests only those. - faces: Vec<(Vec, BezPath, f64)>, + pub(super) faces: Vec<(Vec, BezPath, f64)>, face_index: RectIndex, /// Bounded faces left out as slivers ([`is_sliver`]): their cycle of half-edges and the inputs /// whose fill covers them (none for a gap, such as a thin cutout). pub(super) slivers: Vec<(Vec, Vec)>, /// Outer boundaries of connected pieces, and the face each one is a hole in. - holes: Vec<(Vec, BezPath)>, - face_holes: Vec>, - tidy: Tidy, + pub(super) holes: Vec<(Vec, BezPath)>, + pub(super) face_holes: Vec>, + pub(super) tidy: Tidy, /// The inputs' anchors (sorted by x) and how close results snap back onto them. - anchors: Vec, - snap: f64, + pub(super) anchors: Vec, + pub(super) snap: f64, } /// With `cover`, also finds which inputs cover each sliver, which only [`Map::merge`] reads; @@ -41,7 +41,7 @@ pub(crate) fn map(shapes: &[Shape], cover: bool) -> Option { } /// [`map`] whose faces and pieces are refit to `precision`, and whose slivers thinner than it are dropped. -fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option { +pub(super) fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option { let mut inputs: Vec<(BezPath, usize)> = Vec::new(); for (i, s) in shapes.iter().enumerate() { let mut bp = BezPath::new(); diff --git a/crates/three-d/Cargo.toml b/crates/three-d/Cargo.toml index f5eefa1c9b..48d2bfbf05 100644 --- a/crates/three-d/Cargo.toml +++ b/crates/three-d/Cargo.toml @@ -11,3 +11,6 @@ workspace = true [dependencies] vectorcraft-geom = { workspace = true } vectorcraft-pathops = { workspace = true } + +[dev-dependencies] +proptest = { workspace = true } diff --git a/crates/three-d/src/fold.rs b/crates/three-d/src/fold.rs new file mode 100644 index 0000000000..c68f8aa6ca --- /dev/null +++ b/crates/three-d/src/fold.rs @@ -0,0 +1,1237 @@ +//! The panels and hinges of a packaging blank, from its fold lines. +//! +//! Cut lines bound the material. Each connected piece of Cut lines with material is one blank: its +//! outline is the largest closed Cut subpath of the piece when every other face of the piece lies +//! inside it or inside another closed Cut subpath, and the piece's outer boundary otherwise. A face +//! is material when it lies inside that outline and inside no other closed Cut subpath of the piece, +//! so a slot drawn as a rectangle across the outline leaves the same material as a notch drawn in +//! it. Crease, Partial Cut and Perforation lines divide the material into panels; the pieces of them +//! between two panels are that pair's hinge. [`blanks`] also lists what is wrong with the lines +//! ([`IssueCode`]). + +use std::collections::{HashMap, HashSet}; + +use vectorcraft_geom::kurbo::{Line, ParamCurveArclen, ParamCurveNearest, PathSeg}; +use vectorcraft_geom::{BezPath, FillRule, ParamCurve, PathData, Point, Rect, Shape as _, SubPath}; +use vectorcraft_pathops::{Adjacency, DEFAULT_PRECISION, SHAPE_BUILDER_MAX_SEGMENTS, Shape, adjacency, find_gaps, interior_point, unite_all}; + +/// Most panels one blank may have. Its hinges are the edges of a planar graph on its panels, so there +/// are at most 3 × 256 - 6 = 762 of them. +pub const MAX_PANELS: usize = 256; +/// Most segments the fold lines may have together. +pub const MAX_SEGMENTS: usize = SHAPE_BUILDER_MAX_SEGMENTS; + +/// What a fold line does. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LineKind { + /// Separates the material. + Cut, + /// A fold. + Crease, + /// A fold cut part way through the board. + PartialCut, + /// A fold along a line of cuts. + Perforation, +} + +impl LineKind { + /// The angle a line of this kind folds at when it has none of its own, in degrees: Crease and + /// Perforation 90, Partial Cut -90 (VectorCraft's own values); a positive angle folds away from + /// the printed side. A Cut line does not fold: 0. + pub fn default_angle(self) -> f64 { + match self { + LineKind::Cut => 0.0, + LineKind::Crease | LineKind::Perforation => 90.0, + LineKind::PartialCut => -90.0, + } + } +} + +/// A fold line: the path (document coordinates), its kind, its own fold angle in degrees if it has +/// one, and a key the issues name it by. +#[derive(Clone, Debug)] +pub struct FoldLine { + pub path: PathData, + pub kind: LineKind, + pub angle: Option, + pub key: u64, +} + +/// One blank: its panels, the hinges between them, and its holes. +#[derive(Clone, Debug, Default)] +pub struct Blank { + pub panels: Vec, + pub hinges: Vec, + pub holes: Vec, +} + +/// A panel: an area of material between fold lines. +#[derive(Clone, Debug)] +pub struct Panel { + pub outline: PathData, + pub area: f64, +} + +/// The fold between panels `a` and `b` (indices into the blank's panels, `a` < `b`), about the +/// straight line from `from` to `to`, at `angle` degrees, made of the lines `keys`. `straight` is +/// false when its pieces are not on one straight line within the tolerance; it then folds about the +/// line through its longest piece. +#[derive(Clone, Debug)] +pub struct Hinge { + pub a: usize, + pub b: usize, + pub from: Point, + pub to: Point, + pub angle: f64, + pub keys: Vec, + pub straight: bool, +} + +/// What can be wrong with fold lines, in the order [`blanks`] lists them. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum IssueCode { + /// No Cut line. + NoCut, + /// The Cut lines enclose no area. + Open, + /// An end of a Cut line meets no other fold line within the tolerance (a slit that ends on a + /// crease is not loose). + LooseEnd, + /// An end of a Cut line comes within the tolerance of a Cut line without meeting it; the panels + /// are built with the gap closed. + Gap, + /// Over [`MAX_SEGMENTS`] segments or [`MAX_PANELS`] panels in a blank, or the lines can't be + /// mapped. + TooComplex, + /// A Cut line and a crease lie on top of each other. + CutOverCrease, + /// Two lines of the same kind lie on top of each other. + Duplicate, + /// A crease ends inside a panel. + DanglingCrease, + /// A crease divides no two panels. + NoSplit, + /// A crease lies outside every blank. + Outside, + /// A hinge's pieces are not on one straight line. + NotStraight, + /// A gap between lines is narrower than the planar map can tell apart. + Sliver, + /// A hole holds crease lines, or a blank lies inside a hole. + Ambiguous, + /// A panel is joined to the largest panel of its blank by no chain of hinges. + LoosePanel, + /// A fold line is on a layer that does not print (the caller reports it). + NonPrinting, +} + +impl IssueCode { + /// Every code, in order. + pub const ALL: [IssueCode; 15] = [ + IssueCode::NoCut, + IssueCode::Open, + IssueCode::LooseEnd, + IssueCode::Gap, + IssueCode::TooComplex, + IssueCode::CutOverCrease, + IssueCode::Duplicate, + IssueCode::DanglingCrease, + IssueCode::NoSplit, + IssueCode::Outside, + IssueCode::NotStraight, + IssueCode::Sliver, + IssueCode::Ambiguous, + IssueCode::LoosePanel, + IssueCode::NonPrinting, + ]; + + /// The code's stable id. + pub fn id(self) -> &'static str { + match self { + IssueCode::NoCut => "noCut", + IssueCode::Open => "open", + IssueCode::LooseEnd => "looseEnd", + IssueCode::Gap => "gap", + IssueCode::TooComplex => "tooComplex", + IssueCode::CutOverCrease => "cutOverCrease", + IssueCode::Duplicate => "duplicate", + IssueCode::DanglingCrease => "danglingCrease", + IssueCode::NoSplit => "noSplit", + IssueCode::Outside => "outside", + IssueCode::NotStraight => "notStraight", + IssueCode::Sliver => "sliver", + IssueCode::Ambiguous => "ambiguous", + IssueCode::LoosePanel => "loosePanel", + IssueCode::NonPrinting => "nonPrinting", + } + } + + /// Whether it is an error (the blank can't be made as drawn) rather than a warning. + pub fn is_error(self) -> bool { + matches!(self, IssueCode::NoCut | IssueCode::Open | IssueCode::LooseEnd | IssueCode::TooComplex | IssueCode::CutOverCrease) + } +} + +/// One issue: its code, the lines it is about, and the place it is at, when it has one. +#[derive(Clone, Debug, PartialEq)] +pub struct Issue { + pub code: IssueCode, + pub keys: Vec, + pub at: Option, +} + +impl Issue { + fn new(code: IssueCode, mut keys: Vec, at: Option) -> Self { + keys.sort_unstable(); + keys.dedup(); + Issue { code, keys, at } + } +} + +/// One subpath of a fold line. +struct Piece { + sp: SubPath, + line: usize, +} + +/// The blanks `lines` make, and their issues in [`IssueCode`] order. `tolerance` (points) is how +/// far apart a Cut line's end and another Cut line may be and still be joined, by a line [`blanks`] +/// adds, and how far a hinge's pieces may stray from one straight line. Nothing is built when there +/// is no Cut line, the lines are too complex, or the Cut lines enclose no area. +pub fn blanks(lines: &[FoldLine], tolerance: f64) -> (Vec, Vec) { + let tolerance = if tolerance.is_finite() && tolerance > 0.0 { tolerance } else { DEFAULT_PRECISION }; + // Counted before anything is copied. + let segments = lines.iter().flat_map(|l| &l.path.subpaths).filter(|sp| usable(sp)).try_fold(0usize, |n, sp| { + let n = n.saturating_add(sp.segment_count()); + (n <= MAX_SEGMENTS).then_some(n) + }); + if segments.is_none() { + return (vec![], vec![Issue::new(IssueCode::TooComplex, vec![], None)]); + } + let pieces: Vec = lines + .iter() + .enumerate() + .flat_map(|(line, l)| l.path.subpaths.iter().filter(|sp| usable(sp)).map(move |sp| Piece { sp: sp.clone(), line })) + .collect(); + let mut issues = vec![]; + let kind = |p: &Piece| lines.get(p.line).map_or(LineKind::Cut, |l| l.kind); + let key = |p: &Piece| lines.get(p.line).map_or(0, |l| l.key); + let cuts: Vec<&Piece> = pieces.iter().filter(|p| kind(p) == LineKind::Cut).collect(); + if cuts.is_empty() { + return (vec![], vec![Issue::new(IssueCode::NoCut, vec![], None)]); + } + let folds: Vec<&Piece> = pieces.iter().filter(|p| kind(p) != LineKind::Cut).collect(); + let cut_shapes: Vec = cuts.iter().map(|p| shape(p.sp.clone())).collect(); + let gaps = find_gaps(&cut_shapes, tolerance); + // `find_gaps` takes ends closer than 1/10,000 of the tolerance as joined, which the map may not + // join: those are bridged too, without an issue. + let joined = find_gaps(&cut_shapes, (tolerance * 1e-4).max(1e-6)); + // An end a gap starts or ends at is not loose. + let gap_ends = + Cells::new(gaps.iter().chain(&joined).flatten().map(|&e| (Rect::from_points(e, e), (e.x.to_bits(), e.y.to_bits()))).collect(), 0.0, 4096.0); + let bridged = |at: Point| gap_ends.near(at, 1e-6).into_iter().any(|(x, y)| Point::new(f64::from_bits(x), f64::from_bits(y)).distance(at) <= 1e-6); + issues.extend( + loose_ends(&cuts, &folds, tolerance) + .into_iter() + .filter(|&(_, at)| !bridged(at)) + .map(|(i, at)| Issue::new(IssueCode::LooseEnd, vec![cuts.get(i).map_or(0, |p| key(p))], Some(at))), + ); + if !gaps.is_empty() { + // The cut lines by their ends, to name the line each gap starts from. + let at_ends = cuts.iter().enumerate().flat_map(|(i, p)| ends(&p.sp).into_iter().map(move |e| (Rect::from_points(e, e), (i, e)))); + let by_end = Cells::new(at_ends.map(|(r, (i, e))| (r, (i, e.x.to_bits(), e.y.to_bits()))).collect(), 0.0, 4096.0); + for g in &gaps { + let of = by_end + .near(g[0], 1e-6) + .into_iter() + .find(|&(_, x, y)| Point::new(f64::from_bits(x), f64::from_bits(y)).distance(g[0]) <= 1e-6) + .and_then(|(i, _, _)| cuts.get(i)) + .map(|p| key(p)); + issues.push(Issue::new(IssueCode::Gap, of.into_iter().collect(), Some(g[0]))); + } + } + let gaps: Vec<[Point; 2]> = gaps.into_iter().chain(joined).collect(); + let gap_shape = shape_of_gaps(&gaps); + let Some(material) = Material::new(&cuts, &gaps, cut_shapes.into_iter().chain(gap_shape.clone()).collect()) else { + issues.push(Issue::new(IssueCode::TooComplex, vec![], None)); + return (vec![], sorted(issues)); + }; + if material.blanks.is_empty() { + issues.push(Issue::new(IssueCode::Open, cuts.iter().map(|p| key(p)).collect(), None)); + return (vec![], sorted(issues)); + } + let all: Vec = pieces.iter().map(|p| shape(p.sp.clone())).chain(gap_shape).collect(); + let Some(full) = adjacency(&all, DEFAULT_PRECISION) else { + issues.push(Issue::new(IssueCode::TooComplex, vec![], None)); + return (vec![], sorted(issues)); + }; + let cut_lines: Vec = cuts.iter().map(|p| p.line).collect(); + let ctx = Context { lines, pieces: &pieces, cut_lines: &cut_lines, material: &material, full: &full, tolerance }; + let built = ctx.build(&mut issues); + (built, sorted(issues)) +} + +fn sorted(mut issues: Vec) -> Vec { + issues.sort_by_key(|i| i.code); + issues +} + +/// A subpath with two anchors or more, every coordinate finite. +fn usable(sp: &SubPath) -> bool { + sp.anchors.len() >= 2 && sp.anchors.iter().all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()) +} + +fn shape(sp: SubPath) -> Shape { + Shape::new(PathData::single(sp), FillRule::NonZero, 0) +} + +/// The lines across `gaps`, as one input. +fn shape_of_gaps(gaps: &[[Point; 2]]) -> Option { + (!gaps.is_empty()).then(|| Shape::new(PathData::new(gaps.iter().map(|g| SubPath::polyline(g, false)).collect()), FillRule::NonZero, 0)) +} + +/// The two ends of an open subpath; none for a closed one or one that ends where it starts. +fn ends(sp: &SubPath) -> Vec { + match (sp.anchors.first(), sp.anchors.last()) { + (Some(a), Some(b)) if !sp.closed && a.p.distance(b.p) > 1e-6 => vec![a.p, b.p], + _ => vec![], + } +} + +/// Whether `sp` encloses an area: closed, or open with its ends together. +fn is_loop(sp: &SubPath) -> bool { + ends(sp).is_empty() && sp.anchors.len() >= 2 +} + +/// Most grid cells one item is filed under by [`Cells`]; a larger one is tried for every point. +const SPAN: usize = 1024; + +/// The farthest cell from the grid's origin, on each axis, that [`Cells`] numbers a point in. +const CELL_LIMIT: f64 = 1_048_576.0; + +/// Most (cell, item) entries [`Cells`] holds in all; the items past it are tried for every point, as +/// large ones are. +const CELL_ENTRIES: usize = 1 << 21; + +/// Items (segments, faces, ends) by the cells of a square grid that their bounds cover, so that +/// finding the items near a point tests only those in its cells. +struct Cells { + origin: Point, + cell: f64, + cells: HashMap<(i64, i64), Vec>, + /// Items whose bounds cover more than [`SPAN`] cells, near every point. + wide: Vec, +} + +impl Cells { + /// `items` by their bounds, in cells `cell` wide or `1/divisions` of all the bounds where that is + /// wider. + fn new(items: Vec<(Rect, T)>, cell: f64, divisions: f64) -> Self { + let bounds = items.iter().map(|(b, _)| *b).filter(Rect::is_finite).reduce(|a, b| a.union(b)).unwrap_or_default(); + let cell = cell.max(bounds.width().max(bounds.height()) / divisions); + let cell = if cell.is_finite() && cell > 0.0 { cell } else { 1.0 }; + let mut grid = Cells { origin: bounds.origin(), cell, cells: HashMap::new(), wide: vec![] }; + let mut entries = 0usize; + for (b, item) in items { + let ((x0, y0), (x1, y1)) = (grid.cell_of(Point::new(b.x0, b.y0)), grid.cell_of(Point::new(b.x1, b.y1))); + let span = usize::try_from((x1 - x0 + 1).saturating_mul(y1 - y0 + 1)).unwrap_or(usize::MAX); + if span > SPAN || entries.saturating_add(span) > CELL_ENTRIES { + grid.wide.push(item); + continue; + } + entries += span; + for x in x0..=x1 { + for y in y0..=y1 { + grid.cells.entry((x, y)).or_default().push(item); + } + } + } + grid + } + + fn cell_of(&self, p: Point) -> (i64, i64) { + let at = |v: f64, o: f64| ((v - o) / self.cell).floor().clamp(-CELL_LIMIT, CELL_LIMIT) as i64; + (at(p.x, self.origin.x), at(p.y, self.origin.y)) + } + + /// The items whose bounds come within `r` of `p` (and some farther ones), each once. When `r` + /// spans more cells than hold items, the cells that hold items are read instead. + fn near(&self, p: Point, r: f64) -> Vec { + let mut out = self.wide.clone(); + let ((x0, y0), (x1, y1)) = (self.cell_of(Point::new(p.x - r, p.y - r)), self.cell_of(Point::new(p.x + r, p.y + r))); + let span = (x1 - x0 + 1).saturating_mul(y1 - y0 + 1); + if usize::try_from(span).map_or(true, |n| n > self.cells.len()) { + for (&(x, y), items) in &self.cells { + if (x0..=x1).contains(&x) && (y0..=y1).contains(&y) { + out.extend(items); + } + } + } else { + for x in x0..=x1 { + for y in y0..=y1 { + out.extend(self.cells.get(&(x, y)).into_iter().flatten()); + } + } + } + out.sort_unstable(); + out.dedup(); + out + } +} + +/// The ends of `cuts` that lie more than `tolerance` from every other fold line among `cuts` and +/// `folds`, as (index into `cuts`, end). A line's own points count when they are more than +/// `tolerance` from the end along the line, so a cut line that comes back to its own end meets it. +fn loose_ends(cuts: &[&Piece], folds: &[&Piece], tolerance: f64) -> Vec<(usize, Point)> { + let segs: Vec> = cuts.iter().chain(folds).map(|p| PathData::single(p.sp.clone()).to_bezpath().segments().collect()).collect(); + let boxes = segs.iter().enumerate().flat_map(|(j, ss)| ss.iter().enumerate().map(move |(k, s)| (s.bounding_box(), (j, k)))); + // The cells are as wide as the tolerance, or 1/4096 of the lines where that is wider. + let grid = Cells::new(boxes.collect(), tolerance, 4096.0); + let mut out = vec![]; + for (i, p) in cuts.iter().enumerate() { + let own = segs.get(i).map(Vec::as_slice).unwrap_or_default(); + // How far along the line each of its segments starts, and the line's length. + let starts: Vec = own.iter().scan(0.0, |at, s| Some(std::mem::replace(at, *at + s.arclen(1e-3)))).collect(); + let total = own.last().zip(starts.last()).map_or(0.0, |(s, at)| at + s.arclen(1e-3)); + for (k, e) in ends(&p.sp).into_iter().enumerate() { + let near = grid.near(e, tolerance).into_iter().any(|(j, s)| { + let Some(seg) = segs.get(j).and_then(|ss| ss.get(s)) else { return false }; + let b = seg.bounding_box(); + if e.x < b.x0 - tolerance || e.x > b.x1 + tolerance || e.y < b.y0 - tolerance || e.y > b.y1 + tolerance { + return false; + } + let hit = seg.nearest(e, 1e-9); + if hit.distance_sq.sqrt() > tolerance { + return false; + } + if j != i { + return true; + } + let along = starts.get(s).copied().unwrap_or(0.0) + seg.subsegment(0.0..hit.t).arclen(1e-3); + (if k == 0 { along } else { total - along }) > tolerance + }); + if !near { + out.push((i, e)); + } + } + } + out +} + +/// A point inside `path`, or the middle of its bounds for one too thin to find one in. +fn point_in(path: &PathData) -> Option { + interior_point(path).or_else(|| path.bounds().map(|b| b.center())) +} + +fn contains(bp: &BezPath, p: Point) -> bool { + bp.winding(p) != 0 +} + +/// The loops that open Cut pieces and the lines across `gaps` make end to end: each chain of them +/// whose every end meets exactly one end of another piece of the chain (within 1e-6), as (index +/// into `cuts` of its first Cut piece, closed path). Pieces that lie on no cycle are left out first; +/// ends where three of the remaining pieces or more meet join nothing. +fn chains(cuts: &[&Piece], gaps: &[[Point; 2]]) -> Vec<(usize, BezPath)> { + const NEAR: f64 = 1e-6; + // Cell numbers stay far from the ends of `i64`, so a neighbor's number does not overflow. + let cell = |v: f64| (v / NEAR).round().clamp(-1e15, 1e15) as i64; + let key = |p: Point| (cell(p.x), cell(p.y)); + // The ends by node: ends within `NEAR` of a node's first end share it. + let mut nodes: HashMap<(i64, i64), usize> = HashMap::new(); + let mut firsts: Vec = vec![]; + let mut node_of = |p: Point| { + let (kx, ky) = key(p); + for dx in -1..=1 { + for dy in -1..=1 { + if let Some(&n) = nodes.get(&(kx.saturating_add(dx), ky.saturating_add(dy))) + && firsts.get(n).is_some_and(|q| q.distance(p) <= NEAR) + { + return n; + } + } + } + firsts.push(p); + nodes.insert((kx, ky), firsts.len() - 1); + firsts.len() - 1 + }; + // The open Cut pieces (with their index into `cuts`) and the gap lines, each with its segments. + let pieces = cuts + .iter() + .enumerate() + .filter(|(_, p)| ends(&p.sp).len() == 2) + .map(|(i, p)| (Some(i), PathData::single(p.sp.clone()).to_bezpath().segments().collect())); + let lines = gaps.iter().map(|g| (None, vec![PathSeg::Line(Line::new(g[0], g[1]))])); + let items: Vec<(Option, Vec)> = pieces.chain(lines).collect(); + // (index into `items`, start node, end node) of each, and the pieces at each node. + let open: Vec<(usize, usize, usize)> = + items.iter().enumerate().filter_map(|(k, (_, segs))| Some((k, node_of(segs.first()?.start()), node_of(segs.last()?.end())))).collect(); + let mut at: HashMap> = HashMap::new(); + for (k, &(_, a, b)) in open.iter().enumerate() { + at.entry(a).or_default().push(k); + at.entry(b).or_default().push(k); + } + // A piece that lies on no cycle of pieces (a slit, a line from another one's side, a cut that + // joins two loops) is no part of a loop: such pieces are dropped, so that a slit at a loop's + // corner does not stop the loop. + let live: Vec = bridges(firsts.len(), &open).into_iter().map(|b| !b).collect(); + for ks in at.values_mut() { + ks.retain(|&k| live.get(k) == Some(&true)); + } + let mut used: Vec = live.iter().map(|l| !l).collect(); + let mut out = vec![]; + for start in 0..open.len() { + if used.get(start) != Some(&false) { + continue; + } + // Walk from the start piece's first end until the chain comes back to it, or stops. + let Some(&(_, first_node, _)) = open.get(start) else { continue }; + let (mut k, mut from, mut walk) = (start, first_node, vec![]); + let closed = loop { + let Some(&(_, a, b)) = open.get(k) else { break false }; + if used.get(k) != Some(&false) { + break false; + } + if let Some(u) = used.get_mut(k) { + *u = true; + } + let forward = a == from; + walk.push((k, forward)); + let to = if forward { b } else { a }; + if to == first_node { + break true; + } + let next = at.get(&to).filter(|ks| ks.len() == 2).and_then(|ks| ks.iter().copied().find(|&j| j != k)); + match next { + Some(j) => (k, from) = (j, to), + None => break false, + } + }; + if !closed || at.get(&first_node).is_none_or(|ks| ks.len() != 2) { + continue; + } + let mut bp = BezPath::new(); + let mut first_cut = None; + for (n, &(k, forward)) in walk.iter().enumerate() { + let Some((i, segs)) = open.get(k).and_then(|&(j, _, _)| items.get(j)) else { continue }; + first_cut = first_cut.or(*i); + let segs: Vec = if forward { segs.clone() } else { segs.iter().rev().map(|s| s.reverse()).collect() }; + for (m, s) in segs.iter().enumerate() { + if n == 0 && m == 0 { + bp.move_to(s.start()); + } + match *s { + PathSeg::Line(l) => bp.line_to(l.p1), + PathSeg::Quad(q) => bp.quad_to(q.p1, q.p2), + PathSeg::Cubic(c) => bp.curve_to(c.p1, c.p2, c.p3), + } + } + } + bp.close_path(); + if let Some(i) = first_cut { + out.push((i, bp)); + } + } + out +} + +/// Which of `edges` ((id, end node, end node), nodes below `nodes`) lie on no cycle: the bridges of +/// the graph, found depth first without recursion. +fn bridges(nodes: usize, edges: &[(usize, usize, usize)]) -> Vec { + let mut adj: Vec> = vec![vec![]; nodes]; + for (k, &(_, a, b)) in edges.iter().enumerate() { + adj.get_mut(a).into_iter().for_each(|l| l.push((b, k))); + adj.get_mut(b).into_iter().for_each(|l| l.push((a, k))); + } + let mut bridge = vec![false; edges.len()]; + let (mut disc, mut low) = (vec![usize::MAX; nodes], vec![0usize; nodes]); + let mut timer = 0usize; + for s in 0..nodes { + if disc.get(s) != Some(&usize::MAX) { + continue; + } + let mut stamp = |v: usize, disc: &mut Vec, low: &mut Vec| { + disc.get_mut(v).into_iter().for_each(|d| *d = timer); + low.get_mut(v).into_iter().for_each(|l| *l = timer); + timer += 1; + }; + stamp(s, &mut disc, &mut low); + // (node, the edge it was reached by, the next of its edges to follow) + let mut stack: Vec<(usize, Option, usize)> = vec![(s, None, 0)]; + while let Some(&(v, by, i)) = stack.last() { + if let Some(&(w, e)) = adj.get(v).and_then(|l| l.get(i)) { + if let Some(top) = stack.last_mut() { + top.2 += 1; + } + if Some(e) == by { + continue; + } + match disc.get(w).copied() { + Some(usize::MAX) => { + stamp(w, &mut disc, &mut low); + stack.push((w, Some(e), 0)); + } + Some(d) => { + if let Some(l) = low.get_mut(v) { + *l = (*l).min(d); + } + } + None => {} + } + } else { + stack.pop(); + let low_v = low.get(v).copied().unwrap_or(0); + if let Some(&(u, _, _)) = stack.last() { + if let Some(l) = low.get_mut(u) { + *l = (*l).min(low_v); + } + if disc.get(u).is_some_and(|&d| low_v > d) + && let Some(b) = by.and_then(|e| bridge.get_mut(e)) + { + *b = true; + } + } + } + } + } + bridge +} + +/// The material the Cut lines leave: the faces of their planar map, which are material, which are +/// holes, and the blanks (connected pieces with material). +struct Material { + map: Adjacency, + /// For each face of `map`: a point inside it, whether it is material, whether it is a hole. + points: Vec>, + material: Vec, + hole: Vec, + /// The pieces of `map` that are blanks, in order, and each one's outline. + blanks: Vec, + bounds: Vec, + /// For each piece of `map`, the blank (index into `blanks`) it is part of: its own, or for a + /// piece that lies in a blank's material (a window), that blank. + owner: Vec>, + /// The faces of each piece of `map`, and its edges. + faces_by_piece: Vec>, + edges_by_piece: Vec>, + /// Each face's outer boundary and its whole path (with its holes), and the faces by where they + /// are. + outer: Vec, + whole: Vec, + face_cells: Cells, + /// The blanks by where their outlines are (built once every piece is classified). + bound_cells: Cells, +} + +/// A loop among the Cut lines: its path and its area. +type Loop = (BezPath, f64); + +impl Material { + /// The material of `cuts` with the lines across `gaps`, mapped as `shapes` (the cuts, then the + /// gap lines). + fn new(cuts: &[&Piece], gaps: &[[Point; 2]], shapes: Vec) -> Option { + let map = adjacency(&shapes, DEFAULT_PRECISION)?; + let points: Vec> = map.faces.iter().map(|f| point_in(&f.path)).collect(); + let pieces = map.faces.iter().map(|f| f.piece + 1).chain(map.edges.iter().map(|e| e.piece + 1)).max().unwrap_or(0); + let mut faces_by_piece = vec![vec![]; pieces]; + for (f, face) in map.faces.iter().enumerate() { + if let Some(list) = faces_by_piece.get_mut(face.piece) { + list.push(f); + } + } + // The piece each input is part of, from the edges it lies on. + let mut piece_of_input: Vec> = vec![None; shapes.len()]; + let mut edges_by_piece = vec![vec![]; pieces]; + for (e, edge) in map.edges.iter().enumerate() { + if let Some(list) = edges_by_piece.get_mut(edge.piece) { + list.push(e); + } + for &s in &edge.sources { + if let Some(slot) = piece_of_input.get_mut(s).filter(|p| p.is_none()) { + *slot = Some(edge.piece); + } + } + } + let mut loops: Vec> = vec![vec![]; pieces]; + for (i, p) in cuts.iter().enumerate().filter(|(_, p)| is_loop(&p.sp)) { + let Some(list) = piece_of_input.get(i).copied().flatten().and_then(|piece| loops.get_mut(piece)) else { continue }; + let bp = PathData::single(SubPath::of(p.sp.anchors.clone(), true)).to_bezpath(); + let area = bp.area().abs(); + list.push((bp, area)); + } + // Loops drawn as open pieces end to end, such as a slot of four lines. + for (i, bp) in chains(cuts, gaps) { + let Some(list) = piece_of_input.get(i).copied().flatten().and_then(|piece| loops.get_mut(piece)) else { continue }; + let area = bp.area().abs(); + list.push((bp, area)); + } + // Each piece's outer boundary and a point of it. + let mut outlines: Vec)>> = vec![None; pieces]; + for o in &map.outlines { + if let Some(slot) = outlines.get_mut(o.piece).filter(|s| s.is_none()) { + *slot = Some((o.path.to_bezpath(), o.path.subpaths.first().and_then(|sp| sp.anchors.first()).map(|a| a.p))); + } + } + // Outer pieces first: the face a piece lies in belongs to a piece with a larger outline. + let mut order: Vec<(usize, f64, Option)> = + outlines.iter().enumerate().map(|(p, o)| (p, o.as_ref().map_or(0.0, |o| o.0.area().abs()), o.as_ref().and_then(|o| o.1))).collect(); + order.sort_by(|a, b| b.1.total_cmp(&a.1)); + let outer: Vec = + map.faces.iter().map(|f| f.path.subpaths.first().map(|sp| PathData::single(sp.clone()).to_bezpath()).unwrap_or_default()).collect(); + let whole: Vec = map.faces.iter().map(|f| f.path.to_bezpath()).collect(); + let face_cells = Cells::new(outer.iter().enumerate().map(|(f, bp)| (bp.bounding_box(), f)).collect(), 0.0, 256.0); + let faces = map.faces.len(); + let mut m = Material { + map, + points, + material: vec![false; faces], + hole: vec![false; faces], + blanks: vec![], + bounds: vec![], + owner: vec![None; pieces], + faces_by_piece, + edges_by_piece, + outer, + whole, + face_cells, + bound_cells: Cells::new(vec![], 0.0, 256.0), + }; + for (piece, _, first) in order { + match first.and_then(|q| m.around(piece, q)) { + // A piece in a blank's material is a hole in it, a window. + Some(f) if m.material.get(f) == Some(&true) => { + let owner = m.map.faces.get(f).and_then(|x| m.owner.get(x.piece)).copied().flatten(); + for g in m.faces_by_piece.get(piece).cloned().unwrap_or_default() { + let usable = m.points.get(g).copied().flatten().is_some(); + if let Some(h) = m.hole.get_mut(g) { + *h = usable; + } + } + if let Some(o) = m.owner.get_mut(piece) { + *o = owner; + } + } + _ => { + let own = loops.get(piece).map(Vec::as_slice).unwrap_or_default(); + let fallback = outlines.get(piece).cloned().flatten().map(|o| o.0); + m.classify(piece, own, fallback); + } + } + } + m.bound_cells = Cells::new(m.bounds.iter().enumerate().map(|(b, bp)| (bp.bounding_box(), b)).collect(), 0.0, 256.0); + Some(m) + } + + /// The face of another piece than `piece` whose outer boundary holds `q`, a point of its + /// outline, the one with the smallest outer boundary when several do. The boundaries are + /// compared, not the faces' own areas, which leave out the holes in them. + fn around(&self, piece: usize, q: Point) -> Option { + let outer_area = |f: usize| self.outer.get(f).map_or(f64::INFINITY, |bp| bp.area().abs()); + self.face_cells + .near(q, 0.0) + .into_iter() + .filter(|&f| self.map.faces.get(f).is_some_and(|x| x.piece != piece)) + .filter(|&f| self.outer.get(f).is_some_and(|bp| contains(bp, q))) + .min_by(|&a, &b| outer_area(a).total_cmp(&outer_area(b))) + } + + fn area(&self, f: usize) -> f64 { + self.map.faces.get(f).map_or(f64::INFINITY, |x| x.area) + } + + /// Which faces of `piece` are material and which are holes, by its own loops `loops`; with + /// material, the piece is a blank. A loop that holds the same faces as a larger one (a loop + /// drawn twice) counts once. Its outlines are its largest loop and each smaller loop that shares + /// no face with a larger outline (two outlines joined by a cut line); its other loops cut + /// material out. When the outlines and the loops that cut out do not cover every face (an + /// outline drawn as open lines), every loop cuts out and the blank is bounded by `fallback`, its + /// outer boundary. + fn classify(&mut self, piece: usize, loops: &[Loop], fallback: Option) { + let faces = self.faces_by_piece.get(piece).cloned().unwrap_or_default(); + let mut by_area: Vec<&Loop> = loops.iter().collect(); + by_area.sort_by(|a, b| b.1.total_cmp(&a.1)); + let points = &self.points; + let unusable = |f: usize| points.get(f).copied().flatten().is_none(); + // The piece's faces by their points, so that each loop tests only the faces near it. + let at: Vec<(Rect, usize)> = + faces.iter().enumerate().filter_map(|(k, &f)| points.get(f).copied().flatten().map(|p| (Rect::from_points(p, p), k))).collect(); + let extent = at.iter().map(|(r, _)| *r).reduce(|a, b| a.union(b)); + let near = Cells::new(at, 0.0, 256.0); + // Each loop with the faces of the piece it holds (positions in `faces`, ascending); loops + // that hold none, and loops that hold the same faces as a larger one, are left out. + let mut seen: HashSet> = HashSet::new(); + let mut own: Vec<(&BezPath, Vec)> = vec![]; + for l in by_area { + let b = l.0.bounding_box().inflate(1e-6, 1e-6); + // Only the part of the loop's bounds where faces are is looked up, a few hundred cells + // across at most. + let Some(q) = extent.map(|e| b.intersect(e)).filter(|q| q.width() >= 0.0 && q.height() >= 0.0) else { continue }; + let holds: Vec = near + .near(q.center(), q.width().max(q.height()) / 2.0) + .into_iter() + .filter(|&k| faces.get(k).and_then(|&f| points.get(f).copied().flatten()).is_some_and(|p| b.contains(p) && contains(&l.0, p))) + .collect(); + if !holds.is_empty() && seen.insert(holds.clone()) { + own.push((&l.0, holds)); + } + } + // Outlines go largest first; a loop holding a face an outline holds cuts out instead. + let (mut outlines, mut others): (Vec, Vec) = (vec![], vec![]); + let mut in_an_outline = vec![false; faces.len()]; + let mut held = vec![false; faces.len()]; + for (i, (_, holds)) in own.iter().enumerate() { + holds.iter().for_each(|&k| held.get_mut(k).into_iter().for_each(|h| *h = true)); + if holds.iter().any(|&k| in_an_outline.get(k) == Some(&true)) { + others.push(i); + } else { + holds.iter().for_each(|&k| in_an_outline.get_mut(k).into_iter().for_each(|h| *h = true)); + outlines.push(i); + } + } + let covered = faces.iter().enumerate().all(|(k, &f)| held.get(k) == Some(&true) || unusable(f)); + if !covered { + outlines.clear(); + others = (0..own.len()).collect(); + } + let mut cut = vec![false; faces.len()]; + for (_, holds) in others.iter().filter_map(|&i| own.get(i)) { + holds.iter().for_each(|&k| cut.get_mut(k).into_iter().for_each(|c| *c = true)); + } + let mut any = false; + for (k, &f) in faces.iter().enumerate() { + let in_outline = outlines.is_empty() || in_an_outline.get(k) == Some(&true); + let cut_out = cut.get(k) == Some(&true); + let material = !unusable(f) && in_outline && !cut_out; + any |= material; + if let Some(m) = self.material.get_mut(f) { + *m = material; + } + if let Some(h) = self.hole.get_mut(f) { + *h = !unusable(f) && in_outline && cut_out; + } + } + if any { + let bound = if outlines.is_empty() { + fallback + } else { + let mut all = BezPath::new(); + outlines.iter().filter_map(|&o| own.get(o)).for_each(|o| all.extend(o.0.elements().iter().copied())); + Some(all) + }; + if let Some(o) = self.owner.get_mut(piece) { + *o = Some(self.blanks.len()); + } + self.blanks.push(piece); + self.bounds.push(bound.unwrap_or_default()); + } + } + + /// The face of the Cut lines' map that holds `p`, the smallest when several do. + fn face_at(&self, p: Point) -> Option { + self.face_cells + .near(p, 0.0) + .into_iter() + .filter(|&f| self.whole.get(f).is_some_and(|bp| contains(bp, p))) + .min_by(|&a, &b| self.area(a).total_cmp(&self.area(b))) + } + + /// Whether `p` lies inside the outline of a blank. + fn in_a_blank(&self, p: Point) -> bool { + self.bound_cells.near(p, 0.0).into_iter().any(|b| self.bounds.get(b).is_some_and(|bp| contains(bp, p))) + } + + /// The blank (index into `blanks`) face `f` is part of. + fn blank_of(&self, f: usize) -> Option { + let piece = self.map.faces.get(f)?.piece; + self.owner.get(piece).copied().flatten() + } +} + +/// What a face of the full map is. +#[derive(Clone, Copy, PartialEq)] +enum Place { + /// Panel `panel` of blank `blank`. + Panel { + blank: usize, + panel: usize, + }, + /// A hole of a blank. + Hole, + Outside, +} + +/// A piece of crease between two panels of one blank. +struct HingePiece { + path: PathData, + lines: Vec, +} + +struct Context<'a> { + lines: &'a [FoldLine], + pieces: &'a [Piece], + /// The fold line of each input of the Cut lines' map, in order; the gap lines come after them. + cut_lines: &'a [usize], + material: &'a Material, + full: &'a Adjacency, + tolerance: f64, +} + +impl Context<'_> { + /// The fold line that input `i` of the full map is part of; `None` for the gap lines. + fn line_of(&self, i: usize) -> Option { + self.pieces.get(i).map(|p| p.line) + } + + fn kind_of(&self, i: usize) -> LineKind { + self.line_of(i).and_then(|l| self.lines.get(l)).map_or(LineKind::Cut, |l| l.kind) + } + + fn key(&self, line: usize) -> u64 { + self.lines.get(line).map_or(0, |l| l.key) + } + + fn keys(&self, lines: impl IntoIterator) -> Vec { + lines.into_iter().map(|l| self.key(l)).collect() + } + + fn build(&self, issues: &mut Vec) -> Vec { + let mut blanks: Vec = vec![Blank::default(); self.material.blanks.len()]; + // Hole faces that share an edge are one hole (a cut line across a window splits it in two + // faces): they are grouped, and each group's faces are united. + let m = self.material; + let is_hole = |f: usize| m.hole.get(f) == Some(&true); + let mut group: Vec = (0..m.map.faces.len()).collect(); + let root = |group: &mut Vec, mut f: usize| { + while let Some(&g) = group.get(f) { + if g == f { + break; + } + let up = group.get(g).copied().unwrap_or(g); + if let Some(slot) = group.get_mut(f) { + *slot = up; + } + f = up; + } + f + }; + for e in &m.map.edges { + if let (Some(a), Some(b)) = (e.left, e.right) + && a != b + && is_hole(a) + && is_hole(b) + { + let (ra, rb) = (root(&mut group, a), root(&mut group, b)); + if let Some(slot) = group.get_mut(ra) { + *slot = rb; + } + } + } + let mut by_group: HashMap> = HashMap::new(); + for f in (0..m.map.faces.len()).filter(|&f| is_hole(f)) { + by_group.entry(root(&mut group, f)).or_default().push(f); + } + let mut groups: Vec> = by_group.into_values().collect(); + groups.sort_unstable(); + for faces in groups { + let Some(b) = faces.first().and_then(|&f| m.blank_of(f)).and_then(|b| blanks.get_mut(b)) else { continue }; + let paths: Vec<&PathData> = faces.iter().filter_map(|&f| m.map.faces.get(f).map(|x| &x.path)).collect(); + let hole = match paths.as_slice() { + [one] => (*one).clone(), + _ => unite_all(&paths.iter().map(|p| (*p, FillRule::NonZero)).collect::>()), + }; + b.holes.push(hole); + } + let places = self.places(&mut blanks); + if blanks.iter().any(|b| b.panels.len() > MAX_PANELS) { + issues.push(Issue::new(IssueCode::TooComplex, vec![], None)); + return vec![]; + } + let pieces = self.edges(&places, issues); + let hinged = self.hinges(&mut blanks, pieces, issues); + self.creases(&places, &hinged, issues); + self.slivers(issues); + self.nested(issues); + self.loose_panels(&blanks, &places, issues); + blanks + } + + /// What each face of the full map is, adding the panels to `blanks`. + fn places(&self, blanks: &mut [Blank]) -> Vec { + self.full + .faces + .iter() + .map(|face| { + let Some(c) = point_in(&face.path).and_then(|p| self.material.face_at(p)) else { return Place::Outside }; + let Some(blank) = self.material.blank_of(c) else { return Place::Outside }; + if self.material.material.get(c) == Some(&true) { + let Some(b) = blanks.get_mut(blank) else { return Place::Outside }; + b.panels.push(Panel { outline: face.path.clone(), area: face.area }); + Place::Panel { blank, panel: b.panels.len() - 1 } + } else if self.material.hole.get(c) == Some(&true) { + Place::Hole + } else { + Place::Outside + } + }) + .collect() + } + + fn place(&self, places: &[Place], f: Option) -> Place { + f.and_then(|f| places.get(f)).copied().unwrap_or(Place::Outside) + } + + /// Overlaps, dangling creases and creases in holes, from the full map's edges → the hinge + /// pieces, by (blank, panel, panel). + fn edges(&self, places: &[Place], issues: &mut Vec) -> Vec<((usize, usize, usize), HingePiece)> { + let mut pieces = vec![]; + let mut seen: HashSet<(IssueCode, Vec)> = HashSet::new(); + let mut report = |issues: &mut Vec, code: IssueCode, keys: Vec| { + let issue = Issue::new(code, keys, None); + if seen.insert((code, issue.keys.clone())) { + issues.push(issue); + } + }; + for e in &self.full.edges { + let cut = e.sources.iter().any(|&s| self.kind_of(s) == LineKind::Cut); + let creases: Vec = e.sources.iter().filter(|&&s| self.kind_of(s) != LineKind::Cut).filter_map(|&s| self.line_of(s)).collect(); + let mut by_line: Vec = e.sources.iter().filter_map(|&s| self.line_of(s)).collect(); + by_line.sort_unstable(); + by_line.dedup(); + if cut && !creases.is_empty() { + report(issues, IssueCode::CutOverCrease, self.keys(by_line.iter().copied())); + continue; + } + // Two subpaths of one kind on the same edge, from two lines or from one line's own + // subpaths (a compound path); the gap lines are left out. + let drawn: Vec = e.sources.iter().copied().filter(|&s| self.line_of(s).is_some()).collect(); + let mut duplicates: Vec = drawn + .iter() + .filter(|&&s| drawn.iter().any(|&o| o != s && self.kind_of(o) == self.kind_of(s))) + .filter_map(|&s| self.line_of(s)) + .collect(); + duplicates.sort_unstable(); + duplicates.dedup(); + if !duplicates.is_empty() { + report(issues, IssueCode::Duplicate, self.keys(duplicates)); + } + if creases.is_empty() { + continue; + } + match (self.place(places, e.left), self.place(places, e.right)) { + (Place::Panel { blank, panel: a }, Place::Panel { blank: other, panel: b }) if blank == other && a != b => { + pieces.push(((blank, a.min(b), a.max(b)), HingePiece { path: e.path.clone(), lines: creases })); + } + (Place::Panel { .. }, Place::Panel { .. }) if e.left == e.right => { + report(issues, IssueCode::DanglingCrease, self.keys(creases)); + } + (Place::Hole, _) | (_, Place::Hole) => report(issues, IssueCode::Ambiguous, self.keys(creases)), + _ => {} + } + } + pieces + } + + /// The hinges `pieces` make, added to `blanks` → the lines with a hinge. + fn hinges(&self, blanks: &mut [Blank], mut pieces: Vec<((usize, usize, usize), HingePiece)>, issues: &mut Vec) -> Vec { + pieces.sort_by_key(|p| p.0); + let mut hinged = vec![]; + let mut start = 0; + while start < pieces.len() { + let pair = pieces.get(start).map(|p| p.0); + let end = pieces.iter().skip(start).position(|p| Some(p.0) != pair).map_or(pieces.len(), |n| start + n); + let group: Vec<&HingePiece> = pieces.get(start..end).unwrap_or_default().iter().map(|p| &p.1).collect(); + start = end; + let Some((blank, a, b)) = pair else { break }; + let lines: Vec = group.iter().flat_map(|p| p.lines.iter().copied()).collect(); + match self.hinge(&group, a, b) { + Some(h) => { + if !h.straight { + issues.push(Issue::new(IssueCode::NotStraight, h.keys.clone(), None)); + } + hinged.extend(lines); + if let Some(bl) = blanks.get_mut(blank) { + bl.hinges.push(h); + } + } + None => issues.push(Issue::new(IssueCode::NoSplit, self.keys(lines.iter().copied()), None)), + } + } + hinged.sort_unstable(); + hinged.dedup(); + hinged + } + + /// The hinge between panels `a` and `b` made of `group`, along its longest piece; `None` when + /// its pieces are shorter than the tolerance in all, or span less than it. + fn hinge(&self, group: &[&HingePiece], a: usize, b: usize) -> Option { + let chord = |p: &HingePiece| { + let sp = p.path.subpaths.first()?; + Some((sp.anchors.first()?.p, sp.anchors.last()?.p)) + }; + let longest = group.iter().filter_map(|p| Some((*p, chord(p)?))).max_by(|x, y| { + let (lx, ly) = (x.1.0.distance(x.1.1), y.1.0.distance(y.1.1)); + lx.total_cmp(&ly) + })?; + let (p0, p1) = longest.1; + let len = p0.distance(p1); + // The longest piece only sets the direction; the length check is on the whole hinge below. + if len.is_nan() || len <= 1e-9 { + return None; + } + let d = (p1 - p0) / len; + let off = |p: Point| ((p - p0).cross(d)).abs(); + let mut straight = true; + let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY); + for p in group { + for seg in p.path.to_bezpath().segments() { + for t in [0.0, 0.25, 0.5, 0.75, 1.0] { + let q = seg.eval(t); + straight &= off(q) <= self.tolerance; + let s = (q - p0).dot(d); + lo = lo.min(s); + hi = hi.max(s); + } + } + } + // The pieces' own length, not the span from the first to the last, which takes in the gaps + // between pieces that lie apart. + let length: f64 = group.iter().map(|p| p.path.to_bezpath().segments().map(|s| s.arclen(1e-3)).sum::()).sum(); + if !(lo.is_finite() && hi.is_finite()) || hi - lo < self.tolerance || length.is_nan() || length < self.tolerance { + return None; + } + let mut lines: Vec = group.iter().flat_map(|p| p.lines.iter().copied()).collect(); + lines.sort_unstable(); + lines.dedup(); + let angle = longest + .0 + .lines + .first() + .and_then(|&l| self.lines.get(l)) + .map(|l| l.angle.filter(|a| a.is_finite()).unwrap_or_else(|| l.kind.default_angle())) + .unwrap_or(90.0); + let mut keys = self.keys(lines); + keys.sort_unstable(); + keys.dedup(); + Some(Hinge { a, b, from: p0 + d * lo, to: p0 + d * hi, angle, keys, straight }) + } + + /// Creases with no hinge: outside every blank, or dividing no two panels. + fn creases(&self, places: &[Place], hinged: &[usize], issues: &mut Vec) { + let named: HashSet = + issues.iter().filter(|i| i.code != IssueCode::LooseEnd && i.code != IssueCode::Gap).flat_map(|i| i.keys.iter().copied()).collect(); + // Whether each line is drawn (has a usable subpath), and whether one of its edges touches a + // panel. + let mut drawn = vec![false; self.lines.len()]; + for p in self.pieces { + if let Some(d) = drawn.get_mut(p.line) { + *d = true; + } + } + let mut on_panel = vec![false; self.lines.len()]; + for e in &self.full.edges { + if [e.left, e.right].into_iter().any(|f| matches!(self.place(places, f), Place::Panel { .. })) { + for line in e.sources.iter().filter_map(|&s| self.line_of(s)) { + if let Some(on) = on_panel.get_mut(line) { + *on = true; + } + } + } + } + for (line, l) in self.lines.iter().enumerate() { + if l.kind == LineKind::Cut || hinged.binary_search(&line).is_ok() || named.contains(&l.key) || drawn.get(line) != Some(&true) { + continue; + } + let code = if on_panel.get(line) == Some(&true) { IssueCode::NoSplit } else { IssueCode::Outside }; + issues.push(Issue::new(code, vec![l.key], None)); + } + } + + /// Slivers of the full map inside a blank. + fn slivers(&self, issues: &mut Vec) { + for s in &self.full.slivers { + let Some(p) = point_in(s) else { continue }; + if self.material.in_a_blank(p) { + issues.push(Issue::new(IssueCode::Sliver, vec![], Some(p))); + } + } + } + + /// Blanks that lie inside a hole of another blank. + fn nested(&self, issues: &mut Vec) { + let m = self.material; + for (bi, &piece) in m.blanks.iter().enumerate() { + let faces = m.faces_by_piece.get(piece).map(Vec::as_slice).unwrap_or_default(); + let Some(p) = faces.iter().find(|&&f| m.material.get(f) == Some(&true)).and_then(|&f| m.points.get(f).copied().flatten()) else { + continue; + }; + let in_hole = + m.face_cells.near(p, 0.0).into_iter().any(|f| { + m.hole.get(f) == Some(&true) && m.blank_of(f).is_some_and(|b| b != bi) && m.outer.get(f).is_some_and(|bp| contains(bp, p)) + }); + if in_hole { + let edges = m.edges_by_piece.get(piece).map(Vec::as_slice).unwrap_or_default(); + let lines = edges.iter().filter_map(|&e| m.map.edges.get(e)).flat_map(|e| e.sources.iter().filter_map(|&s| self.cut_lines.get(s))); + issues.push(Issue::new(IssueCode::Ambiguous, self.keys(lines.copied()), Some(p))); + } + } + } + + /// Panels joined to their blank's base panel (the largest; on a tie, the one whose inside point is + /// highest on the page, then leftmost) by no chain of hinges. + fn loose_panels(&self, blanks: &[Blank], places: &[Place], issues: &mut Vec) { + // The edges beside each panel, by (blank, panel), gathered once. + let mut beside: HashMap<(usize, usize), Vec> = HashMap::new(); + for (i, e) in self.full.edges.iter().enumerate() { + for f in [e.left, e.right] { + if let Place::Panel { blank, panel } = self.place(places, f) { + let list = beside.entry((blank, panel)).or_default(); + if list.last() != Some(&i) { + list.push(i); + } + } + } + } + for (bi, b) in blanks.iter().enumerate() { + let Some(base) = base_panel(&b.panels) else { continue }; + let mut reached = vec![false; b.panels.len()]; + let mut queue = vec![base]; + if let Some(r) = reached.get_mut(base) { + *r = true; + } + while let Some(p) = queue.pop() { + for h in b.hinges.iter().filter(|h| h.a == p || h.b == p) { + let other = if h.a == p { h.b } else { h.a }; + if let Some(r) = reached.get_mut(other).filter(|r| !**r) { + *r = true; + queue.push(other); + } + } + } + for (pi, panel) in b.panels.iter().enumerate().filter(|(i, _)| reached.get(*i) == Some(&false)) { + let edges = beside.get(&(bi, pi)).map(Vec::as_slice).unwrap_or_default(); + let lines = edges.iter().filter_map(|&e| self.full.edges.get(e)); + let keys = lines.flat_map(|e| e.sources.iter().filter_map(|&s| self.line_of(s))).map(|l| self.key(l)).collect(); + issues.push(Issue::new(IssueCode::LoosePanel, keys, point_in(&panel.outline))); + } + } + } +} + +/// The base panel of `panels`: the largest by area; panels whose areas differ by less than 1e-9 of +/// the larger tie, and the tie goes to the one whose inside point is highest on the page, then +/// leftmost. +pub fn base_panel(panels: &[Panel]) -> Option { + let top = panels.iter().map(|p| p.area).fold(f64::NEG_INFINITY, f64::max); + if !top.is_finite() { + return None; + } + panels + .iter() + .enumerate() + .filter(|(_, p)| top - p.area <= 1e-9 * top.abs()) + .filter_map(|(i, p)| Some((i, point_in(&p.outline)?))) + .min_by(|a, b| a.1.y.total_cmp(&b.1.y).then(a.1.x.total_cmp(&b.1.x))) + .map(|(i, _)| i) +} + +#[cfg(test)] +mod tests; diff --git a/crates/three-d/src/fold/tests.rs b/crates/three-d/src/fold/tests.rs new file mode 100644 index 0000000000..a3f2c68d37 --- /dev/null +++ b/crates/three-d/src/fold/tests.rs @@ -0,0 +1,740 @@ +use super::*; +use proptest::prelude::*; +use vectorcraft_geom::Rect; + +const TOL: f64 = 0.1; + +fn p(x: f64, y: f64) -> Point { + Point::new(x, y) +} + +fn poly(points: &[(f64, f64)], closed: bool) -> PathData { + PathData::single(SubPath::polyline(&points.iter().map(|&(x, y)| p(x, y)).collect::>(), closed)) +} + +fn line(kind: LineKind, points: &[(f64, f64)], closed: bool, key: u64) -> FoldLine { + FoldLine { path: poly(points, closed), kind, angle: None, key } +} + +fn cut(points: &[(f64, f64)], key: u64) -> FoldLine { + line(LineKind::Cut, points, true, key) +} + +fn crease(a: (f64, f64), b: (f64, f64), key: u64) -> FoldLine { + line(LineKind::Crease, &[a, b], false, key) +} + +fn codes(issues: &[Issue]) -> Vec<&'static str> { + issues.iter().map(|i| i.code.id()).collect() +} + +fn areas(b: &Blank) -> Vec { + let mut a: Vec = b.panels.iter().map(|p| (p.area * 1000.0).round() as i64).collect(); + a.sort_unstable(); + a +} + +/// A tray: a 100 × 60 base with a 30 pt wall on each side, drawn as one closed cross, and the four +/// creases round the base (keys 10 to 13). +fn tray() -> Vec { + vec![ + cut( + &[ + (30.0, 0.0), + (130.0, 0.0), + (130.0, 30.0), + (160.0, 30.0), + (160.0, 90.0), + (130.0, 90.0), + (130.0, 120.0), + (30.0, 120.0), + (30.0, 90.0), + (0.0, 90.0), + (0.0, 30.0), + (30.0, 30.0), + ], + 1, + ), + crease((30.0, 30.0), (130.0, 30.0), 10), + crease((130.0, 30.0), (130.0, 90.0), 11), + crease((130.0, 90.0), (30.0, 90.0), 12), + crease((30.0, 90.0), (30.0, 30.0), 13), + ] +} + +/// The outline of a slotted box in the style of FEFCO 0201 (glue flap, four body panels 100, 60, +/// 100 and 60 wide and 80 high, 30 pt flaps top and bottom) with its 4 pt slots drawn as notches. +const NOTCHED: [(f64, f64); 30] = [ + (20.0, 0.0), + (118.0, 0.0), + (118.0, 30.0), + (122.0, 30.0), + (122.0, 0.0), + (178.0, 0.0), + (178.0, 30.0), + (182.0, 30.0), + (182.0, 0.0), + (278.0, 0.0), + (278.0, 30.0), + (282.0, 30.0), + (282.0, 0.0), + (340.0, 0.0), + (340.0, 140.0), + (282.0, 140.0), + (282.0, 110.0), + (278.0, 110.0), + (278.0, 140.0), + (182.0, 140.0), + (182.0, 110.0), + (178.0, 110.0), + (178.0, 140.0), + (122.0, 140.0), + (122.0, 110.0), + (118.0, 110.0), + (118.0, 140.0), + (20.0, 140.0), + (20.0, 110.0), + (0.0, 110.0), +]; + +/// The slotted box's creases: the glue flap's and the body panels' (vertical), and the flaps' +/// (horizontal, from slot to slot). +fn box_creases() -> Vec { + let mut out = vec![]; + for (k, x) in [20.0, 120.0, 180.0, 280.0].into_iter().enumerate() { + out.push(crease((x, 30.0), (x, 110.0), 100 + k as u64)); + } + for (k, (x0, x1)) in [(20.0, 118.0), (122.0, 178.0), (182.0, 278.0), (282.0, 340.0)].into_iter().enumerate() { + out.push(crease((x0, 30.0), (x1, 30.0), 110 + k as u64)); + out.push(crease((x0, 110.0), (x1, 110.0), 120 + k as u64)); + } + out +} + +fn notched_box() -> Vec { + let mut outline: Vec<(f64, f64)> = NOTCHED.to_vec(); + outline.extend([(0.0, 30.0), (20.0, 30.0)]); + let mut lines = vec![cut(&outline, 1)]; + lines.extend(box_creases()); + lines +} + +fn check(lines: &[FoldLine]) -> (Vec, Vec) { + blanks(lines, TOL) +} + +#[test] +fn a_tray_has_a_base_four_walls_and_four_hinges() { + let (b, issues) = check(&tray()); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(b.len(), 1); + assert_eq!(areas(&b[0]), vec![1_800_000, 1_800_000, 3_000_000, 3_000_000, 6_000_000]); + assert_eq!(b[0].hinges.len(), 4); + for h in &b[0].hinges { + assert!(h.straight && h.angle == 90.0 && h.keys.len() == 1, "{h:?}"); + assert!((h.from.distance(h.to) - if h.keys[0] % 2 == 0 { 100.0 } else { 60.0 }).abs() < 1e-6, "{h:?}"); + } + assert_eq!(base_panel(&b[0].panels).map(|i| (b[0].panels[i].area).round()), Some(6000.0)); +} + +#[test] +fn a_slotted_box_gives_the_same_panels_however_its_slots_and_outline_are_drawn() { + let (notched, issues) = check(¬ched_box()); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(notched.len(), 1); + assert_eq!(notched[0].panels.len(), 13, "glue flap, four body panels, eight flaps"); + assert_eq!(notched[0].hinges.len(), 12); + assert!(notched[0].holes.is_empty()); + + // The slots as rectangles across a plain outline. + let mut across = + vec![cut(&[(20.0, 0.0), (340.0, 0.0), (340.0, 140.0), (20.0, 140.0), (20.0, 110.0), (0.0, 110.0), (0.0, 30.0), (20.0, 30.0)], 1)]; + for (k, x) in [120.0, 180.0, 280.0].into_iter().enumerate() { + across.push(cut(&[(x - 2.0, -5.0), (x + 2.0, -5.0), (x + 2.0, 30.0), (x - 2.0, 30.0)], 2 + k as u64)); + across.push(cut(&[(x - 2.0, 110.0), (x + 2.0, 110.0), (x + 2.0, 145.0), (x - 2.0, 145.0)], 5 + k as u64)); + } + across.extend(box_creases()); + let (b, issues) = check(&across); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(b.len(), 1); + assert_eq!(areas(&b[0]), areas(¬ched[0])); + assert_eq!(b[0].hinges.len(), 12); + + // The notched outline as four open paths, end to end. + let mut outline: Vec<(f64, f64)> = NOTCHED.to_vec(); + outline.extend([(0.0, 30.0), (20.0, 30.0), (20.0, 0.0)]); + let mut open: Vec = + [0..9, 8..17, 16..25, 24..33].into_iter().enumerate().map(|(k, r)| line(LineKind::Cut, &outline[r], false, 1 + k as u64)).collect(); + open.extend(box_creases()); + let (b, issues) = check(&open); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(areas(&b[0]), areas(¬ched[0])); + assert_eq!(b[0].hinges.len(), 12); + + // Input order does not change the result. + let mut reversed = notched_box(); + reversed.reverse(); + let (b, _) = check(&reversed); + assert_eq!(areas(&b[0]), areas(¬ched[0])); +} + +#[test] +fn a_round_tuck_flap_folds_like_any_panel() { + let mut bp = BezPath::new(); + bp.move_to(p(0.0, 40.0)); + bp.line_to(p(0.0, 140.0)); + bp.line_to(p(100.0, 140.0)); + bp.line_to(p(100.0, 40.0)); + bp.curve_to(p(100.0, 10.0), p(80.0, 0.0), p(50.0, 0.0)); + bp.curve_to(p(20.0, 0.0), p(0.0, 10.0), p(0.0, 40.0)); + bp.close_path(); + let lines = vec![FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Cut, angle: None, key: 1 }, crease((0.0, 40.0), (100.0, 40.0), 2)]; + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(b[0].panels.len(), 2); + assert_eq!(b[0].hinges.len(), 1); +} + +#[test] +fn a_window_is_a_hole_in_its_panel() { + let mut lines = tray(); + lines.push(cut(&[(60.0, 45.0), (100.0, 45.0), (100.0, 75.0), (60.0, 75.0)], 2)); + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(b[0].holes.len(), 1); + assert_eq!(areas(&b[0]), vec![1_800_000, 1_800_000, 3_000_000, 3_000_000, 4_800_000]); +} + +/// The tray's outline as one open path whose end stops `short` before its start. +fn tray_with_gap(short: f64) -> Vec { + let mut lines = tray(); + lines[0] = line( + LineKind::Cut, + &[ + (30.0 + short, 0.0), + (130.0, 0.0), + (130.0, 30.0), + (160.0, 30.0), + (160.0, 90.0), + (130.0, 90.0), + (130.0, 120.0), + (30.0, 120.0), + (30.0, 90.0), + (0.0, 90.0), + (0.0, 30.0), + (30.0, 30.0), + (30.0, 0.0), + ], + false, + 1, + ); + lines +} + +#[test] +fn a_gap_within_the_tolerance_is_closed_and_one_past_it_is_a_loose_end() { + let (closed, _) = check(&tray()); + let (b, issues) = check(&tray_with_gap(0.05)); + assert_eq!(codes(&issues), vec!["gap"], "{issues:?}"); + assert_eq!(issues[0].keys, vec![1]); + assert_eq!(areas(&b[0]), areas(&closed[0])); + assert_eq!(b[0].hinges.len(), 4); + // The tolerance boundary. + let (_, issues) = blanks(&tray_with_gap(0.05), 0.06); + assert_eq!(codes(&issues), vec!["gap"]); + let (b, issues) = blanks(&tray_with_gap(0.05), 0.04); + assert!(codes(&issues).starts_with(&["open", "looseEnd", "looseEnd"]) || codes(&issues).starts_with(&["looseEnd"]), "{issues:?}"); + assert!(issues.iter().any(|i| i.code == IssueCode::LooseEnd && i.at.is_some_and(|a| a.distance(p(30.05, 0.0)) < 1e-9)), "{issues:?}"); + assert!(b.iter().all(|b| b.panels.len() < 5), "the outline does not close"); +} + +#[test] +fn no_cut_lines_or_no_enclosed_area_build_nothing() { + let (b, issues) = check(&[crease((0.0, 0.0), (10.0, 0.0), 1)]); + assert!(b.is_empty()); + assert_eq!(codes(&issues), vec!["noCut"]); + let (b, issues) = check(&[]); + assert!(b.is_empty()); + assert_eq!(codes(&issues), vec!["noCut"]); + let (b, issues) = check(&[line(LineKind::Cut, &[(0.0, 0.0), (50.0, 0.0), (50.0, 50.0)], false, 1)]); + assert!(b.is_empty()); + assert!(codes(&issues).contains(&"open") && codes(&issues).contains(&"looseEnd"), "{issues:?}"); + // A non-finite line is left out. + let mut lines = tray(); + lines.push(line(LineKind::Crease, &[(0.0, 0.0), (f64::NAN, 1.0)], false, 9)); + let (b, issues) = check(&lines); + assert!(issues.is_empty() && b[0].panels.len() == 5, "{issues:?}"); +} + +#[test] +fn a_cut_end_inside_the_blank_is_a_loose_end() { + let mut lines = tray(); + lines.push(line(LineKind::Cut, &[(80.0, 0.0), (80.0, 20.0)], false, 2)); + let (b, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["looseEnd"], "{issues:?}"); + assert_eq!((issues[0].keys.clone(), issues[0].at), (vec![2], Some(p(80.0, 20.0)))); + assert_eq!(b[0].panels.len(), 5, "a cut into a wall does not divide it"); + // A slit that ends on a crease is not loose: it cuts the wall in two. + let mut lines = tray(); + lines.push(line(LineKind::Cut, &[(80.0, 0.0), (80.0, 30.0)], false, 2)); + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!((b[0].panels.len(), b[0].hinges.len()), (6, 5)); +} + +#[test] +fn a_cut_line_that_comes_back_through_its_own_end_meets_it() { + // From (80, 10) out to (90, 20), then back through (80, 10) to the outline at (70, 0): the + // start lies on the line's own second segment, so it is not loose. + let mut lines = tray(); + lines.push(line(LineKind::Cut, &[(80.0, 10.0), (90.0, 20.0), (70.0, 0.0)], false, 2)); + let (_, issues) = check(&lines); + assert!(!codes(&issues).contains(&"looseEnd"), "{issues:?}"); + // A first segment shorter than the tolerance does not make the second one meet the end. + let mut lines = tray(); + lines.push(line(LineKind::Cut, &[(90.0, 25.0), (90.05, 25.0), (80.0, 20.0), (80.0, 0.0)], false, 2)); + let (_, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["looseEnd"], "{issues:?}"); + assert_eq!(issues[0].at, Some(p(90.0, 25.0))); +} + +#[test] +fn two_outlines_joined_by_a_cut_line_are_both_material() { + let lines = vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1), + cut(&[(150.0, 0.0), (180.0, 0.0), (180.0, 30.0), (150.0, 30.0)], 2), + line(LineKind::Cut, &[(100.0, 10.0), (150.0, 10.0)], false, 3), + ]; + let (b, issues) = check(&lines); + assert_eq!(b.len(), 1, "one connected piece"); + assert_eq!(areas(&b[0]), vec![900_000, 10_000_000], "{issues:?}"); + assert!(b[0].holes.is_empty()); + // A slot drawn across the outline is still cut out, not made material where it sticks out. + let lines = + vec![cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1), cut(&[(48.0, -10.0), (52.0, -10.0), (52.0, 20.0), (48.0, 20.0)], 2)]; + let (b, _) = check(&lines); + assert_eq!(b.len(), 1); + assert_eq!(areas(&b[0]), vec![10_000_000 - 80_000]); + // The same slot drawn as four open lines end to end, one of them backwards. + let slot = [(48.0, -10.0), (52.0, -10.0), (52.0, 20.0), (48.0, 20.0)]; + let mut lines = vec![cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1)]; + lines.push(line(LineKind::Cut, &[slot[0], slot[1]], false, 2)); + lines.push(line(LineKind::Cut, &[slot[2], slot[1]], false, 3)); + lines.push(line(LineKind::Cut, &[slot[2], slot[3]], false, 4)); + lines.push(line(LineKind::Cut, &[slot[3], slot[0]], false, 5)); + let (b, issues) = check(&lines); + assert_eq!(b.len(), 1, "{issues:?}"); + assert_eq!(areas(&b[0]), vec![10_000_000 - 80_000]); + // And with a gap within the tolerance at one corner. + lines[4] = line(LineKind::Cut, &[slot[3], (48.0, -9.95)], false, 5); + let (b, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["gap"], "{issues:?}"); + assert_eq!(b.len(), 1); + assert_eq!(areas(&b[0]), vec![10_000_000 - 80_000]); + // A slot right across the blank, with no corner inside the outline and no outline corner + // inside the slot, cuts it in two. + let lines = vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1), + cut(&[(10.0, -210.0), (20.0, -210.0), (20.0, 110.0), (10.0, 110.0)], 2), + ]; + let (b, _) = check(&lines); + assert_eq!(b.len(), 1); + assert_eq!(areas(&b[0]), vec![1_000_000, 8_000_000]); +} + +#[test] +fn an_outline_drawn_twice_keeps_its_material() { + let square = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]; + let (b, issues) = check(&[cut(&square, 1), cut(&square, 2)]); + assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}"); + assert_eq!(issues[0].keys, vec![1, 2]); + assert_eq!(b.len(), 1); + assert_eq!(areas(&b[0]), vec![10_000_000]); + // The same two squares as the subpaths of one compound path. + let mut twice = poly(&square, true); + twice.subpaths.extend(poly(&square, true).subpaths); + let (b, issues) = check(&[FoldLine { path: twice, kind: LineKind::Cut, angle: None, key: 1 }]); + assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}"); + assert_eq!(issues[0].keys, vec![1]); + assert_eq!(areas(&b[0]), vec![10_000_000]); +} + +#[test] +fn a_large_tolerance_still_closes_nearly_touching_ends_and_short_outlines() { + // Ends 0.0005 apart, closer than 1/10,000 of the tolerance. + let nearly = line(LineKind::Cut, &[(0.0005, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0), (0.0, 0.0)], false, 1); + let (b, issues) = blanks(&[nearly], 10.0); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(areas(&b[0]), vec![10_000_000]); + // An outline shorter than the tolerance, 0.05 pt open: a gap, and no loose end. + let short = line(LineKind::Cut, &[(0.05, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (0.0, 0.0)], false, 1); + let (b, issues) = blanks(&[short], 10.0); + assert_eq!(codes(&issues), vec!["gap"], "{issues:?}"); + assert_eq!(areas(&b[0]), vec![1000]); +} + +#[test] +fn a_lookup_wider_than_the_occupied_cells_reads_only_those_cells() { + // Two points 1e-9 apart make cells about 2.4e-13 wide: a lookup 1e-6 around one spans some + // 10^14 cells, and finds both points by reading the two cells that hold them. + let cells = Cells::new(vec![(Rect::from_points(p(0.0, 0.0), p(0.0, 0.0)), 1), (Rect::from_points(p(1e-9, 0.0), p(1e-9, 0.0)), 2)], 0.0, 4096.0); + assert_eq!(cells.near(p(0.0, 0.0), 1e-6), vec![1, 2]); + assert_eq!(cells.near(p(5.0, 5.0), 1e-6), Vec::::new()); + // A square open by 0.0000011 pt at a 10 pt tolerance. + let square = line(LineKind::Cut, &[(0.0000011, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (0.0, 0.0)], false, 1); + let (b, issues) = blanks(&[square], 10.0); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(b.len(), 1); +} + +#[test] +fn a_window_of_open_lines_with_a_slit_to_its_corner_is_still_a_hole() { + let outline = cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1); + let window = [(40.0, 40.0), (60.0, 40.0), (60.0, 60.0), (40.0, 60.0)]; + let slit = line(LineKind::Cut, &[(40.0, 0.0), (40.0, 40.0)], false, 2); + let (closed, issues) = check(&[outline.clone(), slit.clone(), cut(&window, 3)]); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!((closed[0].holes.len(), areas(&closed[0])), (1, vec![10_000_000 - 400_000])); + let mut lines = vec![outline, slit]; + for k in 0..4 { + lines.push(line(LineKind::Cut, &[window[k], window[(k + 1) % 4]], false, 3 + k as u64)); + } + let (open, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!((open[0].holes.len(), areas(&open[0])), (1, areas(&closed[0]))); + // The outline as four open lines too, the slit from its corner to the window's. + let corners = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]; + let mut lines: Vec = (0..4).map(|k| line(LineKind::Cut, &[corners[k], corners[(k + 1) % 4]], false, 10 + k as u64)).collect(); + lines.push(line(LineKind::Cut, &[(0.0, 0.0), (40.0, 40.0)], false, 2)); + for k in 0..4 { + lines.push(line(LineKind::Cut, &[window[k], window[(k + 1) % 4]], false, 3 + k as u64)); + } + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!((b[0].holes.len(), areas(&b[0])), (1, areas(&closed[0]))); +} + +#[test] +fn a_grid_of_many_touching_outlines_is_classified_without_comparing_every_pair() { + // 100 × 100 touching squares, each its own closed outline: one piece of 10,000 panels. + let mut lines = vec![]; + for i in 0..100u64 { + for j in 0..100u64 { + let (x, y) = (10.0 * i as f64, 10.0 * j as f64); + lines.push(cut(&[(x, y), (x + 10.0, y), (x + 10.0, y + 10.0), (x, y + 10.0)], 100 * i + j)); + } + } + let (b, issues) = check(&lines); + assert!(b.is_empty()); + assert!(codes(&issues).contains(&"tooComplex"), "{issues:?}"); +} + +#[test] +fn open_cut_lines_far_from_the_origin_are_checked_without_overflow() { + let lines = [ + line(LineKind::Cut, &[(1e13, 0.0), (1e13 + 4096.0, 0.0), (1e13 + 4096.0, 4096.0)], false, 1), + line(LineKind::Cut, &[(1e13 + 4096.0, 4096.0), (1e13, 4096.0), (1e13, 0.0)], false, 2), + ]; + let (b, issues) = check(&lines); + assert!(b.len() <= 1, "{issues:?}"); +} + +#[test] +fn a_blank_in_the_hole_of_a_narrow_ring_is_a_blank_of_its_own() { + // The ring's own area (1,900) is less than the hole's (8,100), but the square lies in the hole. + let lines = vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1), + cut(&[(5.0, 5.0), (95.0, 5.0), (95.0, 95.0), (5.0, 95.0)], 2), + cut(&[(40.0, 40.0), (60.0, 40.0), (60.0, 60.0), (40.0, 60.0)], 3), + ]; + let (b, issues) = check(&lines); + assert_eq!(b.len(), 2, "{issues:?}"); + assert_eq!(codes(&issues), vec!["ambiguous"], "{issues:?}"); + assert_eq!(issues[0].keys, vec![3]); +} + +#[test] +fn too_many_segments_are_refused_before_the_lines_are_copied() { + // Many lines that together pass the limit by one segment. + let each: Vec<(f64, f64)> = (0..=64).map(|i| (i as f64, 0.0)).collect(); + let lines: Vec = (0..=(MAX_SEGMENTS / 64) as u64).map(|k| line(LineKind::Cut, &each, false, k)).collect(); + assert!(lines.len() * 64 > MAX_SEGMENTS); + let (b, issues) = check(&lines); + assert!(b.is_empty()); + assert_eq!(codes(&issues), vec!["tooComplex"]); +} + +#[test] +fn many_separate_blanks_each_with_a_window_are_told_apart() { + // A 50 × 40 grid of 10 pt squares 5 pt apart, each with a 4 pt window and a crease beside it. + let mut lines = vec![]; + for i in 0..50u64 { + for j in 0..40u64 { + let (x, y) = (15.0 * i as f64, 15.0 * j as f64); + let k = 10 * (40 * i + j); + lines.push(cut(&[(x, y), (x + 10.0, y), (x + 10.0, y + 10.0), (x, y + 10.0)], k)); + lines.push(cut(&[(x + 1.0, y + 1.0), (x + 5.0, y + 1.0), (x + 5.0, y + 5.0), (x + 1.0, y + 5.0)], k + 1)); + lines.push(crease((x + 7.0, y), (x + 7.0, y + 10.0), k + 2)); + } + } + let (blanks, issues) = check(&lines); + assert!(issues.is_empty(), "{:?}", issues.first()); + assert_eq!(blanks.len(), 2000); + assert!(blanks.iter().all(|b| b.panels.len() == 2 && b.hinges.len() == 1 && b.holes.len() == 1)); +} + +#[test] +fn many_separate_cut_lines_are_checked_by_the_cells_near_each_end() { + // 2,000 short slits from the top edge of a long blank, each ending loose inside it. + let mut lines = vec![cut(&[(0.0, 0.0), (4000.0, 0.0), (4000.0, 100.0), (0.0, 100.0)], 1)]; + for i in 0..2000u64 { + let x = 1.0 + 2.0 * i as f64; + lines.push(line(LineKind::Cut, &[(x, 0.0), (x, 50.0)], false, 10 + i)); + } + let (_, issues) = check(&lines); + let loose: Vec<&Issue> = issues.iter().filter(|i| i.code == IssueCode::LooseEnd).collect(); + assert_eq!(loose.len(), 2000); + assert!(loose.iter().all(|i| i.at.is_some_and(|at| (at.y - 50.0).abs() < 1e-9))); +} + +#[test] +fn too_many_segments_or_panels_are_too_complex() { + // One point more than segments. + let mut zigzag: Vec<(f64, f64)> = (0..=MAX_SEGMENTS + 1).map(|i| (i as f64 * 0.5, (i % 2) as f64)).collect(); + let (b, issues) = check(&[line(LineKind::Cut, &zigzag, false, 1)]); + assert!(b.is_empty()); + assert_eq!(codes(&issues), vec!["tooComplex"]); + zigzag.truncate(MAX_SEGMENTS + 1); + let (_, issues) = check(&[line(LineKind::Cut, &zigzag, false, 1)]); + assert!(!codes(&issues).contains(&"tooComplex"), "at the limit"); + // A grid of 16 × 16 panels is at the panel limit; 17 × 16 is past it. + let grid = |cols: usize| { + let mut lines = vec![cut(&[(0.0, 0.0), (cols as f64 * 10.0, 0.0), (cols as f64 * 10.0, 160.0), (0.0, 160.0)], 1)]; + for i in 1..cols { + lines.push(crease((i as f64 * 10.0, 0.0), (i as f64 * 10.0, 160.0), 100 + i as u64)); + } + for j in 1..16 { + lines.push(crease((0.0, j as f64 * 10.0), (cols as f64 * 10.0, j as f64 * 10.0), 200 + j as u64)); + } + lines + }; + let (b, issues) = check(&grid(16)); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(b[0].panels.len(), MAX_PANELS); + let (b, issues) = check(&grid(17)); + assert!(b.is_empty()); + assert_eq!(codes(&issues), vec!["tooComplex"]); +} + +#[test] +fn lines_on_top_of_each_other_are_reported() { + let mut lines = tray(); + lines.push(crease((40.0, 0.0), (120.0, 0.0), 20)); + let (_, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["cutOverCrease"], "{issues:?}"); + assert_eq!(issues[0].keys, vec![1, 20]); + + let mut lines = tray(); + lines.push(crease((130.0, 30.0), (30.0, 30.0), 20)); + let (b, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}"); + assert_eq!(issues[0].keys, vec![10, 20]); + assert_eq!(b[0].hinges.len(), 4); + assert_eq!(b[0].hinges.iter().find(|h| h.keys.contains(&20)).map(|h| h.keys.clone()), Some(vec![10, 20])); +} + +#[test] +fn a_crease_that_ends_inside_a_panel_is_dangling() { + let mut lines = tray(); + lines.push(crease((80.0, 30.0), (80.0, 60.0), 20)); + let (b, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["danglingCrease"], "{issues:?}"); + assert_eq!(issues[0].keys, vec![20]); + assert_eq!(b[0].panels.len(), 5); +} + +#[test] +fn a_hinge_shorter_than_the_tolerance_divides_nothing_and_leaves_a_loose_panel() { + let lines = vec![ + cut(&[(0.0, 0.0), (50.0, 0.0), (50.0, 49.95), (100.0, 49.95), (100.0, 99.95), (50.0, 99.95), (50.0, 50.0), (0.0, 50.0)], 1), + crease((50.0, 49.95), (50.0, 50.0), 2), + ]; + let (b, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["noSplit", "loosePanel"], "{issues:?}"); + assert_eq!(issues[0].keys, vec![2]); + assert!(b[0].hinges.is_empty()); + // The same with a hinge as long as the panels: no issue. + let lines = vec![cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)], 1), crease((50.0, 0.0), (50.0, 50.0), 2)]; + let (_, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); +} + +#[test] +fn hinge_pieces_far_apart_are_measured_by_their_own_length() { + // A window leaves two 0.02 pt strips joining the halves, each crossed by a crease: 0.04 pt of + // hinge, though its pieces span 100 pt. + let lines = vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1), + cut(&[(40.0, 0.02), (60.0, 0.02), (60.0, 99.98), (40.0, 99.98)], 2), + crease((50.0, 0.0), (50.0, 0.02), 3), + crease((50.0, 99.98), (50.0, 100.0), 4), + ]; + let (b, issues) = check(&lines); + assert!(codes(&issues).contains(&"noSplit"), "{issues:?}"); + assert!(b[0].hinges.is_empty()); +} + +#[test] +fn a_window_split_by_a_cut_line_is_one_hole() { + let mut lines = + vec![cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1), cut(&[(40.0, 40.0), (60.0, 40.0), (60.0, 60.0), (40.0, 60.0)], 2)]; + lines.push(line(LineKind::Cut, &[(40.0, 50.0), (60.0, 50.0)], false, 3)); + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(b[0].holes.len(), 1); + let area = vectorcraft_pathops::area(&b[0].holes[0], FillRule::NonZero); + assert!((area - 400.0).abs() < 1e-3, "{area}"); +} + +#[test] +fn a_hinge_drawn_as_short_pieces_is_measured_whole() { + // Ten 5 pt pieces make a 50 pt hinge, longer than a 10 pt tolerance though each piece is not. + let mut lines = vec![cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)], 1)]; + for k in 0..10u64 { + let y = 5.0 * k as f64; + lines.push(crease((50.0, y), (50.0, y + 5.0), 10 + k)); + } + let (b, issues) = blanks(&lines, 10.0); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(b[0].hinges.len(), 1); + let h = &b[0].hinges[0]; + assert!((h.from.distance(h.to) - 50.0).abs() < 1e-6 && h.keys.len() == 10, "{h:?}"); +} + +#[test] +fn a_crease_outside_the_blank_is_reported() { + let mut lines = tray(); + lines.push(crease((200.0, 0.0), (250.0, 0.0), 20)); + let (_, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["outside"], "{issues:?}"); + assert_eq!(issues[0].keys, vec![20]); +} + +#[test] +fn a_bent_crease_folds_along_its_longest_piece() { + let mut lines = tray(); + lines[1] = line(LineKind::Crease, &[(30.0, 30.0), (90.0, 30.0), (130.0, 32.0)], false, 10); + lines[0] = cut( + &[ + (30.0, 0.0), + (130.0, 0.0), + (130.0, 32.0), + (160.0, 32.0), + (160.0, 90.0), + (130.0, 90.0), + (130.0, 120.0), + (30.0, 120.0), + (30.0, 90.0), + (0.0, 90.0), + (0.0, 30.0), + (30.0, 30.0), + ], + 1, + ); + lines[2] = crease((130.0, 32.0), (130.0, 90.0), 11); + let (b, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["notStraight"], "{issues:?}"); + let h = b[0].hinges.iter().find(|h| h.keys == vec![10]).unwrap(); + assert!(!h.straight); + assert!((h.from.y - 30.0).abs() < 1e-9 && (h.to.y - 30.0).abs() < 1e-9, "along the 60 pt piece: {h:?}"); + // Within the tolerance, a crease is straight. + let mut lines = tray(); + lines[1] = line(LineKind::Crease, &[(30.0, 30.0), (90.0, 30.05), (130.0, 30.0)], false, 10); + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + assert!(b[0].hinges.iter().all(|h| h.straight)); +} + +#[test] +fn a_slot_too_narrow_to_map_is_a_sliver() { + let mut lines = tray(); + lines.push(cut(&[(60.0, 45.0), (60.004, 45.0), (60.004, 75.0), (60.0, 75.0)], 2)); + let (_, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["sliver"], "{issues:?}"); + assert!(issues[0].at.is_some_and(|a| Rect::new(59.9, 44.0, 60.1, 76.0).contains(a))); +} + +#[test] +fn lines_in_a_hole_are_ambiguous() { + let mut window = tray(); + window.push(cut(&[(60.0, 45.0), (100.0, 45.0), (100.0, 75.0), (60.0, 75.0)], 2)); + let mut lines = window.clone(); + lines.push(crease((70.0, 45.0), (70.0, 75.0), 20)); + let (_, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["ambiguous"], "{issues:?}"); + assert_eq!(issues[0].keys, vec![20]); + let mut lines = window; + lines.push(cut(&[(70.0, 50.0), (90.0, 50.0), (90.0, 70.0), (70.0, 70.0)], 3)); + let (b, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["ambiguous"], "{issues:?}"); + assert_eq!(issues[0].keys, vec![3]); + assert_eq!(b.len(), 2, "the square in the window is a blank of its own"); +} + +#[test] +fn partial_cuts_fold_the_other_way_and_a_line_s_own_angle_wins() { + let mut lines = tray(); + lines[1].kind = LineKind::PartialCut; + lines[2].angle = Some(45.0); + lines[3].kind = LineKind::Perforation; + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + let angle = |key: u64| b[0].hinges.iter().find(|h| h.keys == vec![key]).map(|h| h.angle); + assert_eq!((angle(10), angle(11), angle(12), angle(13)), (Some(-90.0), Some(45.0), Some(90.0), Some(90.0))); +} + +#[test] +fn every_code_has_an_id_and_a_severity() { + let ids: Vec<&str> = IssueCode::ALL.iter().map(|c| c.id()).collect(); + assert_eq!(ids.len(), 15); + let mut unique = ids.clone(); + unique.sort_unstable(); + unique.dedup(); + assert_eq!(unique.len(), 15); + let errors: Vec<&str> = IssueCode::ALL.iter().filter(|c| c.is_error()).map(|c| c.id()).collect(); + assert_eq!(errors, vec!["noCut", "open", "looseEnd", "tooComplex", "cutOverCrease"]); + let mut sorted = IssueCode::ALL; + sorted.sort(); + assert_eq!(sorted, IssueCode::ALL, "listed in issue order"); +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(48))] + /// Random fold lines never panic, and the panels and hinges they give are consistent. + #[test] + fn random_fold_lines_give_consistent_blanks( + segs in proptest::collection::vec((0u8..4, -50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0), 1..10), + boxed in any::(), + ) { + let kinds = [LineKind::Cut, LineKind::Crease, LineKind::PartialCut, LineKind::Perforation]; + let mut lines: Vec = segs + .iter() + .enumerate() + .map(|(i, &(k, a, b, c, d))| line(kinds[usize::from(k)], &[(a, b), (c, d)], false, i as u64)) + .collect(); + if boxed { + lines.push(cut(&[(-40.0, -40.0), (40.0, -40.0), (40.0, 40.0), (-40.0, 40.0)], 99)); + } + let (blanks, issues) = blanks(&lines, TOL); + for b in &blanks { + prop_assert!(!b.panels.is_empty() && b.panels.len() <= MAX_PANELS); + for h in &b.hinges { + prop_assert!(h.a < h.b && h.b < b.panels.len()); + prop_assert!(h.from.is_finite() && h.to.is_finite()); + } + } + let mut sorted = issues.clone(); + sorted.sort_by_key(|i| i.code); + prop_assert_eq!(sorted, issues); + } +} diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index d01a8b9840..01b5c75d9f 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -6,6 +6,7 @@ //! intersecting profiles can have ambiguous visibility and are not solid modelling inputs. #![forbid(unsafe_code)] +pub mod fold; mod solid; mod visibility; pub use solid::{ diff --git a/crates/ui-egui/src/addons/packaging.rs b/crates/ui-egui/src/addons/packaging.rs index 1c70bef5d0..1e827a7efc 100644 --- a/crates/ui-egui/src/addons/packaging.rs +++ b/crates/ui-egui/src/addons/packaging.rs @@ -2,10 +2,15 @@ //! panel lists the fold line roles, each with its swatch's chip and how many of the selected objects //! have it (of the whole document while nothing is selected); clicking a role gives the selected //! paths that role (`addon.packaging.setRole`). Its menu's Role Swatches… picks the swatch that -//! carries a role (`addon.packaging.setRoleSwatch`). +//! carries a role (`addon.packaging.setRoleSwatch`). Its Check button, like the Check Fold Lines menu +//! item, checks the fold lines (`addon.packaging.check`) and lists the issues found under it, each +//! with a Select button; the list is kept until the document changes. + +use std::sync::{Arc, Weak}; use egui::{Align, Layout, Sense, Ui, vec2}; use serde_json::{Value, json}; +use vectorcraft_engine::doc::Document; use crate::VectorcraftApp; use crate::menus::Item; @@ -18,12 +23,16 @@ pub const ID: &str = "foldLines"; pub const SET_ROLE: &str = "addon.packaging.setRole"; /// The command that picks a role's swatch. pub const SET_ROLE_SWATCH: &str = "addon.packaging.setRoleSwatch"; +/// The command that checks the fold lines. +pub const CHECK: &str = "addon.packaging.check"; /// The roles by name, as `addon.packaging.setRole` and Role Swatches… take them. pub const ROLES: &[(&str, &str)] = &[("Cut Line", "cut"), ("Crease Line", "crease"), ("Partial Cut Line", "partialCut"), ("Perforation Line", "perforation")]; /// Where the panel keeps the last `addon.packaging.roles` answer (panel state). const STATE: &str = "fold-lines"; +/// Where the panel keeps the last check (panel state). +const CHECKED: &str = "fold-lines-check"; /// Object › Plug-ins › Packaging Tools. pub fn menu() -> Vec { @@ -35,9 +44,141 @@ pub fn menu() -> Vec { make("Make Crease Line", "crease"), make("Make Partial Cut Line", "partialCut"), make("Make Perforation Line", "perforation"), + Item::Sep, + Item::Cmd("Check Fold Lines", CHECK, Value::Null), ] } +/// One issue of a check: whether it is an error, its message (English) and the objects it names. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Issue { + pub error: bool, + pub message: String, + pub ids: Vec, +} + +/// The document a check was made on: its id, and its content as it was then. Selecting changes +/// neither, so the issues stay listed while their Select buttons are used. The content is held +/// weakly: it is compared, never kept alive. +type DocKey = (u64, Weak); + +/// The last check of a document. +#[derive(Clone, Debug, Default)] +pub(crate) struct Checked { + pub key: Option, + pub panels: u64, + pub hinges: u64, + pub issues: Vec, +} + +impl Checked { + /// The check `r` (an `addon.packaging.check` answer) of the document `key`. + fn of(key: DocKey, r: &Value) -> Checked { + let count = |k: &str| r[k].as_u64().unwrap_or(0); + let issues: Vec = r["issues"] + .as_array() + .into_iter() + .flatten() + .map(|i| Issue { + error: i["severity"] == "error", + message: i["message"].as_str().unwrap_or_default().to_string(), + ids: i["ids"].as_array().into_iter().flatten().filter_map(Value::as_u64).collect(), + }) + .collect(); + Checked { key: Some(key), panels: count("panels"), hinges: count("hinges"), issues } + } + + /// The summary line, in English (the status bar and the panel show it translated). + fn summary(&self) -> String { + let errors = self.issues.iter().filter(|i| i.error).count(); + crate::i18n::fmt( + "Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings}", + &[ + ("panels", &self.panels.to_string()), + ("hinges", &self.hinges.to_string()), + ("errors", &errors.to_string()), + ("warnings", &(self.issues.len() - errors).to_string()), + ], + ) + } +} + +/// The active document's [`DocKey`]. +fn doc_key(app: &VectorcraftApp) -> Option { + app.session.active().map(|st| (st.uid, Arc::downgrade(&st.doc))) +} + +/// Runs `addon.packaging.check` with `p` and shows its summary in the status bar → the check, kept +/// in `ctx` for the panel. +fn run_check(app: &mut VectorcraftApp, ctx: &egui::Context, p: Value) -> Option { + let r = app.run(CHECK, p).map_err(|e| app.status(e)).ok()?; + let checked = Checked::of(doc_key(app)?, &r); + app.status(checked.summary()); + set_pstate(ctx, CHECKED, checked.clone()); + Some(checked) +} + +/// Check Fold Lines from its menu item: checks with `p`, keeps the issues for the Fold Lines panel +/// and shows the panel. +pub(crate) fn check(app: &mut VectorcraftApp, p: Value) { + let ctx = app.ui_ctx.clone().unwrap_or_default(); + if run_check(app, &ctx, p).is_some() + && let Err(e) = crate::panel_docking::reveal_panel(app, ID) + { + app.status(e); + } +} + +/// The last check of the active document, while the document has not changed since. +fn last_check(app: &VectorcraftApp, ctx: &egui::Context) -> Option { + let checked: Checked = pstate(ctx, CHECKED); + let same = match (&checked.key, doc_key(app)) { + (Some((uid, doc)), Some((now, current))) => *uid == now && doc.ptr_eq(¤t), + _ => false, + }; + same.then_some(checked) +} + +/// The Check button, then the last check's summary and issues (errors in the error color, warnings +/// in the warning color), each with a Select button; clicking an issue selects its objects too. +fn show_check(app: &mut VectorcraftApp, ui: &mut Ui) { + widgets::divider(ui); + let width = ui.available_width(); + if widgets::flat_button(ui, tl!("Check"), width).clicked() { + run_check(app, ui.ctx(), json!({})); + } + let Some(checked) = last_check(app, ui.ctx()) else { return }; + ui.add_space(4.0); + dim_label(ui, &crate::i18n::msg(&checked.summary())); + if checked.issues.is_empty() { + dim_label(ui, tl!("No issues found.")); + } + let t = crate::theme::Tokens::get(ui.ctx()); + let mut select = None; + for (n, issue) in checked.issues.iter().enumerate() { + ui.horizontal(|ui| { + let can = !issue.ids.is_empty(); + let picked = ui + .with_layout(Layout::right_to_left(Align::Center), |ui| { + let button = ui.add_enabled_ui(can, |ui| widgets::flat_button(ui, tl!("Select"), 56.0)).inner; + let text = egui::RichText::new(crate::i18n::msg(&issue.message)).color(if issue.error { t.error } else { t.warning }); + let row = + ui.with_layout(Layout::left_to_right(Align::Center), |ui| ui.add(egui::Label::new(text).sense(Sense::click()).wrap())).inner; + button.clicked() || (row.clicked() && can) + }) + .inner; + if picked { + select = Some(n); + } + }); + } + if let Some(issue) = select.and_then(|n| checked.issues.get(n)) + && let Err(e) = app.run("select.set", json!({ "ids": issue.ids })) + { + app.status(e); + } +} + /// One role row: (role id, swatch name, the swatch's paint if the document has it, count). type Row = (String, String, Option, u64); @@ -103,6 +244,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { { app.status(e); } + show_check(app, ui); } /// Role Swatches… (the dialog of `addon.packaging.setRoleSwatch`): when another role is picked, its diff --git a/crates/ui-egui/src/addons/packaging/tests.rs b/crates/ui-egui/src/addons/packaging/tests.rs index cfe9909dc8..808956e4d7 100644 --- a/crates/ui-egui/src/addons/packaging/tests.rs +++ b/crates/ui-egui/src/addons/packaging/tests.rs @@ -1,7 +1,7 @@ use serde_json::json; use vectorcraft_engine::Session; -use super::{ID, ROLES, SET_ROLE, SET_ROLE_SWATCH, show}; +use super::{CHECK, ID, ROLES, SET_ROLE, SET_ROLE_SWATCH, show}; use crate::tests_labels::painted_text; use crate::{VectorcraftApp, menus}; @@ -125,6 +125,137 @@ fn role_swatches_shows_the_swatch_of_the_role_picked() { assert_eq!(crate::dialogs::form::params(&d), json!({"role": "crease", "swatch": "Ink"}), "the dialog sends no __role"); } +/// An app with a square blank cut on its outline, a crease across it and a cut line that stops +/// inside it, nothing selected → (app, the cut line that stops). +fn blank() -> (VectorcraftApp, u64) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let path = |app: &mut VectorcraftApp, d: &str| app.run("path.create", json!({ "d": d })).unwrap()["id"].as_u64().unwrap(); + let outline = path(&mut app, "M50 50 L250 50 L250 250 L50 250 Z"); + let crease = path(&mut app, "M50 150 L250 150"); + let slit = path(&mut app, "M100 50 L100 100"); + app.run(SET_ROLE, json!({"role": "cut", "ids": [outline, slit]})).unwrap(); + app.run(SET_ROLE, json!({"role": "crease", "ids": [crease]})).unwrap(); + app.run("select.none", json!({})).unwrap(); + (app, slit) +} + +/// Frames of the panel in one context, the pointer clicking the middle of the element that screen +/// readers name `click` (egui finds what the pointer is over from the frame before, so the move +/// gets a frame of its own) → the text the last frame painted. +fn frames(app: &mut VectorcraftApp, ctx: &egui::Context, click: Option<&str>) -> String { + ctx.enable_accesskit(); + crate::theme::install_fonts(ctx); + // The context's clock runs on from its last frame: egui requires time to move forward. + let mut time = ctx.input(|i| i.time); + let mut frame = |app: &mut VectorcraftApp, events: Vec| { + time += 0.1; + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(320.0, 480.0)); + let input = egui::RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| show(app, ui)); + out.textures_delta.clear(); + out + }; + frame(app, vec![]); + let out = frame(app, vec![]); + let Some(label) = click else { return crate::tests_labels::shapes_text(&out) }; + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + // A button carries its text as its name, a label as its value. + let node = nodes.iter().find(|(_, n)| n.label() == Some(label) || n.value() == Some(label)); + let b = node.unwrap_or_else(|| panic!("nothing named {label:?}")).1.bounds().expect("bounds"); + let at = egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(app, vec![egui::Event::PointerMoved(at)]); + frame(app, vec![button(true)]); + let out = frame(app, vec![button(false)]); + crate::tests_labels::shapes_text(&out) +} + +#[test] +fn check_fold_lines_lists_its_issues_in_the_panel_until_the_document_changes() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let (mut app, _) = blank(); + let entries = menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Packaging Tools"] && e.label == "Check Fold Lines").expect("listed"); + assert_eq!(item.command.as_deref(), Some(CHECK)); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + assert!(!crate::panel_docking::showing(&app.ui, ID)); + menus::invoke(&mut app, CHECK, item.params.clone()); + assert!(crate::panel_docking::showing(&app.ui, ID), "the panel opens"); + assert_eq!(app.ui.status, "Panels: 2, creases: 1, errors: 1, warnings: 0"); + let text = frames(&mut app, &ctx, None); + assert!(text.contains("A cut line ends without meeting another cut line."), "{text}"); + assert!(text.contains("Panels: 2, creases: 1, errors: 1, warnings: 0") && text.contains("Select"), "{text}"); + // Any change to the document takes the list away. + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap(); + let text = frames(&mut app, &ctx, None); + assert!(!text.contains("A cut line ends"), "{text}"); +} + +#[test] +fn the_check_button_checks_and_clicking_an_issue_selects_its_lines() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let (mut app, slit) = blank(); + let ctx = egui::Context::default(); + let text = frames(&mut app, &ctx, Some("Check")); + assert!(text.contains("A cut line ends without meeting another cut line."), "{text}"); + assert!(app.session.active().unwrap().selection.is_empty()); + frames(&mut app, &ctx, Some("A cut line ends without meeting another cut line.")); + let selected: Vec = app.session.active().unwrap().selection.objects.iter().map(|id| id.0).collect(); + assert_eq!(selected, [slit]); + let text = frames(&mut app, &ctx, None); + assert!(text.contains("A cut line ends without meeting another cut line."), "selecting keeps the list: {text}"); + // A clean blank: no issues. + app.run("edit.clear", json!({})).unwrap(); + let text = frames(&mut app, &ctx, Some("Check")); + assert!(text.contains("No issues found.") && text.contains("Panels: 2, creases: 1, errors: 0, warnings: 0"), "{text}"); +} + +#[test] +fn issues_and_the_summary_show_in_the_interface_language() { + let (mut app, _) = blank(); + let ctx = egui::Context::default(); + crate::i18n::set_current(crate::i18n::Lang::from_code("de").unwrap()); + let text = frames(&mut app, &ctx, Some(crate::i18n::t("Check"))); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert!(!text.contains("A cut line ends") && !text.contains("Panels:"), "{text}"); + assert!(text.contains("Schnittlinie") && text.contains('2'), "{text}"); +} + +/// The messages `addon.packaging.check` gives its issues, one for each code (two for `noCut`). +const ISSUE_MESSAGES: [&str; 16] = [ + "No cut lines are in the selection.", + "No cut lines are in the document.", + "The cut lines do not enclose an area.", + "A cut line ends without meeting another cut line.", + "A gap between cut lines was closed.", + "The fold lines are too complex to check.", + "A cut line and a crease lie on top of each other.", + "Two lines of the same role lie on top of each other.", + "A crease ends inside a panel.", + "A crease does not divide two panels.", + "A crease lies outside the cut outline.", + "A crease that is not straight is folded along one straight line.", + "A gap between cut lines is too narrow to tell apart.", + "A cut-out area holds other fold lines.", + "A panel is not joined to the rest by a crease.", + "A fold line is on a non-printing layer.", +]; + +#[test] +fn every_issue_message_translates_in_every_complete_message_catalog() { + for code in [ + "cs", "de", "el", "es", "fr", "hi", "hu", "it", "ja", "ka", "ko", "pl", "pt-br", "ru", "sv", "uk", "vi", "zh-hans", "zh-hant", "fi", "tr", + "ca", "nl", "da", + ] { + let lang = crate::i18n::Lang::from_code(code).unwrap(); + for m in ISSUE_MESSAGES.into_iter().chain(["Panels: 3, creases: 2, errors: 1, warnings: 0"]) { + assert_ne!(crate::i18n::message(lang, m), m, "{code}: {m}"); + } + } +} + #[test] fn the_panel_without_a_document_asks_for_one() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 71e443a399..ab9ed92de5 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -7084,4 +7084,23 @@ breakText Glyphs Глифи No objects are selected. Няма избрани обекти. Open a document to mark its fold lines. Отворете документ, за да отбележите линиите му на сгъване. Remove Fold Line Role Премахни вида на линията + Check Провери + Check Fold Lines Провери линиите на сгъване +@msg No cut lines are in the selection. В селекцията няма линии за рязане. +@msg No cut lines are in the document. В документа няма линии за рязане. +@msg The cut lines do not enclose an area. Линиите за рязане не ограждат площ. +@msg A cut line ends without meeting another cut line. Линия за рязане завършва, без да срещне друга линия за рязане. +@msg A gap between cut lines was closed. Процеп между линии за рязане беше затворен. +@msg The fold lines are too complex to check. Линиите на сгъване са твърде сложни за проверка. +@msg A cut line and a crease lie on top of each other. Линия за рязане и линия за биговане лежат една върху друга. +@msg Two lines of the same role lie on top of each other. Две линии от един и същи вид лежат една върху друга. +@msg A crease ends inside a panel. Линия за биговане завършва вътре в панел. +@msg A crease does not divide two panels. Линия за биговане не разделя два панела. +@msg A crease lies outside the cut outline. Линия за биговане лежи извън контура за рязане. +@msg A crease that is not straight is folded along one straight line. Линия за биговане, която не е права, се сгъва по една права линия. +@msg A gap between cut lines is too narrow to tell apart. Процеп между линии за рязане е твърде тесен, за да се различи. +@msg A cut-out area holds other fold lines. Изрязана област съдържа други линии на сгъване. +@msg A panel is not joined to the rest by a crease. Панел не е свързан с останалите с линия за биговане. +@msg A fold line is on a non-printing layer. Линия на сгъване е на слой, който не се печата. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Панели: {panels}, бигове: {hinges}, грешки: {errors}, предупреждения: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer трябва да е "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 883d6dd387..d6cc94f911 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -7137,4 +7137,23 @@ shape Open Otvoren No objects are selected. Nijedan objekat nije odabran. Open a document to mark its fold lines. Otvorite dokument da označite njegove linije savijanja. Remove Fold Line Role Ukloni vrstu linije + Check Provjeri + Check Fold Lines Provjeri linije savijanja +@msg No cut lines are in the selection. U odabiru nema linija rezanja. +@msg No cut lines are in the document. U dokumentu nema linija rezanja. +@msg The cut lines do not enclose an area. Linije rezanja ne zatvaraju nijednu površinu. +@msg A cut line ends without meeting another cut line. Linija rezanja završava a da ne susreće drugu liniju rezanja. +@msg A gap between cut lines was closed. Razmak između linija rezanja je zatvoren. +@msg The fold lines are too complex to check. Linije savijanja su previše složene za provjeru. +@msg A cut line and a crease lie on top of each other. Linija rezanja i linija bigovanja leže jedna preko druge. +@msg Two lines of the same role lie on top of each other. Dvije linije iste vrste leže jedna preko druge. +@msg A crease ends inside a panel. Linija bigovanja završava unutar panela. +@msg A crease does not divide two panels. Linija bigovanja ne razdvaja dva panela. +@msg A crease lies outside the cut outline. Linija bigovanja leži izvan konture rezanja. +@msg A crease that is not straight is folded along one straight line. Linija bigovanja koja nije ravna savija se duž jedne prave linije. +@msg A gap between cut lines is too narrow to tell apart. Razmak između linija rezanja je preuzak da bi se razlikovao. +@msg A cut-out area holds other fold lines. Izrezana površina sadrži druge linije savijanja. +@msg A panel is not joined to the rest by a crease. Panel nije povezan s ostatkom nijednom linijom bigovanja. +@msg A fold line is on a non-printing layer. Linija savijanja je na sloju koji se ne štampa. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Paneli: {panels}, bigovi: {hinges}, greške: {errors}, upozorenja: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer mora biti "singleLine", "everyLine", "standardSingleLine" ili "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a8a63cbf55..0089095906 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7945,4 +7945,23 @@ breakText Glyphs Glifs No objects are selected. No hi ha cap objecte seleccionat. Open a document to mark its fold lines. Obre un document per marcar-ne les línies de plegat. Remove Fold Line Role Elimina el tipus de línia + Check Comprova + Check Fold Lines Comprova les línies de plegat +@msg No cut lines are in the selection. No hi ha cap línia de tall a la selecció. +@msg No cut lines are in the document. No hi ha cap línia de tall al document. +@msg The cut lines do not enclose an area. Les línies de tall no tanquen cap àrea. +@msg A cut line ends without meeting another cut line. Una línia de tall acaba sense trobar cap altra línia de tall. +@msg A gap between cut lines was closed. S’ha tancat un buit entre línies de tall. +@msg The fold lines are too complex to check. Les línies de plegat són massa complexes per comprovar-les. +@msg A cut line and a crease lie on top of each other. Una línia de tall i una d’hendit estan superposades. +@msg Two lines of the same role lie on top of each other. Dues línies del mateix tipus estan superposades. +@msg A crease ends inside a panel. Una línia d’hendit acaba dins d’un panell. +@msg A crease does not divide two panels. Una línia d’hendit no separa dos panells. +@msg A crease lies outside the cut outline. Una línia d’hendit és fora del contorn de tall. +@msg A crease that is not straight is folded along one straight line. Una línia d’hendit que no és recta es plega al llarg d’una sola línia recta. +@msg A gap between cut lines is too narrow to tell apart. Un buit entre línies de tall és massa estret per distingir-lo. +@msg A cut-out area holds other fold lines. Una àrea retallada conté altres línies de plegat. +@msg A panel is not joined to the rest by a crease. Un panell no està unit a la resta per cap línia d’hendit. +@msg A fold line is on a non-printing layer. Una línia de plegat és en una capa que no s’imprimeix. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Panells: {panels}, hendits: {hinges}, errors: {errors}, avisos: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer ha de ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 569b1347ec..299aa6cedc 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -9742,3 +9742,22 @@ breakText Glyphs Glyfy No objects are selected. Nejsou vybrány žádné objekty. Open a document to mark its fold lines. Otevřete dokument, abyste označili jeho linie skladu. Remove Fold Line Role Odstranit typ linie + Check Zkontrolovat + Check Fold Lines Zkontrolovat linie skladu +@msg No cut lines are in the selection. Ve výběru nejsou žádné linie řezu. +@msg No cut lines are in the document. V dokumentu nejsou žádné linie řezu. +@msg The cut lines do not enclose an area. Linie řezu neohraničují žádnou plochu. +@msg A cut line ends without meeting another cut line. Linie řezu končí, aniž by se setkala s jinou linií řezu. +@msg A gap between cut lines was closed. Mezera mezi liniemi řezu byla uzavřena. +@msg The fold lines are too complex to check. Linie skladu jsou příliš složité na kontrolu. +@msg A cut line and a crease lie on top of each other. Linie řezu a linie bigu leží přes sebe. +@msg Two lines of the same role lie on top of each other. Dvě linie stejného typu leží přes sebe. +@msg A crease ends inside a panel. Linie bigu končí uvnitř panelu. +@msg A crease does not divide two panels. Linie bigu nerozděluje dva panely. +@msg A crease lies outside the cut outline. Linie bigu leží mimo obrys řezu. +@msg A crease that is not straight is folded along one straight line. Linie bigu, která není rovná, se ohýbá podél jedné přímky. +@msg A gap between cut lines is too narrow to tell apart. Mezera mezi liniemi řezu je příliš úzká na rozlišení. +@msg A cut-out area holds other fold lines. Vyříznutá oblast obsahuje další linie skladu. +@msg A panel is not joined to the rest by a crease. Panel není se zbytkem spojen žádnou linií bigu. +@msg A fold line is on a non-printing layer. Linie skladu je na netisknutelné vrstvě. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Panely: {panels}, bigy: {hinges}, chyby: {errors}, upozornění: {warnings} diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 4578e4efc1..647596237c 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -9844,4 +9844,23 @@ breakText Glyphs Glyffer No objects are selected. Ingen objekter er markeret. Open a document to mark its fold lines. Åbn et dokument for at markere dets foldelinjer. Remove Fold Line Role Fjern linjetype + Check Kontrollér + Check Fold Lines Kontrollér foldelinjer +@msg No cut lines are in the selection. Der er ingen skærelinjer i markeringen. +@msg No cut lines are in the document. Der er ingen skærelinjer i dokumentet. +@msg The cut lines do not enclose an area. Skærelinjerne omslutter ikke et område. +@msg A cut line ends without meeting another cut line. En skærelinje slutter uden at møde en anden skærelinje. +@msg A gap between cut lines was closed. Et mellemrum mellem skærelinjer blev lukket. +@msg The fold lines are too complex to check. Foldelinjerne er for komplekse til at kontrollere. +@msg A cut line and a crease lie on top of each other. En skærelinje og en rillelinje ligger oven på hinanden. +@msg Two lines of the same role lie on top of each other. To linjer af samme type ligger oven på hinanden. +@msg A crease ends inside a panel. En rillelinje slutter inde i et panel. +@msg A crease does not divide two panels. En rillelinje deler ikke to paneler. +@msg A crease lies outside the cut outline. En rillelinje ligger uden for skærekonturen. +@msg A crease that is not straight is folded along one straight line. En rillelinje, der ikke er lige, foldes langs én ret linje. +@msg A gap between cut lines is too narrow to tell apart. Et mellemrum mellem skærelinjer er for smalt til at skelne. +@msg A cut-out area holds other fold lines. Et udskåret område indeholder andre foldelinjer. +@msg A panel is not joined to the rest by a crease. Et panel er ikke forbundet med resten af en rillelinje. +@msg A fold line is on a non-printing layer. En foldelinje ligger på et lag, der ikke udskrives. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Paneler: {panels}, riller: {hinges}, fejl: {errors}, advarsler: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer skal være "singleLine", "everyLine", "standardSingleLine" eller "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c943c89dd2..4be132dc4f 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -9340,3 +9340,22 @@ breakText Glyphs Glyphen No objects are selected. Es sind keine Objekte ausgewählt. Open a document to mark its fold lines. Öffnen Sie ein Dokument, um seine Faltlinien festzulegen. Remove Fold Line Role Linienart entfernen + Check Prüfen + Check Fold Lines Faltlinien prüfen +@msg No cut lines are in the selection. Die Auswahl enthält keine Schnittlinien. +@msg No cut lines are in the document. Das Dokument enthält keine Schnittlinien. +@msg The cut lines do not enclose an area. Die Schnittlinien umschließen keine Fläche. +@msg A cut line ends without meeting another cut line. Eine Schnittlinie endet, ohne auf eine andere Schnittlinie zu treffen. +@msg A gap between cut lines was closed. Eine Lücke zwischen Schnittlinien wurde geschlossen. +@msg The fold lines are too complex to check. Die Faltlinien sind zu komplex für die Prüfung. +@msg A cut line and a crease lie on top of each other. Eine Schnittlinie und eine Rilllinie liegen übereinander. +@msg Two lines of the same role lie on top of each other. Zwei Linien derselben Linienart liegen übereinander. +@msg A crease ends inside a panel. Eine Rilllinie endet innerhalb eines Felds. +@msg A crease does not divide two panels. Eine Rilllinie trennt keine zwei Felder. +@msg A crease lies outside the cut outline. Eine Rilllinie liegt außerhalb der Schnittkontur. +@msg A crease that is not straight is folded along one straight line. Eine nicht gerade Rilllinie wird entlang einer geraden Linie gefaltet. +@msg A gap between cut lines is too narrow to tell apart. Eine Lücke zwischen Schnittlinien ist zu schmal, um sie zu unterscheiden. +@msg A cut-out area holds other fold lines. Ein ausgeschnittener Bereich enthält weitere Faltlinien. +@msg A panel is not joined to the rest by a crease. Ein Feld ist durch keine Rilllinie mit den übrigen verbunden. +@msg A fold line is on a non-printing layer. Eine Faltlinie liegt auf einer nicht druckbaren Ebene. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Felder: {panels}, Rilllinien: {hinges}, Fehler: {errors}, Warnungen: {warnings} diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 906640aa0a..05c6a32103 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7919,4 +7919,23 @@ breakText Glyphs Γλύφοι No objects are selected. Δεν έχουν επιλεγεί αντικείμενα. Open a document to mark its fold lines. Ανοίξτε ένα έγγραφο για να σημειώσετε τις γραμμές δίπλωσής του. Remove Fold Line Role Αφαίρεση τύπου γραμμής + Check Έλεγχος + Check Fold Lines Έλεγχος γραμμών δίπλωσης +@msg No cut lines are in the selection. Η επιλογή δεν περιέχει γραμμές κοπής. +@msg No cut lines are in the document. Το έγγραφο δεν περιέχει γραμμές κοπής. +@msg The cut lines do not enclose an area. Οι γραμμές κοπής δεν περικλείουν καμία περιοχή. +@msg A cut line ends without meeting another cut line. Μια γραμμή κοπής τελειώνει χωρίς να συναντήσει άλλη γραμμή κοπής. +@msg A gap between cut lines was closed. Ένα κενό ανάμεσα σε γραμμές κοπής κλείστηκε. +@msg The fold lines are too complex to check. Οι γραμμές δίπλωσης είναι πολύ σύνθετες για έλεγχο. +@msg A cut line and a crease lie on top of each other. Μια γραμμή κοπής και μια γραμμή πτύχωσης βρίσκονται η μία πάνω στην άλλη. +@msg Two lines of the same role lie on top of each other. Δύο γραμμές του ίδιου τύπου βρίσκονται η μία πάνω στην άλλη. +@msg A crease ends inside a panel. Μια γραμμή πτύχωσης τελειώνει μέσα σε ένα πάνελ. +@msg A crease does not divide two panels. Μια γραμμή πτύχωσης δεν χωρίζει δύο πάνελ. +@msg A crease lies outside the cut outline. Μια γραμμή πτύχωσης βρίσκεται έξω από το περίγραμμα κοπής. +@msg A crease that is not straight is folded along one straight line. Μια γραμμή πτύχωσης που δεν είναι ευθεία διπλώνεται κατά μήκος μίας ευθείας. +@msg A gap between cut lines is too narrow to tell apart. Ένα κενό ανάμεσα σε γραμμές κοπής είναι πολύ στενό για να διακριθεί. +@msg A cut-out area holds other fold lines. Μια αποκομμένη περιοχή περιέχει άλλες γραμμές δίπλωσης. +@msg A panel is not joined to the rest by a crease. Ένα πάνελ δεν συνδέεται με τα υπόλοιπα με καμία γραμμή πτύχωσης. +@msg A fold line is on a non-printing layer. Μια γραμμή δίπλωσης βρίσκεται σε επίπεδο που δεν εκτυπώνεται. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Πάνελ: {panels}, πτυχώσεις: {hinges}, σφάλματα: {errors}, προειδοποιήσεις: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" το composer πρέπει να είναι "singleLine", "everyLine", "standardSingleLine" ή "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9239c93a73..12e483f369 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7906,4 +7906,23 @@ breakText Glyphs Glifos No objects are selected. No hay objetos seleccionados. Open a document to mark its fold lines. Abre un documento para marcar sus líneas de plegado. Remove Fold Line Role Quitar tipo de línea + Check Comprobar + Check Fold Lines Comprobar líneas de plegado +@msg No cut lines are in the selection. No hay líneas de corte en la selección. +@msg No cut lines are in the document. No hay líneas de corte en el documento. +@msg The cut lines do not enclose an area. Las líneas de corte no encierran ningún área. +@msg A cut line ends without meeting another cut line. Una línea de corte termina sin llegar a otra línea de corte. +@msg A gap between cut lines was closed. Se cerró un hueco entre líneas de corte. +@msg The fold lines are too complex to check. Las líneas de plegado son demasiado complejas para comprobarlas. +@msg A cut line and a crease lie on top of each other. Una línea de corte y una de hendido están superpuestas. +@msg Two lines of the same role lie on top of each other. Dos líneas del mismo tipo están superpuestas. +@msg A crease ends inside a panel. Una línea de hendido termina dentro de un panel. +@msg A crease does not divide two panels. Una línea de hendido no separa dos paneles. +@msg A crease lies outside the cut outline. Una línea de hendido está fuera del contorno de corte. +@msg A crease that is not straight is folded along one straight line. Una línea de hendido que no es recta se pliega a lo largo de una sola línea recta. +@msg A gap between cut lines is too narrow to tell apart. Un hueco entre líneas de corte es demasiado estrecho para distinguirlo. +@msg A cut-out area holds other fold lines. Un área recortada contiene otras líneas de plegado. +@msg A panel is not joined to the rest by a crease. Un panel no está unido al resto por ninguna línea de hendido. +@msg A fold line is on a non-printing layer. Una línea de plegado está en una capa que no se imprime. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Paneles: {panels}, hendidos: {hinges}, errores: {errors}, advertencias: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer debe ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 423703e5c1..db6163e7e3 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -8002,4 +8002,23 @@ breakText Glyphs Merkit No objects are selected. Objekteja ei ole valittu. Open a document to mark its fold lines. Avaa asiakirja, niin voit merkitä sen taittoviivat. Remove Fold Line Role Poista viivatyyppi + Check Tarkista + Check Fold Lines Tarkista taittoviivat +@msg No cut lines are in the selection. Valinnassa ei ole leikkausviivoja. +@msg No cut lines are in the document. Asiakirjassa ei ole leikkausviivoja. +@msg The cut lines do not enclose an area. Leikkausviivat eivät rajaa aluetta. +@msg A cut line ends without meeting another cut line. Leikkausviiva päättyy kohtaamatta toista leikkausviivaa. +@msg A gap between cut lines was closed. Leikkausviivojen välinen rako suljettiin. +@msg The fold lines are too complex to check. Taittoviivat ovat liian monimutkaisia tarkistettaviksi. +@msg A cut line and a crease lie on top of each other. Leikkausviiva ja nuuttausviiva ovat päällekkäin. +@msg Two lines of the same role lie on top of each other. Kaksi samantyyppistä viivaa on päällekkäin. +@msg A crease ends inside a panel. Nuuttausviiva päättyy paneelin sisään. +@msg A crease does not divide two panels. Nuuttausviiva ei jaa kahta paneelia. +@msg A crease lies outside the cut outline. Nuuttausviiva on leikkausääriviivan ulkopuolella. +@msg A crease that is not straight is folded along one straight line. Nuuttausviiva, joka ei ole suora, taitetaan yhtä suoraa viivaa pitkin. +@msg A gap between cut lines is too narrow to tell apart. Leikkausviivojen välinen rako on liian kapea erotettavaksi. +@msg A cut-out area holds other fold lines. Leikattu alue sisältää muita taittoviivoja. +@msg A panel is not joined to the rest by a crease. Paneelia ei ole liitetty muihin millään nuuttausviivalla. +@msg A fold line is on a non-printing layer. Taittoviiva on tasolla, jota ei tulosteta. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Paneelit: {panels}, nuuttaukset: {hinges}, virheet: {errors}, varoitukset: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer on oltava "singleLine", "everyLine", "standardSingleLine" tai "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8af602785b..7ae0eab9c6 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -9727,4 +9727,23 @@ breakText Glyphs Glyphes No objects are selected. Aucun objet n’est sélectionné. Open a document to mark its fold lines. Ouvrez un document pour marquer ses lignes de pliage. Remove Fold Line Role Supprimer le type de ligne + Check Vérifier + Check Fold Lines Vérifier les lignes de pliage +@msg No cut lines are in the selection. La sélection ne contient aucune ligne de découpe. +@msg No cut lines are in the document. Le document ne contient aucune ligne de découpe. +@msg The cut lines do not enclose an area. Les lignes de découpe n’entourent aucune zone. +@msg A cut line ends without meeting another cut line. Une ligne de découpe se termine sans rejoindre une autre ligne de découpe. +@msg A gap between cut lines was closed. Un écart entre des lignes de découpe a été fermé. +@msg The fold lines are too complex to check. Les lignes de pliage sont trop complexes pour être vérifiées. +@msg A cut line and a crease lie on top of each other. Une ligne de découpe et une ligne de rainage se superposent. +@msg Two lines of the same role lie on top of each other. Deux lignes du même type se superposent. +@msg A crease ends inside a panel. Une ligne de rainage se termine à l’intérieur d’un panneau. +@msg A crease does not divide two panels. Une ligne de rainage ne sépare pas deux panneaux. +@msg A crease lies outside the cut outline. Une ligne de rainage se trouve hors du contour de découpe. +@msg A crease that is not straight is folded along one straight line. Une ligne de rainage qui n’est pas droite est pliée le long d’une seule ligne droite. +@msg A gap between cut lines is too narrow to tell apart. Un écart entre des lignes de découpe est trop étroit pour être distingué. +@msg A cut-out area holds other fold lines. Une zone découpée contient d’autres lignes de pliage. +@msg A panel is not joined to the rest by a crease. Un panneau n’est relié au reste par aucune ligne de rainage. +@msg A fold line is on a non-printing layer. Une ligne de pliage se trouve sur un calque non imprimable. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} {panels} panneau(x), {hinges} rainage(s), {errors} erreur(s), {warnings} avertissement(s) @msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} pixels, c’est trop grand pour le GIF (65535 pixels par côté au plus) : réduisez la résolution diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 4eed343e3d..d7b10bf7c0 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -4846,6 +4846,25 @@ swatch [Registration] [રજિસ્ટ્રેશન] No objects are selected. કોઈ ઑબ્જેક્ટ પસંદ કરેલ નથી. Open a document to mark its fold lines. તેની ફોલ્ડ લાઇન્સ ચિહ્નિત કરવા દસ્તાવેજ ખોલો. Remove Fold Line Role લાઇન પ્રકાર દૂર કરો + Check ચેક કરો + Check Fold Lines ફોલ્ડ લાઇન્સ ચેક કરો +@msg No cut lines are in the selection. પસંદગીમાં કોઈ કટ લાઇન નથી. +@msg No cut lines are in the document. ડૉક્યુમેન્ટમાં કોઈ કટ લાઇન નથી. +@msg The cut lines do not enclose an area. કટ લાઇન્સ કોઈ વિસ્તાર ઘેરતી નથી. +@msg A cut line ends without meeting another cut line. એક કટ લાઇન બીજી કટ લાઇનને મળ્યા વિના પૂરી થાય છે. +@msg A gap between cut lines was closed. કટ લાઇન્સ વચ્ચેનો ગેપ બંધ કરવામાં આવ્યો. +@msg The fold lines are too complex to check. ફોલ્ડ લાઇન્સ ચેક કરવા માટે ખૂબ જટિલ છે. +@msg A cut line and a crease lie on top of each other. એક કટ લાઇન અને એક ક્રીઝ લાઇન એકબીજા પર છે. +@msg Two lines of the same role lie on top of each other. એક જ પ્રકારની બે લાઇન્સ એકબીજા પર છે. +@msg A crease ends inside a panel. એક ક્રીઝ લાઇન પેનલની અંદર પૂરી થાય છે. +@msg A crease does not divide two panels. એક ક્રીઝ લાઇન બે પેનલને અલગ કરતી નથી. +@msg A crease lies outside the cut outline. એક ક્રીઝ લાઇન કટ આઉટલાઇનની બહાર છે. +@msg A crease that is not straight is folded along one straight line. સીધી ન હોય તેવી ક્રીઝ લાઇન એક સીધી લાઇન પર ફોલ્ડ થાય છે. +@msg A gap between cut lines is too narrow to tell apart. કટ લાઇન્સ વચ્ચેનો ગેપ ઓળખવા માટે ખૂબ સાંકડો છે. +@msg A cut-out area holds other fold lines. એક કટ-આઉટ વિસ્તારમાં બીજી ફોલ્ડ લાઇન્સ છે. +@msg A panel is not joined to the rest by a crease. એક પેનલ કોઈ ક્રીઝ લાઇનથી બાકીના સાથે જોડાયેલી નથી. +@msg A fold line is on a non-printing layer. એક ફોલ્ડ લાઇન નોન-પ્રિન્ટિંગ લેયર પર છે. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} પેનલ: {panels}, ક્રીઝ: {hinges}, ભૂલો: {errors}, ચેતવણીઓ: {warnings} Middle Eastern & South Asian Single-line Composer સિંગલ-લાઇન કમ્પોઝર (મધ્ય પૂર્વ અને દક્ષિણ એશિયા) Middle Eastern & South Asian Every-line Composer એવરી-લાઇન કમ્પોઝર (મધ્ય પૂર્વ અને દક્ષિણ એશિયા) Standard Single-line Composer સ્ટાન્ડર્ડ સિંગલ-લાઇન કમ્પોઝર diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index de33cdbd92..f632881023 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -9347,3 +9347,22 @@ theme Appearance अपीयरेंस No objects are selected. कोई ऑब्जेक्ट सिलेक्ट नहीं है। Open a document to mark its fold lines. फ़ोल्ड लाइनें मार्क करने के लिए कोई डॉक्यूमेंट ओपन करें। Remove Fold Line Role लाइन प्रकार हटाएँ + Check चेक करें + Check Fold Lines फ़ोल्ड लाइनें चेक करें +@msg No cut lines are in the selection. सिलेक्शन में कोई कट लाइन नहीं है। +@msg No cut lines are in the document. डॉक्यूमेंट में कोई कट लाइन नहीं है। +@msg The cut lines do not enclose an area. कट लाइनें कोई एरिया नहीं घेरतीं। +@msg A cut line ends without meeting another cut line. एक कट लाइन किसी दूसरी कट लाइन से मिले बिना खत्म हो जाती है। +@msg A gap between cut lines was closed. कट लाइनों के बीच का गैप बंद कर दिया गया। +@msg The fold lines are too complex to check. फ़ोल्ड लाइनें चेक करने के लिए बहुत जटिल हैं। +@msg A cut line and a crease lie on top of each other. एक कट लाइन और एक क्रीज़ लाइन एक-दूसरे के ऊपर हैं। +@msg Two lines of the same role lie on top of each other. एक ही प्रकार की दो लाइनें एक-दूसरे के ऊपर हैं। +@msg A crease ends inside a panel. एक क्रीज़ लाइन किसी पैनल के अंदर खत्म होती है। +@msg A crease does not divide two panels. एक क्रीज़ लाइन दो पैनलों को अलग नहीं करती। +@msg A crease lies outside the cut outline. एक क्रीज़ लाइन कट आउटलाइन के बाहर है। +@msg A crease that is not straight is folded along one straight line. जो क्रीज़ लाइन सीधी नहीं है, वह एक सीधी लाइन पर फ़ोल्ड होती है। +@msg A gap between cut lines is too narrow to tell apart. कट लाइनों के बीच का गैप पहचानने के लिए बहुत पतला है। +@msg A cut-out area holds other fold lines. एक कट-आउट एरिया में दूसरी फ़ोल्ड लाइनें हैं। +@msg A panel is not joined to the rest by a crease. कोई पैनल किसी क्रीज़ लाइन से बाकी से जुड़ा नहीं है। +@msg A fold line is on a non-printing layer. एक फ़ोल्ड लाइन नॉन-प्रिंटिंग लेयर पर है। +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} पैनल: {panels}, क्रीज़: {hinges}, एरर: {errors}, वॉर्निंग: {warnings} diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index f869e7d07b..5ecfe58e72 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -9730,3 +9730,22 @@ breakText Glyphs Glifák No objects are selected. Nincs kijelölt objektum. Open a document to mark its fold lines. Nyiss meg egy dokumentumot a hajtásvonalai megjelöléséhez. Remove Fold Line Role Vonaltípus eltávolítása + Check Ellenőrzés + Check Fold Lines Hajtásvonalak ellenőrzése +@msg No cut lines are in the selection. A kijelölésben nincs vágóvonal. +@msg No cut lines are in the document. A dokumentumban nincs vágóvonal. +@msg The cut lines do not enclose an area. A vágóvonalak nem zárnak közre területet. +@msg A cut line ends without meeting another cut line. Egy vágóvonal úgy ér véget, hogy nem találkozik másik vágóvonallal. +@msg A gap between cut lines was closed. A vágóvonalak közötti rés le lett zárva. +@msg The fold lines are too complex to check. A hajtásvonalak túl összetettek az ellenőrzéshez. +@msg A cut line and a crease lie on top of each other. Egy vágóvonal és egy bigvonal egymáson fekszik. +@msg Two lines of the same role lie on top of each other. Két azonos típusú vonal egymáson fekszik. +@msg A crease ends inside a panel. Egy bigvonal egy panelen belül ér véget. +@msg A crease does not divide two panels. Egy bigvonal nem választ el két panelt. +@msg A crease lies outside the cut outline. Egy bigvonal a vágási körvonalon kívül van. +@msg A crease that is not straight is folded along one straight line. Egy nem egyenes bigvonal egyetlen egyenes mentén hajlik. +@msg A gap between cut lines is too narrow to tell apart. A vágóvonalak közötti rés túl keskeny a megkülönböztetéshez. +@msg A cut-out area holds other fold lines. Egy kivágott terület további hajtásvonalakat tartalmaz. +@msg A panel is not joined to the rest by a crease. Egy panelt egyetlen bigvonal sem köt a többihez. +@msg A fold line is on a non-printing layer. Egy hajtásvonal nem nyomtatható rétegen van. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Panelek: {panels}, bigek: {hinges}, hibák: {errors}, figyelmeztetések: {warnings} diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c5f865e69b..cd2ad82864 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -7099,4 +7099,23 @@ breakText Glyphs Glif No objects are selected. Tidak ada objek yang dipilih. Open a document to mark its fold lines. Buka dokumen untuk menandai garis lipatnya. Remove Fold Line Role Hapus jenis garis + Check Periksa + Check Fold Lines Periksa garis lipat +@msg No cut lines are in the selection. Tidak ada garis potong dalam seleksi. +@msg No cut lines are in the document. Tidak ada garis potong dalam dokumen. +@msg The cut lines do not enclose an area. Garis potong tidak melingkupi area apa pun. +@msg A cut line ends without meeting another cut line. Sebuah garis potong berakhir tanpa bertemu garis potong lain. +@msg A gap between cut lines was closed. Celah di antara garis potong telah ditutup. +@msg The fold lines are too complex to check. Garis lipat terlalu rumit untuk diperiksa. +@msg A cut line and a crease lie on top of each other. Sebuah garis potong dan sebuah garis lekuk bertumpuk. +@msg Two lines of the same role lie on top of each other. Dua garis dengan jenis yang sama bertumpuk. +@msg A crease ends inside a panel. Sebuah garis lekuk berakhir di dalam panel. +@msg A crease does not divide two panels. Sebuah garis lekuk tidak membagi dua panel. +@msg A crease lies outside the cut outline. Sebuah garis lekuk berada di luar kontur potong. +@msg A crease that is not straight is folded along one straight line. Garis lekuk yang tidak lurus dilipat di sepanjang satu garis lurus. +@msg A gap between cut lines is too narrow to tell apart. Celah di antara garis potong terlalu sempit untuk dibedakan. +@msg A cut-out area holds other fold lines. Area yang dipotong berisi garis lipat lain. +@msg A panel is not joined to the rest by a crease. Sebuah panel tidak tersambung ke bagian lain oleh garis lekuk apa pun. +@msg A fold line is on a non-printing layer. Sebuah garis lipat berada di lapisan yang tidak dicetak. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Panel: {panels}, lekuk: {hinges}, galat: {errors}, peringatan: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer harus "singleLine", "everyLine", "standardSingleLine", atau "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 08cefdbed7..b34cf145a7 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -9374,3 +9374,22 @@ breakText Glyphs Glifi No objects are selected. Nessun oggetto selezionato. Open a document to mark its fold lines. Apri un documento per segnarne le linee di piega. Remove Fold Line Role Rimuovi tipo di linea + Check Verifica + Check Fold Lines Verifica linee di piega +@msg No cut lines are in the selection. Nella selezione non ci sono linee di taglio. +@msg No cut lines are in the document. Nel documento non ci sono linee di taglio. +@msg The cut lines do not enclose an area. Le linee di taglio non racchiudono alcuna area. +@msg A cut line ends without meeting another cut line. Una linea di taglio termina senza incontrare un’altra linea di taglio. +@msg A gap between cut lines was closed. È stato chiuso uno spazio tra linee di taglio. +@msg The fold lines are too complex to check. Le linee di piega sono troppo complesse da verificare. +@msg A cut line and a crease lie on top of each other. Una linea di taglio e una di cordonatura sono sovrapposte. +@msg Two lines of the same role lie on top of each other. Due linee dello stesso tipo sono sovrapposte. +@msg A crease ends inside a panel. Una linea di cordonatura termina all’interno di un pannello. +@msg A crease does not divide two panels. Una linea di cordonatura non divide due pannelli. +@msg A crease lies outside the cut outline. Una linea di cordonatura si trova fuori dal contorno di taglio. +@msg A crease that is not straight is folded along one straight line. Una linea di cordonatura non diritta viene piegata lungo un’unica linea retta. +@msg A gap between cut lines is too narrow to tell apart. Uno spazio tra linee di taglio è troppo stretto per essere distinto. +@msg A cut-out area holds other fold lines. Un’area ritagliata contiene altre linee di piega. +@msg A panel is not joined to the rest by a crease. Un pannello non è unito al resto da alcuna linea di cordonatura. +@msg A fold line is on a non-printing layer. Una linea di piega si trova su un livello non stampabile. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Pannelli: {panels}, cordonature: {hinges}, errori: {errors}, avvisi: {warnings} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 59c7628f40..a224dec9f0 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -9441,3 +9441,22 @@ breakText Glyphs 字形 No objects are selected. オブジェクトが選択されていません。 Open a document to mark its fold lines. ドキュメントを開くと折り線を設定できます。 Remove Fold Line Role 線種を解除 + Check チェック + Check Fold Lines 折り線をチェック +@msg No cut lines are in the selection. 選択範囲にカット線がありません。 +@msg No cut lines are in the document. ドキュメントにカット線がありません。 +@msg The cut lines do not enclose an area. カット線が領域を囲んでいません。 +@msg A cut line ends without meeting another cut line. カット線が他のカット線と接しないまま終わっています。 +@msg A gap between cut lines was closed. カット線間の隙間を閉じました。 +@msg The fold lines are too complex to check. 折り線が複雑すぎるためチェックできません。 +@msg A cut line and a crease lie on top of each other. カット線と筋入れ線が重なっています。 +@msg Two lines of the same role lie on top of each other. 同じ種類の線が 2 本重なっています。 +@msg A crease ends inside a panel. 筋入れ線がパネルの内側で終わっています。 +@msg A crease does not divide two panels. 筋入れ線が 2 つのパネルを分けていません。 +@msg A crease lies outside the cut outline. 筋入れ線がカットの輪郭の外側にあります。 +@msg A crease that is not straight is folded along one straight line. まっすぐでない筋入れ線は 1 本の直線に沿って折られます。 +@msg A gap between cut lines is too narrow to tell apart. カット線間の隙間が狭すぎて区別できません。 +@msg A cut-out area holds other fold lines. 切り抜かれた領域に他の折り線があります。 +@msg A panel is not joined to the rest by a crease. パネルがどの筋入れ線でも他とつながっていません。 +@msg A fold line is on a non-printing layer. 折り線が印刷しないレイヤーにあります。 +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} パネル: {panels}、筋入れ: {hinges}、エラー: {errors}、警告: {warnings} diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 9393433cdb..406a43c301 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -10010,4 +10010,23 @@ font-script Japanese იაპონური No objects are selected. ობიექტები არ არის მონიშნული. Open a document to mark its fold lines. გახსენით დოკუმენტი მისი მოკეცვის ხაზების მოსანიშნად. Remove Fold Line Role ხაზის ტიპის მოხსნა + Check შემოწმება + Check Fold Lines მოკეცვის ხაზების შემოწმება +@msg No cut lines are in the selection. მონიშვნაში ჭრის ხაზები არ არის. +@msg No cut lines are in the document. დოკუმენტში ჭრის ხაზები არ არის. +@msg The cut lines do not enclose an area. ჭრის ხაზები არცერთ არეს არ შემოფარგლავს. +@msg A cut line ends without meeting another cut line. ჭრის ხაზი მთავრდება ისე, რომ სხვა ჭრის ხაზს არ ხვდება. +@msg A gap between cut lines was closed. ჭრის ხაზებს შორის ღრეჩო დაიხურა. +@msg The fold lines are too complex to check. მოკეცვის ხაზები შესამოწმებლად ზედმეტად რთულია. +@msg A cut line and a crease lie on top of each other. ჭრის ხაზი და ბიგის ხაზი ერთმანეთზე დევს. +@msg Two lines of the same role lie on top of each other. ერთი ტიპის ორი ხაზი ერთმანეთზე დევს. +@msg A crease ends inside a panel. ბიგის ხაზი პანელის შიგნით მთავრდება. +@msg A crease does not divide two panels. ბიგის ხაზი ორ პანელს არ ყოფს. +@msg A crease lies outside the cut outline. ბიგის ხაზი ჭრის კონტურის გარეთაა. +@msg A crease that is not straight is folded along one straight line. ბიგის ხაზი, რომელიც სწორი არ არის, ერთი სწორი ხაზის გასწვრივ იკეცება. +@msg A gap between cut lines is too narrow to tell apart. ჭრის ხაზებს შორის ღრეჩო ზედმეტად ვიწროა გასარჩევად. +@msg A cut-out area holds other fold lines. ამოჭრილი არე სხვა მოკეცვის ხაზებს შეიცავს. +@msg A panel is not joined to the rest by a crease. პანელი დანარჩენს არცერთი ბიგის ხაზით არ უერთდება. +@msg A fold line is on a non-printing layer. მოკეცვის ხაზი არასაბეჭდ შრეზეა. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} პანელები: {panels}, ბიგები: {hinges}, შეცდომები: {errors}, გაფრთხილებები: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer უნდა იყოს "singleLine", "everyLine", "standardSingleLine" ან "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 49d5e10dc1..219bd8aa76 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -9337,3 +9337,22 @@ breakText Glyphs 글리프 No objects are selected. 선택한 개체가 없습니다. Open a document to mark its fold lines. 접는 선을 지정하려면 문서를 여세요. Remove Fold Line Role 선 종류 제거 + Check 검사 + Check Fold Lines 접는 선 검사 +@msg No cut lines are in the selection. 선택 영역에 재단선이 없습니다. +@msg No cut lines are in the document. 문서에 재단선이 없습니다. +@msg The cut lines do not enclose an area. 재단선이 영역을 둘러싸지 않습니다. +@msg A cut line ends without meeting another cut line. 재단선이 다른 재단선과 만나지 않고 끝납니다. +@msg A gap between cut lines was closed. 재단선 사이의 틈을 닫았습니다. +@msg The fold lines are too complex to check. 접는 선이 너무 복잡해서 검사할 수 없습니다. +@msg A cut line and a crease lie on top of each other. 재단선과 오시선이 겹쳐 있습니다. +@msg Two lines of the same role lie on top of each other. 같은 종류의 선 두 개가 겹쳐 있습니다. +@msg A crease ends inside a panel. 오시선이 패널 안에서 끝납니다. +@msg A crease does not divide two panels. 오시선이 두 패널을 나누지 않습니다. +@msg A crease lies outside the cut outline. 오시선이 재단 윤곽선 밖에 있습니다. +@msg A crease that is not straight is folded along one straight line. 곧지 않은 오시선은 하나의 직선을 따라 접힙니다. +@msg A gap between cut lines is too narrow to tell apart. 재단선 사이의 틈이 너무 좁아 구별할 수 없습니다. +@msg A cut-out area holds other fold lines. 잘라 낸 영역에 다른 접는 선이 있습니다. +@msg A panel is not joined to the rest by a crease. 패널이 어떤 오시선으로도 나머지와 연결되어 있지 않습니다. +@msg A fold line is on a non-printing layer. 접는 선이 인쇄되지 않는 레이어에 있습니다. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} 패널: {panels}, 오시: {hinges}, 오류: {errors}, 경고: {warnings} diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index f071ebd0e2..62c2566f13 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -9775,3 +9775,22 @@ breakText Glyphs Glyphs No objects are selected. Er zijn geen objecten geselecteerd. Open a document to mark its fold lines. Open een document om de vouwlijnen te markeren. Remove Fold Line Role Lijnsoort verwijderen + Check Controleren + Check Fold Lines Vouwlijnen controleren +@msg No cut lines are in the selection. De selectie bevat geen snijlijnen. +@msg No cut lines are in the document. Het document bevat geen snijlijnen. +@msg The cut lines do not enclose an area. De snijlijnen sluiten geen gebied in. +@msg A cut line ends without meeting another cut line. Een snijlijn eindigt zonder een andere snijlijn te raken. +@msg A gap between cut lines was closed. Een opening tussen snijlijnen is gesloten. +@msg The fold lines are too complex to check. De vouwlijnen zijn te complex om te controleren. +@msg A cut line and a crease lie on top of each other. Een snijlijn en een rillijn liggen over elkaar. +@msg Two lines of the same role lie on top of each other. Twee lijnen van dezelfde soort liggen over elkaar. +@msg A crease ends inside a panel. Een rillijn eindigt binnen een paneel. +@msg A crease does not divide two panels. Een rillijn verdeelt geen twee panelen. +@msg A crease lies outside the cut outline. Een rillijn ligt buiten de snijcontour. +@msg A crease that is not straight is folded along one straight line. Een rillijn die niet recht is, wordt langs één rechte lijn gevouwen. +@msg A gap between cut lines is too narrow to tell apart. Een opening tussen snijlijnen is te smal om te onderscheiden. +@msg A cut-out area holds other fold lines. Een uitgesneden gebied bevat andere vouwlijnen. +@msg A panel is not joined to the rest by a crease. Een paneel is door geen rillijn met de rest verbonden. +@msg A fold line is on a non-printing layer. Een vouwlijn staat op een laag die niet wordt afgedrukt. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Panelen: {panels}, rillijnen: {hinges}, fouten: {errors}, waarschuwingen: {warnings} diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 2477c73abd..587884f787 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -9595,3 +9595,22 @@ breakText Glyphs Glify No objects are selected. Nie zaznaczono żadnych obiektów. Open a document to mark its fold lines. Otwórz dokument, aby oznaczyć jego linie zgięcia. Remove Fold Line Role Usuń rodzaj linii + Check Sprawdź + Check Fold Lines Sprawdź linie zgięcia +@msg No cut lines are in the selection. W zaznaczeniu nie ma linii cięcia. +@msg No cut lines are in the document. W dokumencie nie ma linii cięcia. +@msg The cut lines do not enclose an area. Linie cięcia nie obejmują żadnego obszaru. +@msg A cut line ends without meeting another cut line. Linia cięcia kończy się, nie stykając się z inną linią cięcia. +@msg A gap between cut lines was closed. Zamknięto przerwę między liniami cięcia. +@msg The fold lines are too complex to check. Linie zgięcia są zbyt złożone, aby je sprawdzić. +@msg A cut line and a crease lie on top of each other. Linia cięcia i linia bigowania leżą na sobie. +@msg Two lines of the same role lie on top of each other. Dwie linie tego samego rodzaju leżą na sobie. +@msg A crease ends inside a panel. Linia bigowania kończy się wewnątrz panelu. +@msg A crease does not divide two panels. Linia bigowania nie rozdziela dwóch paneli. +@msg A crease lies outside the cut outline. Linia bigowania leży poza konturem cięcia. +@msg A crease that is not straight is folded along one straight line. Linia bigowania, która nie jest prosta, jest zginana wzdłuż jednej linii prostej. +@msg A gap between cut lines is too narrow to tell apart. Przerwa między liniami cięcia jest zbyt wąska, aby ją rozróżnić. +@msg A cut-out area holds other fold lines. Wycięty obszar zawiera inne linie zgięcia. +@msg A panel is not joined to the rest by a crease. Panel nie jest połączony z resztą żadną linią bigowania. +@msg A fold line is on a non-printing layer. Linia zgięcia znajduje się na warstwie niedrukowanej. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Panele: {panels}, bigi: {hinges}, błędy: {errors}, ostrzeżenia: {warnings} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 333351b9af..4e1f704ec8 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -9813,3 +9813,22 @@ swatch Yellow Green Verde-amarelado No objects are selected. Nenhum objeto selecionado. Open a document to mark its fold lines. Abra um documento para marcar suas linhas de dobra. Remove Fold Line Role Remover Tipo de Linha + Check Verificar + Check Fold Lines Verificar Linhas de Dobra +@msg No cut lines are in the selection. Não há linhas de corte na seleção. +@msg No cut lines are in the document. Não há linhas de corte no documento. +@msg The cut lines do not enclose an area. As linhas de corte não delimitam nenhuma área. +@msg A cut line ends without meeting another cut line. Uma linha de corte termina sem encontrar outra linha de corte. +@msg A gap between cut lines was closed. Uma lacuna entre linhas de corte foi fechada. +@msg The fold lines are too complex to check. As linhas de dobra são complexas demais para verificar. +@msg A cut line and a crease lie on top of each other. Uma linha de corte e uma de vinco estão sobrepostas. +@msg Two lines of the same role lie on top of each other. Duas linhas do mesmo tipo estão sobrepostas. +@msg A crease ends inside a panel. Uma linha de vinco termina dentro de um painel. +@msg A crease does not divide two panels. Uma linha de vinco não divide dois painéis. +@msg A crease lies outside the cut outline. Uma linha de vinco está fora do contorno de corte. +@msg A crease that is not straight is folded along one straight line. Uma linha de vinco que não é reta é dobrada ao longo de uma única linha reta. +@msg A gap between cut lines is too narrow to tell apart. Uma lacuna entre linhas de corte é estreita demais para ser distinguida. +@msg A cut-out area holds other fold lines. Uma área recortada contém outras linhas de dobra. +@msg A panel is not joined to the rest by a crease. Um painel não está unido ao restante por nenhuma linha de vinco. +@msg A fold line is on a non-printing layer. Uma linha de dobra está em uma camada não imprimível. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Painéis: {panels}, vincos: {hinges}, erros: {errors}, avisos: {warnings} diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ae33aa0d55..2c6dec01d4 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -9834,5 +9834,24 @@ shape Open Открытый No objects are selected. Объекты не выделены. Open a document to mark its fold lines. Откройте документ, чтобы отметить его линии сгиба. Remove Fold Line Role Убрать тип линии + Check Проверить + Check Fold Lines Проверить линии сгиба +@msg No cut lines are in the selection. В выделении нет линий реза. +@msg No cut lines are in the document. В документе нет линий реза. +@msg The cut lines do not enclose an area. Линии реза не ограничивают никакую область. +@msg A cut line ends without meeting another cut line. Линия реза заканчивается, не встречая другую линию реза. +@msg A gap between cut lines was closed. Зазор между линиями реза закрыт. +@msg The fold lines are too complex to check. Линии сгиба слишком сложны для проверки. +@msg A cut line and a crease lie on top of each other. Линия реза и линия биговки лежат друг на друге. +@msg Two lines of the same role lie on top of each other. Две линии одного типа лежат друг на друге. +@msg A crease ends inside a panel. Линия биговки заканчивается внутри панели. +@msg A crease does not divide two panels. Линия биговки не разделяет две панели. +@msg A crease lies outside the cut outline. Линия биговки лежит за пределами контура реза. +@msg A crease that is not straight is folded along one straight line. Непрямая линия биговки сгибается по одной прямой. +@msg A gap between cut lines is too narrow to tell apart. Зазор между линиями реза слишком узок, чтобы его различить. +@msg A cut-out area holds other fold lines. Вырезанная область содержит другие линии сгиба. +@msg A panel is not joined to the rest by a crease. Панель не соединена с остальными ни одной линией биговки. +@msg A fold line is on a non-printing layer. Линия сгиба находится на непечатаемом слое. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Панели: {panels}, биговки: {hinges}, ошибки: {errors}, предупреждения: {warnings} @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} пикселей — слишком большой размер для PSD (не более {MAX_SIDE} пикселей по стороне): уменьшите разрешение @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer должен быть "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1bd4fd0692..c0ac175345 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -9425,4 +9425,23 @@ digits Hindi Hindi No objects are selected. Inga objekt är markerade. Open a document to mark its fold lines. Öppna ett dokument för att markera dess falslinjer. Remove Fold Line Role Ta bort linjetyp + Check Kontrollera + Check Fold Lines Kontrollera falslinjer +@msg No cut lines are in the selection. Det finns inga skärlinjer i markeringen. +@msg No cut lines are in the document. Det finns inga skärlinjer i dokumentet. +@msg The cut lines do not enclose an area. Skärlinjerna omsluter inget område. +@msg A cut line ends without meeting another cut line. En skärlinje slutar utan att möta en annan skärlinje. +@msg A gap between cut lines was closed. Ett mellanrum mellan skärlinjer stängdes. +@msg The fold lines are too complex to check. Falslinjerna är för komplexa för att kontrollera. +@msg A cut line and a crease lie on top of each other. En skärlinje och en biglinje ligger ovanpå varandra. +@msg Two lines of the same role lie on top of each other. Två linjer av samma typ ligger ovanpå varandra. +@msg A crease ends inside a panel. En biglinje slutar inuti en panel. +@msg A crease does not divide two panels. En biglinje delar inte två paneler. +@msg A crease lies outside the cut outline. En biglinje ligger utanför skärkonturen. +@msg A crease that is not straight is folded along one straight line. En biglinje som inte är rak falsas längs en rak linje. +@msg A gap between cut lines is too narrow to tell apart. Ett mellanrum mellan skärlinjer är för smalt för att skilja ut. +@msg A cut-out area holds other fold lines. Ett utskuret område innehåller andra falslinjer. +@msg A panel is not joined to the rest by a crease. En panel är inte förbunden med resten av någon biglinje. +@msg A fold line is on a non-printing layer. En falslinje ligger på ett lager som inte skrivs ut. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Paneler: {panels}, bigningar: {hinges}, fel: {errors}, varningar: {warnings} @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pixlar är för stort för PSD (högst {MAX_SIDE} pixlar per sida): sänk upplösningen diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index a2a38c679a..6dded8c1d7 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -9696,3 +9696,22 @@ breakText Glyphs Glifler No objects are selected. Hiçbir nesne seçili değil. Open a document to mark its fold lines. Katlama çizgilerini işaretlemek için bir belgeyi açın. Remove Fold Line Role Çizgi Türünü Kaldır + Check Denetle + Check Fold Lines Katlama Çizgilerini Denetle +@msg No cut lines are in the selection. Seçimde kesim çizgisi yok. +@msg No cut lines are in the document. Belgede kesim çizgisi yok. +@msg The cut lines do not enclose an area. Kesim çizgileri bir alanı çevrelemiyor. +@msg A cut line ends without meeting another cut line. Bir kesim çizgisi başka bir kesim çizgisiyle buluşmadan bitiyor. +@msg A gap between cut lines was closed. Kesim çizgileri arasındaki bir boşluk kapatıldı. +@msg The fold lines are too complex to check. Katlama çizgileri denetlenemeyecek kadar karmaşık. +@msg A cut line and a crease lie on top of each other. Bir kesim çizgisi ile bir pilyaj çizgisi üst üste. +@msg Two lines of the same role lie on top of each other. Aynı türden iki çizgi üst üste. +@msg A crease ends inside a panel. Bir pilyaj çizgisi bir panelin içinde bitiyor. +@msg A crease does not divide two panels. Bir pilyaj çizgisi iki paneli ayırmıyor. +@msg A crease lies outside the cut outline. Bir pilyaj çizgisi kesim konturunun dışında. +@msg A crease that is not straight is folded along one straight line. Düz olmayan bir pilyaj çizgisi tek bir düz çizgi boyunca katlanır. +@msg A gap between cut lines is too narrow to tell apart. Kesim çizgileri arasındaki bir boşluk ayırt edilemeyecek kadar dar. +@msg A cut-out area holds other fold lines. Kesilip çıkarılmış bir alan başka katlama çizgileri içeriyor. +@msg A panel is not joined to the rest by a crease. Bir panel geri kalanlara hiçbir pilyaj çizgisiyle bağlı değil. +@msg A fold line is on a non-printing layer. Bir katlama çizgisi yazdırılmayan bir katmanda. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Paneller: {panels}, pilyajlar: {hinges}, hatalar: {errors}, uyarılar: {warnings} diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 17c673885d..84eb22f968 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -9349,3 +9349,22 @@ breakText Glyphs Гліфи No objects are selected. Об’єкти не виділено. Open a document to mark its fold lines. Відкрийте документ, щоб позначити його лінії згину. Remove Fold Line Role Прибрати тип лінії + Check Перевірити + Check Fold Lines Перевірити лінії згину +@msg No cut lines are in the selection. У виділенні немає ліній різу. +@msg No cut lines are in the document. У документі немає ліній різу. +@msg The cut lines do not enclose an area. Лінії різу не обмежують жодної області. +@msg A cut line ends without meeting another cut line. Лінія різу закінчується, не зустрівши іншої лінії різу. +@msg A gap between cut lines was closed. Зазор між лініями різу закрито. +@msg The fold lines are too complex to check. Лінії згину надто складні для перевірки. +@msg A cut line and a crease lie on top of each other. Лінія різу та лінія біговки лежать одна на одній. +@msg Two lines of the same role lie on top of each other. Дві лінії одного типу лежать одна на одній. +@msg A crease ends inside a panel. Лінія біговки закінчується всередині панелі. +@msg A crease does not divide two panels. Лінія біговки не розділяє двох панелей. +@msg A crease lies outside the cut outline. Лінія біговки лежить поза контуром різу. +@msg A crease that is not straight is folded along one straight line. Непряма лінія біговки згинається вздовж однієї прямої. +@msg A gap between cut lines is too narrow to tell apart. Зазор між лініями різу надто вузький, щоб його розрізнити. +@msg A cut-out area holds other fold lines. Вирізана область містить інші лінії згину. +@msg A panel is not joined to the rest by a crease. Панель не з’єднана з рештою жодною лінією біговки. +@msg A fold line is on a non-printing layer. Лінія згину лежить на шарі, що не друкується. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Панелі: {panels}, біговки: {hinges}, помилки: {errors}, попередження: {warnings} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index da89525314..00ac3f7289 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7459,6 +7459,25 @@ breakText Glyphs Glyph No objects are selected. Không có đối tượng nào được chọn. Open a document to mark its fold lines. Mở tài liệu để đánh dấu các đường gấp của nó. Remove Fold Line Role Bỏ loại đường + Check Kiểm tra + Check Fold Lines Kiểm tra đường gấp +@msg No cut lines are in the selection. Vùng chọn không có đường cắt nào. +@msg No cut lines are in the document. Tài liệu không có đường cắt nào. +@msg The cut lines do not enclose an area. Các đường cắt không bao quanh vùng nào. +@msg A cut line ends without meeting another cut line. Một đường cắt kết thúc mà không gặp đường cắt khác. +@msg A gap between cut lines was closed. Đã đóng một khe hở giữa các đường cắt. +@msg The fold lines are too complex to check. Các đường gấp quá phức tạp để kiểm tra. +@msg A cut line and a crease lie on top of each other. Một đường cắt và một đường cấn nằm chồng lên nhau. +@msg Two lines of the same role lie on top of each other. Hai đường cùng loại nằm chồng lên nhau. +@msg A crease ends inside a panel. Một đường cấn kết thúc bên trong một mặt. +@msg A crease does not divide two panels. Một đường cấn không chia tách hai mặt. +@msg A crease lies outside the cut outline. Một đường cấn nằm ngoài đường viền cắt. +@msg A crease that is not straight is folded along one straight line. Đường cấn không thẳng được gấp theo một đường thẳng. +@msg A gap between cut lines is too narrow to tell apart. Khe hở giữa các đường cắt quá hẹp để phân biệt. +@msg A cut-out area holds other fold lines. Một vùng bị cắt bỏ chứa các đường gấp khác. +@msg A panel is not joined to the rest by a crease. Một mặt không được nối với phần còn lại bằng đường cấn nào. +@msg A fold line is on a non-printing layer. Một đường gấp nằm trên lớp không in. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Mặt: {panels}, đường cấn: {hinges}, lỗi: {errors}, cảnh báo: {warnings} # Messages of the effects, 3D, image export, color profiles, swatch exchange files, color books and DXF import. @msg 3D effects require finite coordinates within 100 million points Hiệu ứng 3D yêu cầu tọa độ hữu hạn trong phạm vi 100 triệu điểm diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5f612cb0d4..40f821ffe4 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -9580,4 +9580,23 @@ breakText Glyphs 字形 No objects are selected. 未选择任何对象。 Open a document to mark its fold lines. 打开文档以标记其折线。 Remove Fold Line Role 移除线条类型 + Check 检查 + Check Fold Lines 检查折线 +@msg No cut lines are in the selection. 所选内容中没有切割线。 +@msg No cut lines are in the document. 文档中没有切割线。 +@msg The cut lines do not enclose an area. 切割线未围成任何区域。 +@msg A cut line ends without meeting another cut line. 一条切割线未与其他切割线相接就结束了。 +@msg A gap between cut lines was closed. 已闭合切割线之间的间隙。 +@msg The fold lines are too complex to check. 折线过于复杂,无法检查。 +@msg A cut line and a crease lie on top of each other. 一条切割线与一条压痕线重叠。 +@msg Two lines of the same role lie on top of each other. 两条同类线条重叠。 +@msg A crease ends inside a panel. 一条压痕线在面板内部结束。 +@msg A crease does not divide two panels. 一条压痕线没有分隔两个面板。 +@msg A crease lies outside the cut outline. 一条压痕线位于切割轮廓之外。 +@msg A crease that is not straight is folded along one straight line. 不直的压痕线沿一条直线折叠。 +@msg A gap between cut lines is too narrow to tell apart. 切割线之间的间隙太窄,无法区分。 +@msg A cut-out area holds other fold lines. 一个镂空区域包含其他折线。 +@msg A panel is not joined to the rest by a crease. 一个面板没有通过任何压痕线与其余部分相连。 +@msg A fold line is on a non-printing layer. 一条折线位于不打印的图层上。 +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} 面板:{panels},压痕:{hinges},错误:{errors},警告:{warnings} @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} 像素对 PSD 而言过大 (每边最多 {MAX_SIDE} 像素):请降低分辨率 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e0b5a13ee2..434723a718 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -9390,4 +9390,23 @@ breakText Glyphs 字符 No objects are selected. 未選取任何物件。 Open a document to mark its fold lines. 開啟文件以標記其摺線。 Remove Fold Line Role 移除線條類型 + Check 檢查 + Check Fold Lines 檢查摺線 +@msg No cut lines are in the selection. 選取範圍中沒有切割線。 +@msg No cut lines are in the document. 文件中沒有切割線。 +@msg The cut lines do not enclose an area. 切割線未圍成任何區域。 +@msg A cut line ends without meeting another cut line. 一條切割線未與其他切割線相接就結束了。 +@msg A gap between cut lines was closed. 已封閉切割線之間的間隙。 +@msg The fold lines are too complex to check. 摺線過於複雜,無法檢查。 +@msg A cut line and a crease lie on top of each other. 一條切割線與一條壓痕線重疊。 +@msg Two lines of the same role lie on top of each other. 兩條同類線條重疊。 +@msg A crease ends inside a panel. 一條壓痕線在面板內部結束。 +@msg A crease does not divide two panels. 一條壓痕線沒有分隔兩個面板。 +@msg A crease lies outside the cut outline. 一條壓痕線位於切割輪廓之外。 +@msg A crease that is not straight is folded along one straight line. 不直的壓痕線沿一條直線摺疊。 +@msg A gap between cut lines is too narrow to tell apart. 切割線之間的間隙太窄,無法區分。 +@msg A cut-out area holds other fold lines. 一個鏤空區域包含其他摺線。 +@msg A panel is not joined to the rest by a crease. 一個面板沒有透過任何壓痕線與其餘部分相連。 +@msg A fold line is on a non-printing layer. 一條摺線位於不列印的圖層上。 +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} 面板:{panels},壓痕:{hinges},錯誤:{errors},警告:{warnings} @msg {what} would print on more than {MAX_TILES} tiles: scale it down {what} 會列印在超過 {MAX_TILES} 個拼貼上:請縮小 diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 3e48476a1a..845ea7102a 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -195,6 +195,11 @@ pub fn invoke(app: &mut VectorcraftApp, id: &str, p: Value) { } return; } + // Check Fold Lines shows its summary and lists its issues in the Fold Lines panel. + if id == crate::addons::packaging::CHECK { + crate::addons::packaging::check(app, p); + return; + } // A Paste the user gives decodes a bitmap off the UI thread ([`crate::placing::adopt_for_paste`]). app.placing.for_user = id.starts_with("edit.paste"); let r = app.run(id, p); diff --git a/docs/mcp.md b/docs/mcp.md index c7aa202d3f..e552ec49b7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13033,9 +13033,10 @@ there is no step. → `{symbols: [name…], ids: [instance id…], skipped: [{la ## Packaging Tools add-on Packaging Tools is a built-in add-on for the dielines of boxes and other folded packaging. Its commands are -`addon.packaging.setRole`, `addon.packaging.roles` and `addon.packaging.setRoleSwatch`. In the desktop app, Object › -Plug-ins › Packaging Tools › Fold Lines opens the Fold Lines panel, and Make Cut Line, Make Crease Line, Make Partial Cut -Line and Make Perforation Line run `addon.packaging.setRole` on the selection. +`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch` and `addon.packaging.check`. In the +desktop app, Object › Plug-ins › Packaging Tools › Fold Lines opens the Fold Lines panel, Make Cut Line, Make Crease Line, +Make Partial Cut Line and Make Perforation Line run `addon.packaging.setRole` on the selection, and Check Fold Lines runs +`addon.packaging.check`. ### Fold line roles @@ -13082,6 +13083,55 @@ panel's menu opens it as Role Swatches…. {"name":"run_command","arguments":{"command":"addon.packaging.setRole","params":{"role":"crease"}}} ``` +### Check Fold Lines + +`addon.packaging.check` (`{ids?, select?: false, tolerance?: 0.1}`) finds the blanks, panels and hinges that the fold +lines make and lists what is wrong with them. It checks the fold lines among the objects (the selection by default), +through groups and clip groups, or every fold line of the document that is shown while nothing is selected and `ids` is +left out. `tolerance` is in points, from 0.01 to 10; a value outside that range, or one that is not a number or a length +such as `"2 mm"`, is an error. The command does not change the document and records no undo step. + +- Cut lines bound the material. Each connected piece of cut lines that encloses material is one blank. Its outline is its + largest closed cut line, and a closed cut line inside the outline is a hole, so a slot drawn as a rectangle across the + outline leaves the same material as a notch drawn in it. Open cut lines that meet end to end count as one closed cut + line, so an outline or a slot drawn as several open cut lines works as well. +- Crease, Partial Cut and Perforation lines divide a blank into panels. The pieces of them that lie between the same two + panels form one hinge. +- The end of a cut line that comes within `tolerance` of another cut line is joined to it with a short line, and the + check reports the gap. + +The issues come in this order. `noCut`, `open`, `looseEnd`, `tooComplex` and `cutOverCrease` are errors; the others are +warnings. + +| Code | Reported when | +|---|---| +| `noCut` | No cut line is among the objects. | +| `open` | The cut lines enclose no area. | +| `looseEnd` | An end of a cut line meets no other fold line within `tolerance`, and no gap is closed at it. `at` is the end. | +| `gap` | An end of a cut line lies within `tolerance` of another cut line without touching it; the panels are built with the gap closed. `at` is the end. | +| `tooComplex` | The lines have more than 65,536 segments, or a blank has more than 256 panels. | +| `cutOverCrease` | A cut line and a crease, partial cut or perforation lie on top of each other. | +| `duplicate` | Two lines of the same role, or two subpaths of one line, lie on top of each other. | +| `danglingCrease` | A crease ends inside a panel. | +| `noSplit` | A crease divides no two panels. | +| `outside` | A crease lies outside every blank. | +| `notStraight` | The pieces of a hinge are not on one straight line within `tolerance`; it folds along the line through its longest piece. | +| `sliver` | A gap between lines inside a blank is narrower than 0.01 pt. | +| `ambiguous` | A hole holds creases, or a blank lies inside another blank's hole. | +| `loosePanel` | A panel is joined to its blank's largest panel by no chain of hinges. | +| `nonPrinting` | A fold line is on a layer that does not print. | + +Result: `{ok, blanks, panels, hinges, holes, issues: [{severity, code, message, ids, at?}], scope}`. `ok` is true when +no issue is an error. `message` is in English, and the Fold Lines panel shows it in the interface language. `ids` names +the objects each issue is about. With `select: true`, those objects become the selection; when no issue names an +object, the selection stays as it is. The Fold Lines panel's Check button runs the same check, shows a summary line +(panels, creases, errors and warnings) and lists the issues; clicking an issue or its Select button selects its objects. +The list is shown until the document changes. + +```json +{"name":"run_command","arguments":{"command":"addon.packaging.check","params":{"tolerance":0.5,"select":true}}} +``` + ## Image Tools add-on Image Tools is a built-in add-on for placed images: its commands are `addon.image.removeBackground`, From f8fe5f06e1536348d94916feed4193dbe93744be Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 03:32:59 -0800 Subject: [PATCH 09/31] .ai graphs: Draw Filled Lines and its Line Width open live and save through the Gy record A line graph whose style record draws its lines as shapes now opens as a live graph with Draw Filled Lines on, and its lineShapeWidth becomes the Line Width (3 pt reads as the default). The flag is ignored when the points are not connected, as the published file format specification says (printed pp. 147-148). Saving writes both values in the Gy record. - Widths from 0.01 to 100 pt are kept. A wider Line Width, a width under 0.01 pt with filled lines, and filled lines without connected points are saved as the graph's art with the existing warning. - In a filled-line series, a filled path with the thin black band outline is read as a band and does not set the series stroke. A filled path with another outline must be a square marker or legend swatch; otherwise the graph keeps its art as plain objects. - The reader in crates/eps/src/import/ai/read/graph.rs reads each value the writer in crates/eps/src/ai_graph.rs writes; the save-then-open tests cover the default, 8 pt and 150 pt widths in both .ai forms. --- crates/doc/src/graph.rs | 3 + crates/doc/src/lib.rs | 5 +- crates/engine/src/cmd/graph/labels.rs | 2 +- crates/engine/src/cmd/graph/tests.rs | 43 +++++++ crates/eps/src/ai_graph.rs | 172 +++++++++++++++++++++---- crates/eps/src/import/ai/read/graph.rs | 108 +++++++++++++--- crates/eps/src/import/ai/tests.rs | 64 ++++++++- docs/mcp.md | 6 +- docs/target-app-parity.md | 2 +- 9 files changed, 356 insertions(+), 49 deletions(-) diff --git a/crates/doc/src/graph.rs b/crates/doc/src/graph.rs index 2213190df6..36fe29a8f2 100644 --- a/crates/doc/src/graph.rs +++ b/crates/doc/src/graph.rs @@ -575,6 +575,9 @@ pub const DEFAULT_FILLED_LINE_WIDTH: f64 = 3.0; pub const MIN_FILLED_LINE_WIDTH: f64 = 0.01; pub const MAX_FILLED_LINE_WIDTH: f64 = 1000.0; +/// The weight of the black outline Draw Filled Lines draws around each band, in points. +pub const FILLED_LINE_OUTLINE_WIDTH: f64 = 0.25; + impl GraphSpec { /// How wide Draw Filled Lines draws a line, in points: [`Self::line_width`], else [`DEFAULT_FILLED_LINE_WIDTH`]. A /// width a file gives outside [`MIN_FILLED_LINE_WIDTH`] to [`MAX_FILLED_LINE_WIDTH`], or not finite, draws the diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 2d956ed30a..4164234a77 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -96,8 +96,9 @@ pub use compound_shape::ShapeMode; pub use corners::LiveCorners; pub use depth::{MAX_DEPTH, MAX_SYMBOL_NODES}; pub use graph::{ - ColumnDesign, ColumnType, DEFAULT_FILLED_LINE_WIDTH, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows, LabelStyles, MAX_FILLED_LINE_WIDTH, - MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, MIN_FILLED_LINE_WIDTH, PiePosition, PieSort, SeriesPaint, TickLength, ValueAxisSide, + ColumnDesign, ColumnType, DEFAULT_FILLED_LINE_WIDTH, FILLED_LINE_OUTLINE_WIDTH, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows, + LabelStyles, MAX_FILLED_LINE_WIDTH, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, MIN_FILLED_LINE_WIDTH, PiePosition, PieSort, SeriesPaint, TickLength, + ValueAxisSide, }; pub use hit::{Hit, HitKind}; pub use links::{LinkInfo, PlacementOptions}; diff --git a/crates/engine/src/cmd/graph/labels.rs b/crates/engine/src/cmd/graph/labels.rs index e6b9a6711b..b5d5632356 100644 --- a/crates/engine/src/cmd/graph/labels.rs +++ b/crates/engine/src/cmd/graph/labels.rs @@ -244,7 +244,7 @@ impl Gen<'_> { let slot = g.series_paints.get(s); let fill = slot.and_then(|p| p.fill.clone().or_else(|| p.stroke.clone().filter(|st| !st.is_none()))).unwrap_or_else(|| default_series_paint(s)); - return self.path(band, fill, Paint::solid(Color::BLACK), 0.25); + return self.path(band, fill, Paint::solid(Color::BLACK), vectorcraft_doc::FILLED_LINE_OUTLINE_WIDTH); } let (fill, stroke, w) = series_marks(g, s, false, default_series_paint(s), 1.0); self.path(pd, fill, stroke, w) diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 83c45ef498..9624e8dbb7 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -9505,6 +9505,49 @@ fn a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns() { } } +/// A line graph the graph tools draw with Draw Filled Lines, saved as `.ai` in either form, opens again as the same graph +/// with its filled lines and Line Width, the default 3 pt included, and without a warning about graphs. A Line Width past +/// the records' 100 pt is saved as the graph's art, with the warning. +#[test] +fn a_drawn_graph_with_filled_lines_saved_as_ai_opens_with_them() { + let dir = vectorcraft_testkit::temp_dir("graph-ai-filled"); + for (width, live) in [(None, true), (Some(8.0), true), (Some(150.0), false)] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,1,6"; + let id = s.execute("graph.create", &json!({"type": "line", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"] + .as_u64() + .unwrap(); + let mut options = json!({"id": id, "filledLines": true}); + if let Some(w) = width { + options["lineWidth"] = json!(w); + } + s.execute("graph.setType", &options).unwrap(); + let written = spec(&s, NodeId(id)); + assert_eq!((written.filled_lines, written.line_width), (true, width)); + for (name, version) in [("v7.ai", Some("7")), ("pdf.ai", None)] { + let path = dir.join(format!("{width:?}-{name}")); + let mut p = json!({"path": path, "format": "ai"}); + if let Some(v) = version { + p["aiVersion"] = json!(v); + } + let r = s.execute("file.saveAs", &p).unwrap(); + let notes = r["warnings"].as_array().cloned().unwrap_or_default(); + let warned = notes.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("graphs are written as their art"))); + assert_eq!(warned, !live, "{width:?} {name}: {r}"); + let mut again = Session::new(); + again.execute("document.open", &json!({"path": path})).unwrap(); + let mut graphs = vec![]; + again.doc().unwrap().doc.walk(|n| graphs.extend(n.extras().graph.as_deref().cloned())); + assert_eq!(graphs.len(), usize::from(live), "{width:?} {name}"); + if let Some(g) = graphs.first() { + assert_eq!((g.kind, g.cells(), g.filled_lines, g.line_width), (written.kind, written.cells(), true, width), "{width:?} {name}"); + assert_eq!(g.filled_line_width(), written.filled_line_width(), "{width:?} {name}"); + } + } + } +} + /// A default legend swatch has the stroke paint and weight of its series' marks, beside the plot or across the top: the /// thin white line of stacked columns and bars, areas and pie wedges, and none on columns and bars. A stroke color kept /// on the series, with or without a weight of its own, is on the swatch too. diff --git a/crates/eps/src/ai_graph.rs b/crates/eps/src/ai_graph.rs index d2db08229f..cb20f0cb99 100644 --- a/crates/eps/src/ai_graph.rs +++ b/crates/eps/src/ai_graph.rs @@ -17,8 +17,8 @@ use std::fmt::Write; use kurbo::{PathSeg, Point}; use vectorcraft_color::{BlendMode, Paint}; use vectorcraft_doc::{ - Appearance, AppearanceItem, GraphKind, GraphSpec, LabelStyles, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, Node, NodeId, NodeKind, PiePosition, - PieSort, TickLength, ValueAxisSide, + Appearance, AppearanceItem, DEFAULT_FILLED_LINE_WIDTH, FILLED_LINE_OUTLINE_WIDTH, GraphKind, GraphSpec, LabelStyles, MAX_GRAPH_CATEGORIES, + MAX_GRAPH_SERIES, MIN_FILLED_LINE_WIDTH, Node, NodeId, NodeKind, PiePosition, PieSort, TickLength, ValueAxisSide, }; use vectorcraft_effects::stroke; use vectorcraft_geom::{Affine, Rect}; @@ -46,6 +46,9 @@ const EDGE: f64 = 0.01; /// Most values one `Gc` takes. const CELLS_PER_RECORD: usize = 15; +/// Widest `lineShapeWidth` the records give, in points (appendix A, `Gy`). +const MAX_LINE_WIDTH: f64 = 100.0; + /// A graph's records: what goes before its group (`%_Gs` to `%_GC`), and the `Go` line that follows /// each series' group, by the group's id. `%_GS` follows the group. pub(crate) struct Records { @@ -89,7 +92,8 @@ pub(crate) fn records(n: &Node, to_art: Affine) -> Option { (r.is_finite() && r.width() > 0.0 && r.height() > 0.0).then_some(())?; let plot = to_art.transform_rect_bbox(r); (plot.is_finite() && plot.width() > 0.0 && plot.height() > 0.0).then_some(())?; - let tags = series_groups(children, width, first_col, g.kind == GraphKind::Line)?; + let line = g.kind == GraphKind::Line; + let tags = series_groups(children, width, first_col, line, line && g.filled_lines)?; draws_axes(n, r).then_some(())?; let placed = n.geometric_bounds()?; (r.x0 >= placed.x0 - EDGE && r.y0 >= placed.y0 - EDGE && r.x1 <= placed.x1 + EDGE && r.y1 <= placed.y1 + EDGE).then_some(())?; @@ -97,14 +101,17 @@ pub(crate) fn records(n: &Node, to_art: Affine) -> Option { let mut head = String::from("%_Gs\n"); let _ = writeln!(head, "%_{} {} {} {} Gb", real(plot.x0), real(plot.y1), real(plot.x1), real(plot.y0)); let flag = |b: bool| u8::from(b); + // `lineShapeWidth`: the width filled lines are drawn at, the graph's default included. let _ = writeln!( head, - "%_{ty} {} {} 14 {} {} 0 {} 6 44 Gy", + "%_{ty} {} {} 14 {} {} {} {} {} 44 Gy", flag(g.drop_shadow), flag(g.first_row_in_front), flag(g.mark_points), flag(g.connect_points), - flag(g.legend_across_top) + flag(g.filled_lines), + flag(g.legend_across_top), + real(g.line_width.unwrap_or(DEFAULT_FILLED_LINE_WIDTH)) ); let _ = writeln!(head, "%_10 2 {} 0 {} {} {} Gd", flag(g.first_column_in_front), real(g.column_width), real(g.cluster_width), flag(g.edge_to_edge)); @@ -233,10 +240,11 @@ fn tick(t: TickLength) -> u8 { } /// Whether `g`'s settings are ones the records give and the reader keeps: a legend beside or across -/// the top, every series of the graph's type, one value axis on the left, lines not filled and no -/// Line Width of their own, no graph -/// designs, label formatting or pie settings, column and cluster widths of 1% to 1000%, and at most -/// [`MAX_TICK_MARKS`] tick marks a division. +/// the top, every series of the graph's type, one value axis on the left, lines filled only where +/// they connect the points (the records ignore the setting otherwise), a Line Width of 0.01 to +/// [`MAX_LINE_WIDTH`] points, with filled lines no series stroked as the bands' outline +/// ([`band_outline`]), which the reader reads as bands, no graph designs, label formatting or pie settings, column and +/// cluster widths of 1% to 1000%, and at most [`MAX_TICK_MARKS`] tick marks a division. fn settings_kept(g: &GraphSpec) -> bool { let percent = |p: f64| (1.0..=1000.0).contains(&p); g.legend @@ -244,8 +252,9 @@ fn settings_kept(g: &GraphSpec) -> bool { && g.value_axis == ValueAxisSide::Left && !g.separate_scales && g.right_series.is_empty() - && !g.filled_lines - && g.line_width.is_none() + && (g.connect_points || !g.filled_lines) + && g.line_width.is_none_or(|w| (MIN_FILLED_LINE_WIDTH..=MAX_LINE_WIDTH).contains(&w)) + && !(g.kind == GraphKind::Line && g.filled_lines && g.series_paints.iter().any(|p| band_outline(&p.stroke.clone().zip(p.stroke_width)))) && g.series_markers.iter().all(Option::is_none) && g.series_columns.iter().all(Option::is_none) && g.label_styles == LabelStyles::default() @@ -320,10 +329,13 @@ fn plain_paint(p: &Node) -> Option<(Option, Option<(Paint, f64)>)> { /// The `Go` line of each series' group among `children`: a group whose series index is one of the /// `series` the table has, each once, of paths [`as_drawn`] with one fill and one line alike -/// ([`plain_paint`]), every path filled unless the graph draws lines (`line`). Its column is the +/// ([`plain_paint`]), every path filled unless the graph draws lines (`line`). With filled lines +/// (`bands`), a filled path outlined as [`band_outline`] says is a band, any other filled path is a +/// [`square`] marker or swatch, and the line of the paths that are not bands is the series' line, +/// as the reader reads it. Its column is the /// table's: after the label column when there is one (`first_col`). `None` when a series has no /// such group. -fn series_groups(children: &[std::sync::Arc], series: usize, first_col: usize, line: bool) -> Option> { +fn series_groups(children: &[std::sync::Arc], series: usize, first_col: usize, line: bool, bands: bool) -> Option> { let mut tags = HashMap::new(); let mut seen = vec![false; series]; for c in children { @@ -334,21 +346,63 @@ fn series_groups(children: &[std::sync::Arc], series: usize, first_col: us *slot = true; let NodeKind::Group { children: paths, clip: false } = &c.kind else { return None }; (as_drawn(c) && *c.appearance == Appearance::default() && !paths.is_empty()).then_some(())?; - let mut paints = vec![]; + let (mut paints, mut strokes) = (vec![], vec![]); for p in paths { as_drawn(p).then_some(())?; - paints.push(plain_paint(p)?); + let (fill, outline) = plain_paint(p)?; + if bands && fill.is_some() && band_outline(&outline) { + // A band, or a mark outlined as one, which the reader reads as a band. + } else if bands && fill.is_some() && !square(p) { + return None; + } else { + strokes.push(outline); + } + paints.push(fill); } - let fill = paints.iter().find_map(|(f, _)| f.clone()); - paints.iter().all(|(f, _)| f.is_none() || *f == fill).then_some(())?; - (line || paints.iter().all(|(f, _)| f.is_some())).then_some(())?; - let stroke = paints.first().and_then(|(_, s)| s.clone()); - paints.iter().all(|(_, s)| *s == stroke).then_some(())?; + let fill = paints.iter().find_map(Clone::clone); + paints.iter().all(|f| f.is_none() || *f == fill).then_some(())?; + (line || paints.iter().all(Option::is_some)).then_some(())?; + let stroke = strokes.first().cloned().flatten(); + strokes.iter().all(|s| *s == stroke).then_some(())?; tags.insert(c.id, format!("%_2 {} 0 0 Go", s + first_col)); } seen.iter().all(|s| *s).then_some(tags) } +/// Whether `stroke`, a path's line and its weight, is the thin black outline Draw Filled Lines +/// draws around a band, whatever the series' own line. +pub(crate) fn band_outline(stroke: &Option<(Paint, f64)>) -> bool { + stroke + .as_ref() + .is_some_and(|(paint, width)| *width == FILLED_LINE_OUTLINE_WIDTH && paint.color().is_some_and(|c| c.to_rgb_uncalibrated() == [0.0; 3])) +} + +/// Whether path `p` is a square with sides along the page's axes, as a data point's default +/// marker and a legend swatch are: four straight sides, closed, as wide as it is tall. In a series +/// with filled lines, every other filled path is a band. +pub(crate) fn square(p: &Node) -> bool { + let NodeKind::Path { path, .. } = &p.kind else { return false }; + if path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()).count() != 1 { + return false; + } + let near = |a: f64, b: f64| (a - b).abs() <= EDGE; + let mut sides = vec![]; + for s in path.to_bezpath().segments() { + let PathSeg::Line(l) = s else { return false }; + if !(near(l.p0.x, l.p1.x) && near(l.p0.y, l.p1.y)) { + sides.push(l); + } + } + let [first, _, _, last] = sides.as_slice() else { return false }; + let (x0, x1) = sides.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), l| (lo.min(l.p0.x), hi.max(l.p0.x))); + let (y0, y1) = sides.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), l| (lo.min(l.p0.y), hi.max(l.p0.y))); + near(last.p1.x, first.p0.x) + && near(last.p1.y, first.p0.y) + && sides.iter().all(|l| near(l.p0.x, l.p1.x) || near(l.p0.y, l.p1.y)) + && x1 - x0 > EDGE + && near(x1 - x0, y1 - y0) +} + /// Whether `art` draws plot `plot`'s left edge and its bottom edge (the document's y runs down) as /// straight lines, each a shown path of one subpath with a plain line ([`plain_paint`]) in a shown /// group, as the reader finds the axes. @@ -409,7 +463,8 @@ pub(crate) mod sample { } /// Graph `g` drawn as a group: a group of each series' marks (a line graph's series as an unfilled - /// line, the others' as filled columns), its axes on the plot's left and bottom edges, and a + /// line, or with filled lines as an outlined band and its markers, the others' as filled + /// columns), its axes on the plot's left and bottom edges, and a /// legend of a swatch for each series; its series groups named after the series. pub(crate) fn graph(doc: &mut Document, g: GraphSpec) -> Node { let r = g.rect; @@ -430,7 +485,27 @@ pub(crate) mod sample { row.get(s).copied().flatten().map(|v| Point::new(r.x0 + 20.0 + 60.0 * c as f64 + 15.0 * s as f64, r.y1 - v * 10.0)) }) .collect(); - let marks: Vec> = if g.kind == GraphKind::Line { + let marks: Vec> = if g.kind == GraphKind::Line && g.filled_lines { + // A band around the line, as wide as the Line Width, with the thin black outline, and a + // marker on each point. + let half = g.filled_line_width() / 2.0; + let mut bp = kurbo::BezPath::new(); + for (i, p) in points.iter().enumerate() { + if i == 0 { bp.move_to((p.x, p.y - half)) } else { bp.line_to((p.x, p.y - half)) } + } + for p in points.iter().rev() { + bp.line_to((p.x, p.y + half)); + } + bp.close_path(); + let band = Node::path( + doc.alloc_id(), + PathData::from_bezpath(&bp), + Appearance::basic(gray.clone(), Paint::solid(Color::BLACK), super::FILLED_LINE_OUTLINE_WIDTH), + ); + let mut marks = vec![Arc::new(band)]; + marks.extend(points.iter().map(|p| path(doc, shapes::rectangle(Rect::from_center_size(*p, (5.0, 5.0))), gray.clone(), Paint::None))); + marks + } else if g.kind == GraphKind::Line { let mut bp = kurbo::BezPath::new(); for (i, p) in points.iter().enumerate() { if i == 0 { bp.move_to(*p) } else { bp.line_to(*p) } @@ -472,7 +547,7 @@ pub(crate) mod sample { /// Graphs whose records read back whole: each type the records give, every setting they keep /// changed, labels with parentheses, backslashes and non-ASCII characters, a label of 255 bytes, - /// and a table without labels. + /// a table without labels, and line graphs with filled lines and Line Widths the records give. pub(crate) fn kept() -> Vec<(&'static str, Document)> { let mut cases = vec![ ("column", document(spec(GraphKind::Column))), @@ -497,6 +572,18 @@ pub(crate) mod sample { let mut g = spec(GraphKind::Column); (g.series, g.categories) = (vec![], vec![]); cases.push(("no labels", document(g))); + let line = |f: &dyn Fn(&mut GraphSpec)| { + let mut g = spec(GraphKind::Line); + f(&mut g); + document(g) + }; + cases.extend([ + ("filled lines", line(&|g| g.filled_lines = true)), + ("filled lines 8 pt wide", line(&|g| (g.filled_lines, g.line_width) = (true, Some(8.0)))), + ("filled lines 100 pt wide", line(&|g| (g.filled_lines, g.line_width) = (true, Some(100.0)))), + ("filled lines 0.01 pt wide", line(&|g| (g.filled_lines, g.line_width) = (true, Some(0.01)))), + ("a Line Width without filled lines", line(&|g| g.line_width = Some(8.0))), + ]); cases } @@ -515,8 +602,20 @@ pub(crate) mod sample { .collect(); cases.extend([ ("no legend", with(&|g| g.legend = false)), - ("filled lines", with(&|g| (g.kind, g.filled_lines) = (GraphKind::Line, true))), - ("a filled line width", with(&|g| (g.kind, g.line_width) = (GraphKind::Line, Some(8.0)))), + ("a Line Width past 100 pt", with(&|g| (g.kind, g.filled_lines, g.line_width) = (GraphKind::Line, true, Some(150.0)))), + ("a Line Width under 0.01 pt", with(&|g| (g.kind, g.filled_lines, g.line_width) = (GraphKind::Line, true, Some(0.001)))), + ("filled lines without connected points", with(&|g| (g.kind, g.filled_lines, g.connect_points) = (GraphKind::Line, true, false))), + ( + "filled lines with series stroked as their outline", + with(&|g| { + (g.kind, g.filled_lines) = (GraphKind::Line, true); + g.series_paints = vec![vectorcraft_doc::SeriesPaint { + stroke: Some(Paint::solid(Color::BLACK)), + stroke_width: Some(super::FILLED_LINE_OUTLINE_WIDTH), + ..Default::default() + }]; + }), + ), ("a series of another type", with(&|g| g.series_kinds = vec![None, Some(GraphKind::Line)])), ("a marker design", with(&|g| g.series_markers = vec![Some("Star".into())])), ("a column design", with(&|g| g.series_columns = vec![Some(Default::default())])), @@ -645,6 +744,29 @@ mod tests { assert_eq!(marks, ["1", "1", "1"], "{head}"); } + /// A marker or swatch is a square along the page's axes; a band, a rotated square, a rectangle + /// of other proportions and an open path are not. + #[test] + fn markers_are_squares_and_bands_are_not() { + use vectorcraft_geom::shapes; + let node = |p: vectorcraft_geom::PathData| Node::path(NodeId(1), p, Appearance::default()); + assert!(square(&node(shapes::rectangle(Rect::new(10.0, 10.0, 15.0, 15.0)))), "a 5 pt marker"); + assert!(!square(&node(shapes::rectangle(Rect::new(10.0, 10.0, 60.0, 13.0)))), "a band along a level line"); + let mut diamond = kurbo::BezPath::new(); + diamond.move_to((0.0, 5.0)); + diamond.line_to((5.0, 0.0)); + diamond.line_to((10.0, 5.0)); + diamond.line_to((5.0, 10.0)); + diamond.close_path(); + assert!(!square(&node(vectorcraft_geom::PathData::from_bezpath(&diamond))), "a rotated square"); + let mut open = kurbo::BezPath::new(); + open.move_to((0.0, 0.0)); + for p in [(5.0, 0.0), (5.0, 5.0), (0.0, 5.0), (0.0, 1.0)] { + open.line_to(p); + } + assert!(!square(&node(vectorcraft_geom::PathData::from_bezpath(&open))), "an open path"); + } + /// A table's cells go fifteen to a record, with one string at most in each. #[test] fn cells_go_fifteen_to_a_record_with_one_string_each() { diff --git a/crates/eps/src/import/ai/read/graph.rs b/crates/eps/src/import/ai/read/graph.rs index 609713fe16..49d9ba7aa5 100644 --- a/crates/eps/src/import/ai/read/graph.rs +++ b/crates/eps/src/import/ai/read/graph.rs @@ -14,10 +14,14 @@ use std::collections::{HashMap, HashSet}; use std::sync::Arc; use kurbo::{PathSeg, Point}; -use vectorcraft_doc::{Appearance, GraphKind, GraphSpec, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, SeriesPaint, TickLength}; +use vectorcraft_doc::{ + Appearance, DEFAULT_FILLED_LINE_WIDTH, GraphKind, GraphSpec, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, MIN_FILLED_LINE_WIDTH, SeriesPaint, + TickLength, +}; use super::types::{GRAPH_OPS, GRAPH_PLAIN, GRAPH_UNENDED, Kind}; use super::{Affine, AppearanceItem, BlendMode, Node, NodeId, NodeKind, Paint, Reader, Rect, V, obj}; +use crate::ai_graph::{band_outline, square}; /// Most cells of a graph's table, its label row and column included. const MAX_CELLS: usize = 2_600_000; @@ -293,11 +297,20 @@ impl Records { self.spec.legend = true; self.spec.mark_points = flag(marks)?; self.spec.connect_points = flag(lines)?; - // Lines drawn as shapes have a width the model doesn't keep. - (!flag(shapes)?).then_some(())?; - self.spec.filled_lines = false; + // Lines drawn as shapes (Draw Filled Lines); without connected points the flag is ignored. + self.spec.filled_lines = flag(shapes)? && self.spec.connect_points; self.spec.legend_across_top = flag(across)?; - finite(width).filter(|w| (0.0..=100.0).contains(w))?; + // `lineShapeWidth`, in points from 0 to 100. The model holds widths from 0.01 points, 3 points + // being its default; a smaller width is left out while the lines aren't filled, and keeps + // filled lines plain. + let width = finite(width).filter(|w| (0.0..=100.0).contains(w))?; + self.spec.line_width = if width == DEFAULT_FILLED_LINE_WIDTH { + None + } else if width >= MIN_FILLED_LINE_WIDTH { + Some(width) + } else { + (!self.spec.filled_lines).then_some(None)? + }; // 44: the series are measured against the left axis; 45 (right) isn't kept per series. (int(axis)? == 44).then_some(())?; if let Some([percentage, digits]) = pie { @@ -471,9 +484,13 @@ fn as_drawn(n: &Node) -> bool { /// Each series' fill and stroke, read from its group (`tags`), which holds paths only, one at /// least: the paths with a fill share it, and every path has the same stroke or none. Only a line -/// graph (`line`) has paths without a fill: its lines. `None` when they differ, or the group, its -/// own appearance or a path is drawn otherwise than [`as_drawn`]. -fn series_paints(art: &Node, tags: &HashMap, line: bool) -> Option> { +/// graph (`line`) has paths without a fill: its lines. With filled lines (`bands`), a filled path +/// outlined as [`band_outline`] says is a band or a mark drawn like one and gives no stroke; any +/// other filled path but a [`square`] marker or legend swatch is a band outlined otherwise. The +/// other paths give the series' stroke, and without them the series has none. `None` when they +/// differ, a band has another outline, or the group, its own appearance or a path is drawn +/// otherwise than [`as_drawn`]. +fn series_paints(art: &Node, tags: &HashMap, line: bool, bands: bool) -> Option> { let mut paints = vec![SeriesPaint::default(); tags.len()]; for group in art.children().into_iter().flatten() { let Some(slot) = tags.get(&group.id).and_then(|i| paints.get_mut(usize::try_from(*i).ok()?)) else { continue }; @@ -483,8 +500,17 @@ fn series_paints(art: &Node, tags: &HashMap, line: bool) -> Option< let (mut fills, mut strokes) = (vec![], vec![]); for p in &paths { as_drawn(p).then_some(())?; - fills.extend(shown(p, true).ok()?); - strokes.push(shown(p, false).ok()?); + let filled = shown(p, true).ok()?; + let outline = shown(p, false).ok()?; + if bands && filled.is_some() && band_outline(&outline) { + // A band, or a mark outlined as one: the graph keeps no stroke for a series that draws bands. + } else if bands && filled.is_some() && !square(p) { + // A band outlined otherwise: the graph draws it again with the thin black outline only. + return None; + } else { + strokes.push(outline); + } + fills.extend(filled); } let fill = fills.first().map(|(paint, _)| paint.clone()); fills.iter().all(|(paint, _)| Some(paint) == fill.as_ref()).then_some(())?; @@ -628,7 +654,8 @@ impl<'a> Reader<'a> { if r.x0 < placed.x0 - EDGE || r.y0 < placed.y0 - EDGE || r.x1 > placed.x1 + EDGE || r.y1 > placed.y1 + EDGE { return false; } - let Some(paints) = series_paints(art, &tags, spec.kind == GraphKind::Line) else { return false }; + let line = spec.kind == GraphKind::Line; + let Some(paints) = series_paints(art, &tags, line, line && spec.filled_lines) else { return false }; spec.series_paints = paints; spec.placed = Some(placed); spec.placed_art = art.children().and_then(|c| vectorcraft_doc::graph::graph_art_without_type(c)); @@ -646,6 +673,7 @@ impl<'a> Reader<'a> { mod tests { use super::*; use vectorcraft_color::Color; + use vectorcraft_doc::FILLED_LINE_OUTLINE_WIDTH; use vectorcraft_geom::shapes; /// A graph's art: one series group (id 2) holding one mark painted `ap`, the group changed by @@ -665,9 +693,57 @@ mod tests { let mut two = one.clone(); two.items.extend(one.items.iter().find(|i| i.is_fill()).cloned()); let tags = HashMap::from([(NodeId(2), 0)]); - let kept = series_paints(&art(one, |_| {}), &tags, false).expect("one fill"); + let kept = series_paints(&art(one, |_| {}), &tags, false, false).expect("one fill"); assert_eq!((kept[0].fill.as_ref(), kept[0].stroke.as_ref()), (Some(&red), Some(&Paint::None))); - assert!(series_paints(&art(two, |_| {}), &tags, false).is_none()); + assert!(series_paints(&art(two, |_| {}), &tags, false, false).is_none()); + } + + /// With filled lines, a band's thin black outline is not the series' stroke: its markers' stroke + /// is, or none. A band outlined otherwise than its markers has no one stroke. + #[test] + fn a_filled_line_bands_outline_is_not_its_series_stroke() { + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let series = |band: Appearance, marker: Appearance| { + let band = Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 3.0)), band)); + let marker = Arc::new(Node::path(NodeId(4), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), marker)); + Node::group(NodeId(1), vec![Arc::new(Node::group(NodeId(2), vec![band, marker]))]) + }; + let tags = HashMap::from([(NodeId(2), 0)]); + let outlined = Appearance::basic(red.clone(), Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)), FILLED_LINE_OUTLINE_WIDTH); + let marker = Appearance::basic(red.clone(), Paint::None, 0.0); + let kept = series_paints(&series(outlined.clone(), marker.clone()), &tags, true, true).expect("a band and a marker"); + assert_eq!((kept[0].fill.as_ref(), kept[0].stroke.as_ref(), kept[0].stroke_width), (Some(&red), Some(&Paint::None), None)); + let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0)); + let stroked = Appearance::basic(red.clone(), blue.clone(), 2.0); + let kept = series_paints(&series(outlined.clone(), stroked), &tags, true, true).expect("a band and a stroked marker"); + assert_eq!((kept[0].stroke.as_ref(), kept[0].stroke_width), (Some(&blue), Some(2.0))); + let bands_only = Node::group( + NodeId(1), + vec![Arc::new(Node::group( + NodeId(2), + vec![Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 3.0)), outlined.clone()))], + ))], + ); + let kept = series_paints(&bands_only, &tags, true, true).expect("a band alone"); + assert_eq!((kept[0].stroke.as_ref(), kept[0].stroke_width), (Some(&Paint::None), None), "a band alone"); + // A band as long as it is wide is a square, and still a band: its outline is not the series' stroke. + let square_band = |marker: Appearance| { + let band = Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 3.0, 3.0)), outlined.clone())); + let marker = Arc::new(Node::path(NodeId(4), shapes::rectangle(Rect::new(10.0, 0.0, 15.0, 5.0)), marker)); + Node::group(NodeId(1), vec![Arc::new(Node::group(NodeId(2), vec![band, marker]))]) + }; + let kept = series_paints(&square_band(marker.clone()), &tags, true, true).expect("a square band and a marker"); + assert_eq!((kept[0].stroke.as_ref(), kept[0].stroke_width), (Some(&Paint::None), None), "a square band"); + assert!(series_paints(&series(outlined, marker.clone()), &tags, true, false).is_none(), "lines not filled"); + let thick = Appearance::basic(red.clone(), Paint::solid(Color::BLACK), 1.0); + assert!(series_paints(&series(thick, marker), &tags, true, true).is_none(), "a 1 pt outline"); + // A band outlined as its markers are stroked is drawn again with the thin black outline. + assert!(series_paints(&series(stroked_like(&blue), stroked_like(&blue)), &tags, true, true).is_none(), "a band outlined in blue"); + } + + /// A red mark stroked 2 pt in `paint`. + fn stroked_like(paint: &Paint) -> Appearance { + Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), paint.clone(), 2.0) } /// A series group that is hidden, see-through or in another blending mode is not drawn again so. @@ -675,8 +751,8 @@ mod tests { fn a_series_group_drawn_otherwise_has_no_series_paint() { let ap = || Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); let tags = HashMap::from([(NodeId(2), 0)]); - assert!(series_paints(&art(ap(), |g| g.visible = false), &tags, false).is_none(), "hidden"); - assert!(series_paints(&art(ap(), |g| g.opacity = 0.5), &tags, false).is_none(), "50% opaque"); - assert!(series_paints(&art(ap(), |g| g.blend = BlendMode::Multiply), &tags, false).is_none(), "Multiply"); + assert!(series_paints(&art(ap(), |g| g.visible = false), &tags, false, false).is_none(), "hidden"); + assert!(series_paints(&art(ap(), |g| g.opacity = 0.5), &tags, false, false).is_none(), "50% opaque"); + assert!(series_paints(&art(ap(), |g| g.blend = BlendMode::Multiply), &tags, false, false).is_none(), "Multiply"); } } diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index f133a9ee03..5fc5c97629 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -11381,6 +11381,68 @@ fn a_graphs_type_and_settings_come_from_its_records() { assert!(art(&r.doc)[0].extras().graph.is_some()); } +/// A series of a line graph drawn with filled lines at `x`: a band filled with the series' color and +/// outlined in a thin black line, and a marker filled alike with no outline. +fn band_series(x: f64) -> String { + format!("0.5 0 0 0 k\n0 0 0 1 K\n0.25 w\n{}B\n1 w\n{}f\n", rect_path(x, 120.0, x + 40.0, 128.0), rect_path(x + 18.0, 122.0, x + 23.0, 127.0)) +} + +/// [`live_graph`] as a line graph with style record `style`, each series drawn by [`band_series`]. +fn band_graph(style: &str) -> String { + live_graph().replace(LIVE_STYLE, style).replace(&series_bar(110.0), &band_series(110.0)).replace(&series_bar(140.0), &band_series(140.0)) +} + +/// A line graph whose lines are drawn as shapes (`drawLinesAsShapes` 1 with `drawLines` 1) keeps +/// Draw Filled Lines and its Line Width (`lineShapeWidth`, in points): 3 points is the graph's +/// default. Its series keep their bands' fill, and the bands' thin black outline is not taken as the +/// series' stroke. With `drawLines` 0 the flag is ignored, and the width is kept for later. +#[test] +fn a_line_graph_drawn_with_filled_lines_keeps_them_and_their_width() { + let live = |text: String| { + let r = read(stream7(&layer7("Graph", &text)).as_bytes()).unwrap(); + assert!(r.warnings.is_empty(), "{text}: {:?}", r.warnings); + let a = art(&r.doc); + let g = a[0].extras().graph.clone().unwrap_or_else(|| panic!("{text}: a live graph")); + (g, live_graphs(&r.doc).1) + }; + let (g, tagged) = live(band_graph("%_7 0 0 14 1 1 1 0 8 44 Gy\n")); + assert_eq!((g.kind, g.filled_lines, g.line_width, tagged), (GraphKind::Line, true, Some(8.0), 2)); + let fill = Some(Paint::solid(Color::cmyk(0.5, 0.0, 0.0, 0.0))); + assert!(g.series_paints.iter().all(|p| p.fill == fill && p.stroke == Some(Paint::None) && p.stroke_width.is_none()), "{:?}", g.series_paints); + assert_eq!(live(band_graph("%_7 0 0 14 1 1 1 0 3 44 Gy\n")).0.line_width, None, "3 pt"); + assert_eq!(live(band_graph("%_7 0 0 14 1 1 1 0 6 44 Gy\n")).0.line_width, Some(6.0), "6 pt"); + assert_eq!(live(band_graph("%_7 0 0 14 1 1 1 0 100 44 Gy\n")).0.line_width, Some(100.0), "100 pt"); + assert_eq!(live(band_graph("%_7 0 0 14 1 1 1 0 0.01 44 Gy\n")).0.line_width, Some(0.01), "0.01 pt"); + // Without filled lines, the series are drawn as the graph's columns are. + let (g, _) = live(live_graph().replace(LIVE_STYLE, "%_7 0 0 14 1 0 1 0 8 44 Gy\n")); + assert_eq!((g.connect_points, g.filled_lines, g.line_width), (false, false, Some(8.0)), "points not connected"); + let (g, _) = live(live_graph().replace(LIVE_STYLE, "%_7 0 0 14 1 1 0 0 0 44 Gy\n")); + assert_eq!((g.filled_lines, g.line_width), (false, None), "lines not filled, 0 pt"); +} + +/// A graph with filled lines whose Line Width the model doesn't hold (0, under 0.01 points, or out of +/// the records' 0 to 100), or with a lines-as-shapes value other than 0 and 1, keeps its drawn art +/// as plain objects, with one note. +#[test] +fn filled_lines_of_a_width_the_model_cant_hold_stay_plain_art() { + for style in [ + "%_7 0 0 14 1 1 1 0 0 44 Gy\n", + "%_7 0 0 14 1 1 1 0 0.001 44 Gy\n", + "%_7 0 0 14 1 1 1 0 101 44 Gy\n", + "%_7 0 0 14 1 1 1 0 -2 44 Gy\n", + "%_7 0 0 14 1 1 1 0 1e999 44 Gy\n", + "%_7 0 0 14 1 1 0 0 101 44 Gy\n", + "%_7 0 0 14 1 1 2 0 8 44 Gy\n", + ] { + let r = read(stream7(&layer7("Graph", &band_graph(style))).as_bytes()).unwrap_or_else(|e| panic!("{style}: {e}")); + assert_eq!(r.warnings, [GRAPH_PLAIN], "{style}"); + assert_eq!(live_graphs(&r.doc), (vec![], 0), "{style}"); + let mut kept = false; + r.doc.walk(|n| kept |= n.children().is_some_and(|c| c.len() == 3)); + assert!(kept, "{style}: the drawn art is kept"); + } +} + /// A graph keeps its drawn art and stays plain, with one note, when a record has a shape or value /// appendix A doesn't give, sets what the model doesn't keep, or the table, the series tags or the /// art don't fit the graph. @@ -11396,7 +11458,7 @@ fn graphs_the_model_cant_keep_stay_plain_art() { ("type 11", live_graph().replace("%_5 0 0 14", "%_11 0 0 14")), ("legends in wedges", live_graph().replace("%_5 0 0 14", "%_5 0 0 15")), ("the right axis", live_graph().replace("6 44 Gy", "6 45 Gy")), - ("lines as shapes", live_graph().replace("%_5 0 0 14 0 1 0", "%_5 0 0 14 0 1 1")), + ("lines as shapes 0 pt wide", live_graph().replace("%_5 0 0 14 0 1 0 0 6", "%_5 0 0 14 0 1 1 0 0")), ("both axes alike", live_graph().replace(LIVE_DIALOG, "%_10 2 0 1 90 80 0 Gd\n")), ("a subscription", live_graph().replace(LIVE_DIALOG, &format!("{LIVE_DIALOG}%_0 0 1 1 1 Gj\n"))), ("a customization", live_graph().replace("GC\n", "GC\n%_2 Gt\n%_(Bars) GD\n%_GT\n")), diff --git a/docs/mcp.md b/docs/mcp.md index c7aa202d3f..f1f002645d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2075,9 +2075,9 @@ were. `graph.setType` refuses `` `columnWidth` must be a number, not "50" `` for `lineWidth`, the Line Width of Draw Filled Lines in points (3 when the graph sets none), takes a number from 0.01 to 1000 (VectorCraft's own range); `"4"` is refused with `` `lineWidth` must be a number, not "4" ``, and a width below 0.01 or past 1000 with `` `lineWidth` must be from 0.01 to 1000 pt, not 0 ``. The graph stores a width only when it is -not 3, so a graph without one is saved and drawn as before. A graph with a width of its own is written to `.ai` as its -art, without the editable graph records. `graph.setType` with options that leave the graph as it is -records no undo step. +not 3, so a graph without one is saved and drawn as before. In `.ai` the graph records carry Draw Filled Lines and +widths up to 100 pt; a graph with a wider Line Width is written to `.ai` as its art, without the editable graph +records. `graph.setType` with options that leave the graph as it is records no undo step. `axisMin`, `axisMax`, `rightAxisMin` and `rightAxisMax` take a number, or null to go back to the value calculated from the data; any other value is refused with `` `axisMin` must be a number or null, not "10" ``. `graph.setData` and `graph.create` refuse a `csv` that is not a string, `series` or `categories` that are not lists, and `rows` that are not diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..8e915e9efc 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1882,7 +1882,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A `.ai` opened from its editing data opens its Objects on Path groups live, with their path, their objects in order along it, Pivot and Rotate, and their art where the file draws it; a group whose spacing has been dragged, or with options an Objects on Path group doesn't hold, opens as a plain group (`crates/eps/src/import/ai/tests.rs`). `.ai` symbol definitions and placed instances open as live symbols, in the Symbols panel's order; an instance of a symbol that isn't read, or whose appearance differs from its symbol's, comes in as the page draws it (`crates/eps/src/import/ai/tests.rs`). In a `.ai` opened from its editing data, an object in a pattern's art or a brush's art with an art style VectorCraft reads opens as itself with its effects live, as an object on a layer does, and an object in a pattern's art keeps the id of a graphic style in the file's list (`crates/eps/src/import/ai/tests.rs`). - A graph in a `.ai` whose records have the shape and values the published version 7 specification gives ([the specification](https://13thmonkey.org/documentation/fonts/AI7FileFormat.pdf), printed pp. 109–112 and 146–158) opens as a live grouped column, stacked column, line or area graph with its saved art, table, axes and settings, and Graph Data edits it ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/add-graph-data.html)); other graphs keep their art as plain objects with a note. Saving to `.ai` writes these records for a graph that reads back as the same graph, and warns that any other graph's data and settings aren't written (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/cmd/graph/tests.rs`). + A graph in a `.ai` whose records have the shape and values the published version 7 specification gives ([the specification](https://13thmonkey.org/documentation/fonts/AI7FileFormat.pdf), printed pp. 109–112 and 146–158) opens as a live grouped column, stacked column, line or area graph with its saved art, table, axes and settings, and Graph Data edits it ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/add-graph-data.html)); other graphs keep their art as plain objects with a note. Saving to `.ai` writes these records for a graph that reads back as the same graph, and warns that any other graph's data and settings aren't written (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/cmd/graph/tests.rs`). A line graph drawn with Draw Filled Lines, which draws thicker filled lines when the points are connected ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/format-columns-bars-and-lines.html)), opens and saves live with its Line Width through the style record's `drawLinesAsShapes` and `lineShapeWidth` (the specification, printed pp. 147–148: points from 0 to 100, ignored when the lines aren't drawn); widths from 0.01 to 100 pt are kept, and a graph with a wider Line Width is saved as its art with the warning. Blends and envelopes in the definitions of a `.ai`'s symbols, patterns and brushes' art count against the same per-file limits on blend layout and envelope checks as the layers' art, so a file with many definitions does not get those limits again for each one (`crates/eps/src/import/ai/read/directives.rs`). A `.ai` or EPS whose editing data has brushes opens with the file's Calligraphic, Scatter, Art and Bristle brushes in the Brushes panel in place of the default ones, in the file's order: the Calligraphic size, roundness and angle with their variation, the Scatter size, spacing, scatter and rotation, the Bristle settings, and the Scatter and Art brushes' art (Art brushes in the older and newer forms of their objects). A brush library `.ai` (brushes and no layers) opens from its PDF part with its brushes, so Other Library lists them. An Art brush in None or Tints keeps that colorization, and one in the newer form also keeps its fixed width, Flip Along and Flip Across, and Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with its guides ([Art brush options](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf), printed page 193). Pattern brushes and brushes that can't be read are left out with a note. Paths with a Calligraphic brush, and paths with an Art brush in the newer form that bends art of solid-filled paths with those options, open as the path with the brush on its stroke, except paths whose brush scales its art proportionately. Paths with an Art brush in the older form, and other brushed paths, still come in as their drawn look (part of #372 and #637; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). In a `.ai` opened from its editing data, a path or type object with Offset Path, Outline Object or Outline Stroke on the whole object opens as itself with those effects live, in their order and shown or hidden; on a fill or stroke of type they stay on that fill or stroke. Offset Path keeps its Offset, Joins and Miter Limit, and Outline Stroke takes its width from the stroke. An Offset Path with a setting missing, out of range or not read keeps the drawn art, as does a path with a Path effect on one fill or stroke (`crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). From 160207e9f2d3de7fe87a2caabd805cff853f4cb6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 03:32:11 -0800 Subject: [PATCH 10/31] 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 a10c403df6e6183643b4d2ecbb688107c0f87f4b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 03:46:53 -0800 Subject: [PATCH 11/31] Scissors: paths a cut makes have every stroke aligned Center path.split (Scissors) and path.cutAtAnchors (Cut Path at Selected Anchor Points) keep the source path's fill and stroke settings on the paths they make, and now set every stroke's alignment to Center in the same undo step, as the help page describes: https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/split-paths.html Every stroke row is reset, hidden ones included. A path of several subpaths has one appearance, so its other subpaths' strokes are centered too, and a cut member of a compound path centers the compound path's strokes. An appearance whose strokes are already centered is left shared. Knife, the erasers and Divide are unchanged. --- crates/engine/src/cmd/draw2.rs | 2 +- crates/engine/src/cmd/draw2/commands.rs | 2 +- crates/engine/src/cmd/draw2/common.rs | 20 ++++ crates/engine/src/cmd/draw2/cut.rs | 8 +- crates/engine/src/cmd/path.rs | 4 +- crates/engine/src/tests/draw2.rs | 130 ++++++++++++++++++++++++ docs/mcp.md | 8 +- docs/target-app-parity.md | 1 + 8 files changed, 169 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/draw2.rs b/crates/engine/src/cmd/draw2.rs index 9055e83844..63ae0a3e4c 100644 --- a/crates/engine/src/cmd/draw2.rs +++ b/crates/engine/src/cmd/draw2.rs @@ -31,6 +31,6 @@ mod freehand; mod smooth; pub use commands::specs; -pub(super) use common::{ids_json, replace_with_pieces, usize_opt}; +pub(super) use common::{center_strokes, ids_json, replace_with_pieces, usize_opt}; pub(super) use cut::{components, erase_outline}; pub(super) use freehand::freehand_brushed; diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 050e477295..b9015a4cc7 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -74,7 +74,7 @@ pub fn specs() -> Vec { "Split Path", [], None, - "{id, subpath?, segment, t: 0–1 (0.5)} or {id, subpath?, anchor}: closed paths open there, open paths become two; one of the two new end points is left selected → {ids}. A t outside 0–1 is refused with an error, and nothing changes", + "{id, subpath?, segment, t: 0–1 (0.5)} or {id, subpath?, anchor}: closed paths open there, open paths become two; one of the two new end points is left selected; the paths keep the source's fill and stroke settings except that every stroke's alignment becomes Center (in a path of several subpaths, the other subpaths' strokes too) → {ids}. A t outside 0–1 is refused with an error, and nothing changes", has_doc, split ), diff --git a/crates/engine/src/cmd/draw2/common.rs b/crates/engine/src/cmd/draw2/common.rs index 332ad331dc..bf52f580e7 100644 --- a/crates/engine/src/cmd/draw2/common.rs +++ b/crates/engine/src/cmd/draw2/common.rs @@ -406,6 +406,26 @@ pub(super) fn sibling_with(d: &mut Document, id: NodeId, pd: PathData) -> Result Ok(n) } +/// Set every stroke of node `id`, and every stroke of the compound path it is a member of (whose +/// strokes its members show), to Center alignment. Every other stroke and fill setting stays as it +/// is, and an appearance whose strokes are all centered stays shared with its other copies. +pub(in super::super) fn center_strokes(d: &mut Document, id: NodeId) { + use vectorcraft_doc::{AppearanceItem, StrokeAlign}; + let parent = d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))); + for n in [Some(id), parent].into_iter().flatten() { + let Some(n) = d.node_mut(n) else { continue }; + let off = |it: &AppearanceItem| matches!(it, AppearanceItem::Stroke(st) if st.align != StrokeAlign::Center); + if !n.appearance.items.iter().any(off) { + continue; + } + for it in &mut n.appearance.items { + if let AppearanceItem::Stroke(st) = it { + st.align = StrokeAlign::Center; + } + } + } +} + /// Replace path or compound path `id` with `pieces` (first keeps the id, the rest go right above /// it; none removes it). `cut` removes the path or puts the other pieces above it. Returns ids. pub(in super::super) fn replace_with_pieces(d: &mut Document, cut: &mut Beside, id: NodeId, pieces: Vec) -> Result> { diff --git a/crates/engine/src/cmd/draw2/cut.rs b/crates/engine/src/cmd/draw2/cut.rs index bb75329765..40a4c74d79 100644 --- a/crates/engine/src/cmd/draw2/cut.rs +++ b/crates/engine/src/cmd/draw2/cut.rs @@ -1,6 +1,6 @@ use super::common::{ - PenRecord, SIZE_VARIATIONS, SIZES, Sample, dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, poly_bounds, - pressure_region, ranged, replace_with_pieces, samples_param, sibling_with, size_pressure, target_paths, usize_opt, + PenRecord, SIZE_VARIATIONS, SIZES, Sample, center_strokes, dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, + poly_bounds, pressure_region, ranged, replace_with_pieces, samples_param, sibling_with, size_pressure, target_paths, usize_opt, }; use super::{ Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Rect, Result, Session, @@ -225,14 +225,17 @@ pub(super) fn split(s: &mut Session, p: &Value) -> Result { sel.add(id); sel.anchors.entry(id).or_default().insert((si, 0)); }; + // The paths a cut makes keep the source's appearance with every stroke centered. if sp.closed { path.subpaths[si] = pieces.pop().ok_or_else(|| EngineError::Other("no such anchor".into()))?; + center_strokes(d, id); pick(sel, id, si); return Ok(vec![id]); } let [left, right] = <[SubPath; 2]>::try_from(pieces).map_err(|_| EngineError::Other("cannot split an open path at its end point".into()))?; if path.subpaths.len() == 1 { path.subpaths[0] = left; + center_strokes(d, id); let node = sibling_with(d, id, PathData::single(right))?; let (parent, idx, _) = d.position(id).ok_or(EngineError::NoNode(id))?; let nid = d.insert(parent, idx + 1, node)?; @@ -241,6 +244,7 @@ pub(super) fn split(s: &mut Session, p: &Value) -> Result { } else { path.subpaths[si] = left; path.subpaths.insert(si + 1, right); + center_strokes(d, id); pick(sel, id, si + 1); Ok(vec![id]) } diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 4d160c7c49..8ae3b46426 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -149,7 +149,7 @@ pub fn specs() -> Vec { "Cut Path at Selected Anchor Points", [], None, - "{} cut the paths at their direct-selected anchors (one undo step): a closed path opens there, an open one becomes one path per piece; one of each cut's two coincident anchors stays selected → {ids}", + "{} cut the paths at their direct-selected anchors (one undo step): a closed path opens there, an open one becomes one path per piece; one of each cut's two coincident anchors stays selected; the paths keep the source's fill and stroke settings except that every stroke's alignment becomes Center (in a path of several subpaths, the other subpaths' strokes too) → {ids}", has_anchors, cut_at_anchors ), @@ -1858,6 +1858,8 @@ fn cut_at_anchors(s: &mut Session, _: &Value) -> Result { let (mut all, mut picked) = (vec![], vec![]); let mut cut = Beside::replacing(d, &cuts.iter().map(|(id, ..)| *id).collect::>()); for (id, subs, starts) in cuts { + // The paths a cut makes keep the source's appearance with every stroke centered. + super::draw2::center_strokes(d, id); // A path of one subpath becomes one path per piece (the first keeps the id); the // pieces of a compound shape stay subpaths of it. if d.node(id).and_then(|n| n.path_data()).is_some_and(|pd| pd.subpaths.len() == 1) { diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 8674750c19..fd2a577795 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -3219,6 +3219,88 @@ fn split_refuses_a_subpath_anchor_or_segment_that_is_not_a_whole_number() { } } +/// Give `id` a 4 pt round-capped Inside stroke and, above it, a hidden red copy aligned Outside. +/// Returns the appearance it now has. +fn side_strokes(s: &mut Session, id: NodeId) -> vectorcraft_doc::Appearance { + use vectorcraft_doc::{AppearanceItem, LineCap, StrokeAlign}; + s.edit("Side Strokes", |d, _| { + let ap = &mut d.node_mut(id).unwrap().appearance; + let st = ap.stroke_mut().unwrap(); + (st.width, st.cap, st.align) = (4.0, LineCap::Round, StrokeAlign::Inside); + let mut top = st.clone(); + (top.align, top.visible, top.paint) = + (StrokeAlign::Outside, false, vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0))); + ap.items.push(AppearanceItem::Stroke(top)); + Ok(()) + }) + .unwrap(); + appearance(s, id) +} + +fn appearance(s: &Session, id: NodeId) -> vectorcraft_doc::Appearance { + (*s.doc().unwrap().doc.node(id).unwrap().appearance).clone() +} + +/// `ap` with every stroke aligned Center and nothing else changed. +fn centered(ap: &vectorcraft_doc::Appearance) -> vectorcraft_doc::Appearance { + let mut ap = ap.clone(); + for it in &mut ap.items { + if let vectorcraft_doc::AppearanceItem::Stroke(st) = it { + st.align = vectorcraft_doc::StrokeAlign::Center; + } + } + ap +} + +#[test] +fn scissors_cut_paths_have_their_strokes_centered() { + // The paths a Scissors cut makes keep the source's fill and strokes, every stroke centered, + // in the cut's one undo step; redo centers them again. + let mut s = session(); + let r = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + let before = side_strokes(&mut s, r); + assert_ne!(before, centered(&before)); + let undo = undo_steps(&s); + s.execute("path.split", &json!({"id": r.0, "anchor": 2})).unwrap(); + assert_eq!(undo_steps(&s), undo + 1); + assert!(!path(&s, r).subpaths[0].closed); + assert_eq!(appearance(&s, r), centered(&before), "closed path"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(path(&s, r).subpaths[0].closed); + assert_eq!(appearance(&s, r), before, "undo"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(appearance(&s, r), centered(&before), "redo"); + // An open path becomes two, at an anchor or inside a segment, both centered. + let anchors = json!([{"x": 100, "y": 300}, {"x": 200, "y": 300}, {"x": 300, "y": 300}]); + for at in [json!({"anchor": 1}), json!({"segment": 0, "t": 0.5})] { + let id = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap()); + let before = side_strokes(&mut s, id); + let made = s.execute("path.split", &with(&at, json!({"id": id.0}))).unwrap(); + let ids: Vec = made["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect(); + assert_eq!(ids.len(), 2, "{at}"); + for i in ids { + assert_eq!(appearance(&s, i), centered(&before), "{at}: {i:?}"); + } + } + // A path of several subpaths keeps one node: its other subpath's strokes are centered too. + let id = two_subpaths(&mut s); + let before = side_strokes(&mut s, id); + s.execute("path.split", &json!({"id": id.0, "anchor": 1})).unwrap(); + assert_eq!(path(&s, id).subpaths.len(), 3); + assert_eq!(appearance(&s, id), centered(&before), "several subpaths"); + // A cut that fails, at an open path's end point, changes neither the strokes nor the history. + let id = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap()); + let before = side_strokes(&mut s, id); + let undo = undo_steps(&s); + assert!(s.execute("path.split", &json!({"id": id.0, "anchor": 0})).is_err()); + assert_eq!((undo_steps(&s), appearance(&s, id)), (undo, before)); + // Strokes already centered stay shared with the undo history's copy. + let id = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap()); + let shared = s.doc().unwrap().doc.node(id).unwrap().appearance.clone(); + s.execute("path.split", &json!({"id": id.0, "anchor": 1})).unwrap(); + assert!(vectorcraft_doc::Shared::ptr_eq(&s.doc().unwrap().doc.node(id).unwrap().appearance, &shared)); +} + /// A subpath, anchor or segment of 2^32 + k fails, where k names one that exists, and the document /// and the undo history stay as they were. A 32-bit build read the number as k. #[test] @@ -3938,6 +4020,54 @@ fn cut_at_anchors_splits_paths_and_leaves_one_end_selected() { assert_eq!(undo_steps(&s), undo); } +#[test] +fn cut_at_anchors_paths_have_their_strokes_centered() { + // Every path the cut makes keeps the source's fill and strokes, every stroke centered, in one + // undo step; a path whose anchors were not selected keeps its strokes. + let mut s = session(); + let anchors = json!([{"x": 100, "y": 100}, {"x": 200, "y": 100}, {"x": 300, "y": 100}, {"x": 400, "y": 100}]); + let id = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap()); + let open = side_strokes(&mut s, id); + let r = rect(&mut s, 500.0, 100.0, 100.0, 100.0); + let closed = side_strokes(&mut s, r); + let other = rect(&mut s, 100.0, 300.0, 100.0, 100.0); + let untouched = side_strokes(&mut s, other); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 1], [0, 2]]})).unwrap(); + s.execute("select.anchors", &json!({"id": r.0, "anchors": [[0, 2]], "mode": "add"})).unwrap(); + assert_eq!(s.doc().unwrap().selection.anchors.len(), 2); + let undo = undo_steps(&s); + let made = s.execute("path.cutAtAnchors", &json!({})).unwrap(); + let ids: Vec = made["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect(); + assert_eq!(undo_steps(&s), undo + 1); + assert_eq!(ids.len(), 4, "three pieces and the opened rectangle"); + for i in &ids { + let want = if *i == r { centered(&closed) } else { centered(&open) }; + assert_eq!(appearance(&s, *i), want, "{i:?}"); + } + assert_eq!(appearance(&s, other), untouched); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((appearance(&s, id), appearance(&s, r)), (open.clone(), closed.clone()), "undo"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!((appearance(&s, id), appearance(&s, r)), (centered(&open), centered(&closed)), "redo"); + // A cut member of a compound path: the compound path's strokes, which it shows, are centered. + let a = rect(&mut s, 100.0, 450.0, 100.0, 100.0); + let b = rect(&mut s, 125.0, 475.0, 50.0, 50.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = s.doc().unwrap().selection.objects[0]; + let before = side_strokes(&mut s, compound); + let members: Vec = match &s.doc().unwrap().doc.node(compound).unwrap().kind { + NodeKind::Compound { children, .. } => children.iter().map(|c| c.id).collect(), + k => panic!("not a compound path: {k:?}"), + }; + let held = path(&s, members[1]); + s.execute("select.anchors", &json!({"id": members[0].0, "anchors": [[0, 2]]})).unwrap(); + s.execute("path.cutAtAnchors", &json!({})).unwrap(); + assert!(!path(&s, members[0]).subpaths[0].closed); + assert_eq!(path(&s, members[1]), held, "the other member keeps its shape"); + assert_eq!(appearance(&s, compound), centered(&before), "compound path"); +} + #[test] fn direct_segment_delete_keeps_the_other_rectangle_edges_and_one_undo() { for initially_selected in [false, true] { diff --git a/docs/mcp.md b/docs/mcp.md index c7aa202d3f..87c5b27920 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5844,7 +5844,13 @@ undo step: the two direct-selected anchors when they are open path ends, else th selection (both ends of one, closing it); anything else is refused. `path.convertAnchor {id, subpath?, anchor, to, x?, y?}` and `path.split {id, subpath?, anchor}` do the same to one anchor (the Anchor Point and Scissors tools); `path.split`, at an anchor or at `segment` and `t`, leaves the first anchor of the piece after the cut selected alone, and a Direct -Selection press on two anchors on top of each other takes the selected one; the Pen with Alt +Selection press on two anchors on top of each other takes the selected one. The paths that `path.cutAtAnchors` and +`path.split` make keep the source path's fill and stroke settings (weight, paint, caps, joins, dashes, width profile, +effects), but every stroke's alignment becomes Center in the same undo step, so an Inside or Outside stroke is centered +on the cut paths ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/split-paths.html)). +VectorCraft's own rules: every stroke row is reset, hidden ones included; a path of several subpaths has one appearance, +so a cut in one subpath centers the strokes of its other subpaths too, closed ones included; a cut member of a compound +path centers the compound path's strokes; strokes already centered are left as they are. The Pen with Alt held over a selected path's handle, anchor or segment works as the Anchor Point tool. `press_key` Escape between two `pointer_gesture` calls of an Anchor Point drag cancels it: the path goes back and no undo step is added. `path.reshapeSegment {id, subpath?, segment, t, dx, dy, perpendicular?}` (a segment dragged with Direct Selection or the Anchor Point tool) moves the segment's diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..c9b8728394 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1204,6 +1204,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur VectorCraft's own Anchors field in the Ellipse dialog (a click with the Ellipse tool; `shape.ellipse {anchors}`, part of #7840) sets how many smooth anchors the ellipse has, 4 by default; 4 draws a live ellipse, and any other count from 2 to 1000 draws a plain path with the anchors spaced evenly by angle, fitted to the typed width and height. The count last confirmed stays as the Ellipse tool's `anchors` option, and the next Ellipse dialog opens on it (`ellipse_with_four_anchors_is_the_live_ellipse`, `ellipse_anchors_draw_that_many_anchors_on_the_ellipse`, `ellipse_refuses_a_bad_anchor_count`, `the_ellipse_dialog_draws_and_keeps_its_anchor_count`). - **Cutting:** Eraser, Scissors, Knife, Mirror & Cut, Line Cut and Rectangle Cut (real geometry, compound paths keep their holes). A Scissors cut (`path.split`) leaves one of the two new end points selected and the rest of the path unselected, as [Cut paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/split-paths.html) and the "Split a path" section of the [CS3 user guide](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf) describe: the two end points lie on top of each other, and a Direct Selection drag from them moves the selected one with its handles and no other anchor. A closed path cut once stays one open path. + The paths a Scissors cut (`path.split`) or Cut Path at Selected Anchor Points (`path.cutAtAnchors`) makes keep the source path's fill and stroke settings, and every stroke's alignment becomes Center in the same undo step, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/split-paths.html) describes. Resetting hidden stroke rows too, centering the strokes of a path's other subpaths and of the compound path a cut member belongs to are VectorCraft's own rules (`scissors_cut_paths_have_their_strokes_centered`, `cut_at_anchors_paths_have_their_strokes_centered`). While Alt is held, the Scissors tool works as the Add Anchor Point tool ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)): a click on a segment adds an anchor point without cutting (`path.insertAnchor`), and the pointer shows the Add Anchor Point cursor. When Alt is let go, a click cuts again. Alt-drag with the Knife cuts in a straight line, and Shift+Alt-drag cuts at 45° or 90°, as [Cut objects using the Knife and Scissors tools](https://web.archive.org/web/20260926095638/https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/cut-objects.html) and [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) describe. Alt counts only when held at the press; the dashed line runs from the press point to the pointer, stays straight after Alt is let go, and release sends `path.knife` with those two points. Alt pressed after the press leaves the cut freehand. Shift+Alt keeps the endpoint at 45° steps from the horizontal and vertical, whatever the Constrain Angle. With Smart Guides on, a straight Knife cut snaps to anchor points and paths: [Cut objects using the Knife and Scissors tools](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/cut-objects.html) describes the Knife snapping to anchor points and paths while Smart Guides are on. Its ends snap as the ends of the Pencil's straight line do, to anchor points and path segments of art that is shown: the press, and the release of an Alt-drag. Shift+Alt steps 45° from the snapped press, and its release stays on that step. With Smart Guides off, or with Snap to Pixel or Snap to Grid on, the cut is not snapped. The dashed line and `path.knife` use the snapped points. From 52bbca2ecb9686f4781b17df109e54d6636367c6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 03:42:20 -0800 Subject: [PATCH 12/31] 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 f54a3faa39a7118c2380a40eef9478db2c9062ae Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 03:24:48 -0800 Subject: [PATCH 13/31] Packaging Tools: Check Fold Lines reports overshooting and stacked fold lines - A crease that runs past the cut outline by the tolerance or more is reported as outside, though its hinge is still built. - Two lines that fold, of any role, on top of each other are reported as duplicate; a line drawn twice is still checked for where it lies. - Hidden lines are left out in every scope, members of a selected group included. - The ids scope gets its own noCut message. - The notStraight, ambiguous and summary texts say what the check finds: the summary counts hinges, not creases. - The fold angle fields, which nothing in this change reads, are removed. - A window drawn as open cut lines stays a hole when a cut line crosses it or when slits join it to an outline of open lines, so that three lines meet at a corner. Cut lines drawn whole that cross a cell leave it material. - A slot drawn across the outline is a notch, not a hole, as when the notch is drawn in the outline; a crease in it lies outside the blank. - notStraight measures each hinge piece at its farthest point from the hinge line instead of at five samples. - Cut lines drawn on top of each other so many times that the gap search would look at more than 16,777,216 pairs are reported as tooComplex before the search. --- .../engine/src/cmd/addons/packaging/check.rs | 19 +- .../src/cmd/addons/packaging/check/tests.rs | 15 + crates/three-d/src/fold.rs | 353 ++++++++++++++---- crates/three-d/src/fold/tests.rs | 192 +++++++++- crates/three-d/src/lib.rs | 2 + crates/ui-egui/src/addons/packaging.rs | 2 +- crates/ui-egui/src/addons/packaging/tests.rs | 24 +- crates/ui-egui/src/i18n/bg.tsv | 11 +- crates/ui-egui/src/i18n/bs.tsv | 11 +- crates/ui-egui/src/i18n/ca.tsv | 11 +- crates/ui-egui/src/i18n/cs.tsv | 11 +- crates/ui-egui/src/i18n/da.tsv | 11 +- crates/ui-egui/src/i18n/de.tsv | 11 +- crates/ui-egui/src/i18n/el.tsv | 11 +- crates/ui-egui/src/i18n/es.tsv | 11 +- crates/ui-egui/src/i18n/fi.tsv | 11 +- crates/ui-egui/src/i18n/fr.tsv | 11 +- crates/ui-egui/src/i18n/gu.tsv | 11 +- crates/ui-egui/src/i18n/hi.tsv | 11 +- crates/ui-egui/src/i18n/hu.tsv | 11 +- crates/ui-egui/src/i18n/id.tsv | 11 +- crates/ui-egui/src/i18n/it.tsv | 11 +- crates/ui-egui/src/i18n/ja.tsv | 11 +- crates/ui-egui/src/i18n/ka.tsv | 11 +- crates/ui-egui/src/i18n/ko.tsv | 11 +- crates/ui-egui/src/i18n/nl.tsv | 11 +- crates/ui-egui/src/i18n/pl.tsv | 11 +- crates/ui-egui/src/i18n/pt-br.tsv | 11 +- crates/ui-egui/src/i18n/ru.tsv | 11 +- crates/ui-egui/src/i18n/sv.tsv | 11 +- crates/ui-egui/src/i18n/tr.tsv | 11 +- crates/ui-egui/src/i18n/uk.tsv | 11 +- crates/ui-egui/src/i18n/vi.tsv | 11 +- crates/ui-egui/src/i18n/zh-hans.tsv | 11 +- crates/ui-egui/src/i18n/zh-hant.tsv | 11 +- docs/mcp.md | 14 +- 36 files changed, 681 insertions(+), 248 deletions(-) diff --git a/crates/engine/src/cmd/addons/packaging/check.rs b/crates/engine/src/cmd/addons/packaging/check.rs index 59f195d4df..da8f7f25dd 100644 --- a/crates/engine/src/cmd/addons/packaging/check.rs +++ b/crates/engine/src/cmd/addons/packaging/check.rs @@ -22,7 +22,7 @@ pub fn specs() -> Vec { "Check Fold Lines", ["Object", "Plug-ins", "Packaging Tools"], None, - "{ids?: [id…] (default: the selection), select?: bool (false), tolerance?: pt 0.01..10 (0.1)} check the fold lines (addon.packaging.roles) among the objects (through groups and clip groups), or, while nothing is selected and ids is left out, every fold line of the document that is shown. Cut lines bound the blanks: each connected piece of them that encloses material is one blank, its outline is its largest closed cut line, and a closed cut line inside it is a hole, so a slot drawn as a rectangle across the outline leaves the same material as a notch drawn in it; open cut lines that meet end to end count as one closed cut line. Crease, Partial Cut and Perforation lines divide a blank into panels; the pieces of them between two panels are that pair's hinge. A cut line end that comes within tolerance of another cut line is joined to it. Issues, in this order: noCut, open, looseEnd (errors), gap (a warning: the gap is closed), tooComplex (an error: more than 65,536 segments or 256 panels in a blank), cutOverCrease (an error), duplicate, danglingCrease, noSplit, outside, notStraight (it folds along the line through its longest piece), sliver, ambiguous, loosePanel (joined to the largest panel by no chain of hinges), nonPrinting (warnings). With select, the objects the issues name become the selection, unless no issue names one. Changes nothing in the document → {ok (no error), blanks, panels, hinges, holes, issues: [{severity: error|warning, code, message (English), ids, at?: [x, y]}], scope: ids|selection|document}", + "{ids?: [id…] (default: the selection), select?: bool (false), tolerance?: pt 0.01..10 (0.1)} check the fold lines (addon.packaging.roles) among the objects (through groups and clip groups), or, while nothing is selected and ids is left out, every fold line of the document; hidden lines are left out, also in a selected group. Cut lines bound the blanks: each connected piece of them that encloses material is one blank, its outline is its largest closed cut line, and a closed cut line inside it is a hole, so a slot drawn as a rectangle across the outline leaves the same material as a notch drawn in it; open cut lines that meet end to end count as one closed cut line. Crease, Partial Cut and Perforation lines divide a blank into panels; the pieces of them between two panels are that pair's hinge. A cut line end that comes within tolerance of another cut line is joined to it. Issues, in this order: noCut, open, looseEnd (errors), gap (a warning: the gap is closed), tooComplex (an error: more than 65,536 segments or 256 panels in a blank), cutOverCrease (an error), duplicate (two cut lines, or two lines that fold of any role), danglingCrease, noSplit, outside (wholly, or in part for tolerance or more), notStraight (a hinge's pieces are not on one straight line), sliver, ambiguous, loosePanel (joined to the largest panel by no chain of hinges), nonPrinting (warnings). With select, the objects the issues name become the selection, unless no issue names one. Changes nothing in the document → {ok (no error), blanks, panels, hinges, holes, issues: [{severity: error|warning, code, message (English), ids, at?: [x, y]}], scope: ids|selection|document}", has_doc, check )] @@ -32,19 +32,20 @@ pub fn specs() -> Vec { fn message(code: IssueCode, scope: &str) -> &'static str { match code { IssueCode::NoCut if scope == "document" => "No cut lines are in the document.", + IssueCode::NoCut if scope == "ids" => "No cut lines are among the given objects.", IssueCode::NoCut => "No cut lines are in the selection.", IssueCode::Open => "The cut lines do not enclose an area.", IssueCode::LooseEnd => "A cut line ends without meeting another cut line.", IssueCode::Gap => "A gap between cut lines was closed.", IssueCode::TooComplex => "The fold lines are too complex to check.", IssueCode::CutOverCrease => "A cut line and a crease lie on top of each other.", - IssueCode::Duplicate => "Two lines of the same role lie on top of each other.", + IssueCode::Duplicate => "Two fold lines lie on top of each other.", IssueCode::DanglingCrease => "A crease ends inside a panel.", IssueCode::NoSplit => "A crease does not divide two panels.", - IssueCode::Outside => "A crease lies outside the cut outline.", - IssueCode::NotStraight => "A crease that is not straight is folded along one straight line.", + IssueCode::Outside => "A crease lies outside the cut outline, wholly or in part.", + IssueCode::NotStraight => "The pieces of a hinge are not on one straight line.", IssueCode::Sliver => "A gap between cut lines is too narrow to tell apart.", - IssueCode::Ambiguous => "A cut-out area holds other fold lines.", + IssueCode::Ambiguous => "A cut-out area holds other fold lines or another blank.", IssueCode::LoosePanel => "A panel is not joined to the rest by a crease.", IssueCode::NonPrinting => "A fold line is on a non-printing layer.", } @@ -110,9 +111,11 @@ fn check(s: &mut Session, p: &Value) -> Result { let given = p.get("ids").is_some_and(|v| !v.is_null()); let roots = checked_ids_or_selection(s, p, CHECK)?; let d = &s.doc()?.doc; + // Hidden lines are left out in every scope, members of a selected group included. + let shown = |ids: Vec| ids.into_iter().filter(|id| d.is_visible(*id)).collect::>(); let (scope, targets) = match (given, roots.is_empty()) { - (true, _) => ("ids", role_targets(d, &roots, false).0), - (false, false) => ("selection", role_targets(d, &roots, false).0), + (true, _) => ("ids", shown(role_targets(d, &roots, false).0)), + (false, false) => ("selection", shown(role_targets(d, &roots, false).0)), (false, true) => ("document", shown_targets(d)), }; let table = RoleTable::of(d); @@ -131,7 +134,7 @@ fn check(s: &mut Session, p: &Value) -> Result { non_printing.push(id.0); } segments = segments.saturating_add(path.subpaths.iter().map(|sp| sp.segment_count()).sum()); - lines.push(FoldLine { path, kind: kind(role), angle: None, key: id.0 }); + lines.push(FoldLine { path, kind: kind(role), key: id.0 }); } let (found, mut issues) = blanks(&lines, tolerance); if !non_printing.is_empty() { diff --git a/crates/engine/src/cmd/addons/packaging/check/tests.rs b/crates/engine/src/cmd/addons/packaging/check/tests.rs index 427656fc29..9940761dea 100644 --- a/crates/engine/src/cmd/addons/packaging/check/tests.rs +++ b/crates/engine/src/cmd/addons/packaging/check/tests.rs @@ -62,6 +62,9 @@ fn the_selection_or_ids_limit_the_check_to_their_lines() { assert_eq!(r["issues"][0]["message"], "No cut lines are in the selection."); let r = check(&mut s, json!({ "ids": [outline] })); assert_eq!((r["scope"].as_str(), r["ok"].as_bool(), r["panels"].as_u64()), (Some("ids"), Some(true), Some(1)), "{r}"); + let r = check(&mut s, json!({ "ids": [creases[1]] })); + assert_eq!((r["scope"].as_str(), codes(&r)), (Some("ids"), vec!["noCut"])); + assert_eq!(r["issues"][0]["message"], "No cut lines are among the given objects."); // No fold lines at all in the document. let mut s = session(); let r = check(&mut s, json!({})); @@ -135,6 +138,18 @@ fn hidden_lines_are_left_out_and_lines_on_a_non_printing_layer_are_noted() { s.execute("select.none", &json!({})).unwrap(); let r = check(&mut s, json!({})); assert_eq!((r["panels"].as_u64(), r["hinges"].as_u64()), (Some(4), Some(3)), "{r}"); + // The same in a selected group, and with the group named by `ids`: the hidden member is left + // out too. + let mut s = session(); + let (outline, creases) = tray(&mut s); + s.execute("select.set", &json!({ "ids": [outline, creases[0], creases[1], creases[2], creases[3]] })).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.setProps", &json!({ "ids": [creases[0]], "visible": false })).unwrap(); + s.execute("select.set", &json!({ "ids": [group] })).unwrap(); + for p in [json!({}), json!({ "ids": [group] })] { + let r = check(&mut s, p); + assert_eq!((r["panels"].as_u64(), r["hinges"].as_u64()), (Some(4), Some(3)), "{r}"); + } // A cut line on a layer that does not print. let mut s = session(); s.execute("layer.new", &json!({ "printable": false })).unwrap(); diff --git a/crates/three-d/src/fold.rs b/crates/three-d/src/fold.rs index c68f8aa6ca..2dbff773f9 100644 --- a/crates/three-d/src/fold.rs +++ b/crates/three-d/src/fold.rs @@ -12,7 +12,7 @@ use std::collections::{HashMap, HashSet}; use vectorcraft_geom::kurbo::{Line, ParamCurveArclen, ParamCurveNearest, PathSeg}; -use vectorcraft_geom::{BezPath, FillRule, ParamCurve, PathData, Point, Rect, Shape as _, SubPath}; +use vectorcraft_geom::{Affine, BezPath, FillRule, ParamCurve, PathData, Point, Rect, Shape as _, SubPath}; use vectorcraft_pathops::{Adjacency, DEFAULT_PRECISION, SHAPE_BUILDER_MAX_SEGMENTS, Shape, adjacency, find_gaps, interior_point, unite_all}; /// Most panels one blank may have. Its hinges are the edges of a planar graph on its panels, so there @@ -34,26 +34,11 @@ pub enum LineKind { Perforation, } -impl LineKind { - /// The angle a line of this kind folds at when it has none of its own, in degrees: Crease and - /// Perforation 90, Partial Cut -90 (VectorCraft's own values); a positive angle folds away from - /// the printed side. A Cut line does not fold: 0. - pub fn default_angle(self) -> f64 { - match self { - LineKind::Cut => 0.0, - LineKind::Crease | LineKind::Perforation => 90.0, - LineKind::PartialCut => -90.0, - } - } -} - -/// A fold line: the path (document coordinates), its kind, its own fold angle in degrees if it has -/// one, and a key the issues name it by. +/// A fold line: the path (document coordinates), its kind, and a key the issues name it by. #[derive(Clone, Debug)] pub struct FoldLine { pub path: PathData, pub kind: LineKind, - pub angle: Option, pub key: u64, } @@ -72,17 +57,16 @@ pub struct Panel { pub area: f64, } -/// The fold between panels `a` and `b` (indices into the blank's panels, `a` < `b`), about the -/// straight line from `from` to `to`, at `angle` degrees, made of the lines `keys`. `straight` is -/// false when its pieces are not on one straight line within the tolerance; it then folds about the -/// line through its longest piece. +/// The hinge between panels `a` and `b` (indices into the blank's panels, `a` < `b`): the straight +/// line from `from` to `to`, made of the lines `keys`. `straight` is false when its pieces are not on +/// one straight line within the tolerance; `from` and `to` are then on the line through its longest +/// piece. #[derive(Clone, Debug)] pub struct Hinge { pub a: usize, pub b: usize, pub from: Point, pub to: Point, - pub angle: f64, pub keys: Vec, pub straight: bool, } @@ -105,13 +89,14 @@ pub enum IssueCode { TooComplex, /// A Cut line and a crease lie on top of each other. CutOverCrease, - /// Two lines of the same kind lie on top of each other. + /// Two Cut lines, or two of the lines that fold (of the same kind or not), lie on top of each + /// other. Duplicate, /// A crease ends inside a panel. DanglingCrease, /// A crease divides no two panels. NoSplit, - /// A crease lies outside every blank. + /// A crease lies outside every blank, wholly, or in part for the tolerance or more. Outside, /// A hinge's pieces are not on one straight line. NotStraight, @@ -221,6 +206,9 @@ pub fn blanks(lines: &[FoldLine], tolerance: f64) -> (Vec, Vec) { return (vec![], vec![Issue::new(IssueCode::NoCut, vec![], None)]); } let folds: Vec<&Piece> = pieces.iter().filter(|p| kind(p) != LineKind::Cut).collect(); + if !gap_work_fits(&cuts, tolerance) { + return (vec![], vec![Issue::new(IssueCode::TooComplex, vec![], None)]); + } let cut_shapes: Vec = cuts.iter().map(|p| shape(p.sp.clone())).collect(); let gaps = find_gaps(&cut_shapes, tolerance); // `find_gaps` takes ends closer than 1/10,000 of the tolerance as joined, which the map may not @@ -271,6 +259,33 @@ pub fn blanks(lines: &[FoldLine], tolerance: f64) -> (Vec, Vec) { (built, sorted(issues)) } +/// Most (open end, Cut segment) pairs within the tolerance of each other that the gap search may +/// look at. +const MAX_GAP_CANDIDATES: usize = 1 << 24; + +/// Whether the gap search over `cuts` stays within [`MAX_GAP_CANDIDATES`]: it looks at the Cut +/// segments within `tolerance` of each open end, and lines drawn on top of each other many times +/// over make that work grow with the square of their number. The count stops at the limit. +fn gap_work_fits(cuts: &[&Piece], tolerance: f64) -> bool { + let boxes: Vec<(Rect, usize)> = cuts + .iter() + .flat_map(|p| { + PathData::single(p.sp.clone()).to_bezpath().segments().map(|s| s.bounding_box().inflate(tolerance, tolerance)).collect::>() + }) + .enumerate() + .map(|(i, b)| (b, i)) + .collect(); + let grid = Cells::new(boxes, 2.0 * tolerance, 4096.0); + let mut work = 0usize; + for e in cuts.iter().flat_map(|p| ends(&p.sp)) { + work = work.saturating_add(grid.near(e, 0.0).len()); + if work > MAX_GAP_CANDIDATES { + return false; + } + } + true +} + fn sorted(mut issues: Vec) -> Vec { issues.sort_by_key(|i| i.code); issues @@ -429,8 +444,9 @@ fn contains(bp: &BezPath, p: Point) -> bool { /// The loops that open Cut pieces and the lines across `gaps` make end to end: each chain of them /// whose every end meets exactly one end of another piece of the chain (within 1e-6), as (index -/// into `cuts` of its first Cut piece, closed path). Pieces that lie on no cycle are left out first; -/// ends where three of the remaining pieces or more meet join nothing. +/// into `cuts` of its first Cut piece, closed path). Pieces that lie on no cycle are left out first. +/// A connected set of the remaining pieces with an end where three or more meet gives the outlines +/// of the faces it encloses instead. fn chains(cuts: &[&Piece], gaps: &[[Point; 2]]) -> Vec<(usize, BezPath)> { const NEAR: f64 = 1e-6; // Cell numbers stay far from the ends of `i64`, so a neighbor's number does not overflow. @@ -477,8 +493,49 @@ fn chains(cuts: &[&Piece], gaps: &[[Point; 2]]) -> Vec<(usize, BezPath)> { for ks in at.values_mut() { ks.retain(|&k| live.get(k) == Some(&true)); } + // The connected pieces of what is left, by node. In a piece where some node joins more than two + // pieces (a window with a cut across it), the loop is the outline of the faces the piece + // encloses; the other pieces are walked end to end below. + let mut group: Vec = (0..firsts.len()).collect(); + for (k, &(_, a, b)) in open.iter().enumerate() { + if live.get(k) == Some(&true) { + let (ra, rb) = (root_of(&mut group, a), root_of(&mut group, b)); + if let Some(slot) = group.get_mut(ra) { + *slot = rb; + } + } + } + let mut branched: HashSet = HashSet::new(); + for (&n, ks) in &at { + if !ks.is_empty() && ks.len() != 2 { + branched.insert(root_of(&mut group, n)); + } + } let mut used: Vec = live.iter().map(|l| !l).collect(); let mut out = vec![]; + let mut joined: HashMap> = HashMap::new(); + for (k, &(_, a, _)) in open.iter().enumerate() { + let r = root_of(&mut group, a); + if used.get(k) == Some(&false) && branched.contains(&r) { + joined.entry(r).or_default().push(k); + if let Some(u) = used.get_mut(k) { + *u = true; + } + } + } + let mut joined: Vec> = joined.into_values().collect(); + joined.sort_unstable(); + for ks in joined { + let Some(first_cut) = ks.iter().filter_map(|&k| open.get(k).and_then(|&(j, _, _)| items.get(j)).and_then(|(i, _)| *i)).min() else { + continue; + }; + let shapes: Vec = ks + .iter() + .filter_map(|&k| open.get(k).and_then(|&(j, _, _)| items.get(j))) + .map(|(_, segs)| Shape::new(PathData::from_bezpath(&BezPath::from_path_segments(segs.iter().copied())), FillRule::NonZero, 0)) + .collect(); + out.extend(enclosed_loops(&shapes).into_iter().map(|bp| (first_cut, bp))); + } for start in 0..open.len() { if used.get(start) != Some(&false) { continue; @@ -534,6 +591,95 @@ fn chains(cuts: &[&Piece], gaps: &[[Point; 2]]) -> Vec<(usize, BezPath)> { out } +/// The loops of a connected set of open Cut pieces `shapes` where some end joins three pieces or +/// more: the outline of all the faces they enclose, and for each group of faces that meet only other +/// faces and are bounded by pieces that meet end to end (a window joined to an outline by two slits, +/// not the middle cell of cut lines that cross), the group's outline, as the pieces of a chain that +/// closes count as one closed Cut line. +fn enclosed_loops(shapes: &[Shape]) -> Vec { + let Some(map) = adjacency(shapes, DEFAULT_PRECISION) else { return vec![] }; + let mut inner = vec![true; map.faces.len()]; + for e in &map.edges { + for (a, b) in [(e.left, e.right), (e.right, e.left)] { + if b.is_none() + && let Some(slot) = a.and_then(|f| inner.get_mut(f)) + { + *slot = false; + } + } + } + let mut group: Vec = (0..map.faces.len()).collect(); + for e in &map.edges { + if let (Some(a), Some(b)) = (e.left, e.right) + && a != b + && inner.get(a) == Some(&true) + && inner.get(b) == Some(&true) + { + let (ra, rb) = (root_of(&mut group, a), root_of(&mut group, b)); + if let Some(slot) = group.get_mut(ra) { + *slot = rb; + } + } + } + let mut sets: HashMap> = HashMap::new(); + for f in (0..map.faces.len()).filter(|&f| inner.get(f) == Some(&true)) { + sets.entry(root_of(&mut group, f)).or_default().push(f); + } + // A group is a loop when its boundary edges come from pieces that lie on that boundary alone, + // that is, pieces that meet end to end round it; pieces of lines that cross it go on past it. + let mut edges_of: HashMap> = HashMap::new(); + for (i, e) in map.edges.iter().enumerate() { + for &s in &e.sources { + edges_of.entry(s).or_default().push(i); + } + } + let side = |g: &mut Vec, f: Option| f.filter(|&f| inner.get(f) == Some(&true)).map(|f| root_of(g, f)); + let mut boundary: HashMap> = HashMap::new(); + for (i, e) in map.edges.iter().enumerate() { + let (l, r) = (side(&mut group, e.left), side(&mut group, e.right)); + if l != r { + for root in [l, r].into_iter().flatten() { + boundary.entry(root).or_default().insert(i); + } + } + } + let whole = |root: &usize| { + boundary.get(root).is_some_and(|edges| { + edges + .iter() + .filter_map(|&i| map.edges.get(i)) + .flat_map(|e| &e.sources) + .all(|s| edges_of.get(s).is_some_and(|all| all.iter().all(|i| edges.contains(i)))) + }) + }; + let mut sets: Vec<(usize, Vec)> = sets.into_iter().filter(|(root, _)| whole(root)).collect(); + sets.push((usize::MAX, (0..map.faces.len()).collect())); + sets.sort_unstable(); + let mut out = vec![]; + for (_, set) in sets { + let faces: Vec<(&PathData, FillRule)> = set.iter().filter_map(|&f| map.faces.get(f)).map(|f| (&f.path, FillRule::NonZero)).collect(); + if !faces.is_empty() { + out.extend(unite_all(&faces).subpaths.into_iter().map(|sp| PathData::single(sp).to_bezpath())); + } + } + out +} + +/// The node that stands for `v`'s set in `group` (a disjoint-set forest), halving the path on the way. +fn root_of(group: &mut [usize], mut v: usize) -> usize { + while let Some(&up) = group.get(v) { + if up == v { + break; + } + let next = group.get(up).copied().unwrap_or(up); + if let Some(slot) = group.get_mut(v) { + *slot = next; + } + v = next; + } + v +} + /// Which of `edges` ((id, end node, end node), nodes below `nodes`) lie on no cycle: the bridges of /// the graph, found depth first without recursion. fn bridges(nodes: usize, edges: &[(usize, usize, usize)]) -> Vec { @@ -809,6 +955,7 @@ impl Material { *h = !unusable(f) && in_outline && cut_out; } } + self.open_notches(piece, fallback.as_ref()); if any { let bound = if outlines.is_empty() { fallback @@ -825,6 +972,45 @@ impl Material { } } + /// Faces of `piece` cut out that meet the outside, directly or through other faces cut out, are + /// a notch, not a hole: they stop being holes. The outside is a usable face that is neither + /// material nor a hole (the part of a slot beyond the outline), or the side with no face of an + /// edge on the piece's outer boundary `outline` (elsewhere a side with no face is a sliver). + fn open_notches(&mut self, piece: usize, outline: Option<&BezPath>) { + let edges = self.edges_by_piece.get(piece).cloned().unwrap_or_default(); + let hole = |s: &Self, f: Option| f.is_some_and(|f| s.hole.get(f) == Some(&true)); + let open = |s: &Self, f: Option| { + f.is_some_and(|f| s.hole.get(f) != Some(&true) && s.material.get(f) != Some(&true) && s.points.get(f).copied().flatten().is_some()) + }; + // Whether `edge` lies on the piece's outer boundary `outline` (its middle within 1e-6 of + // it): its side with no face is then the outside, not a sliver. + let on_outline = |edge: &vectorcraft_pathops::MapEdge| { + let Some(outline) = outline else { return false }; + let segs: Vec = edge.path.to_bezpath().segments().collect(); + let Some(mid) = segs.get(segs.len() / 2).map(|s| s.eval(0.5)) else { return false }; + outline.segments().any(|s| s.nearest(mid, 1e-9).distance_sq <= 1e-12) + }; + let mut next: HashMap> = HashMap::new(); + let mut queue = vec![]; + for edge in edges.iter().filter_map(|&e| self.map.edges.get(e)) { + for (a, b) in [(edge.left, edge.right), (edge.right, edge.left)] { + let Some(f) = a.filter(|_| a != b && hole(self, a)) else { continue }; + if open(self, b) || (b.is_none() && on_outline(edge)) { + queue.push(f); + } else if let Some(g) = b.filter(|_| hole(self, b)) { + next.entry(f).or_default().push(g); + } + } + } + while let Some(f) = queue.pop() { + match self.hole.get_mut(f) { + Some(h) if *h => *h = false, + _ => continue, + } + queue.extend(next.get(&f).into_iter().flatten().copied()); + } + } + /// The face of the Cut lines' map that holds `p`, the smallest when several do. fn face_at(&self, p: Point) -> Option { self.face_cells @@ -865,6 +1051,9 @@ struct HingePiece { lines: Vec, } +/// A hinge piece by the (blank, panel, panel) it lies between. +type PlacedPiece = ((usize, usize, usize), HingePiece); + struct Context<'a> { lines: &'a [FoldLine], pieces: &'a [Piece], @@ -945,9 +1134,9 @@ impl Context<'_> { issues.push(Issue::new(IssueCode::TooComplex, vec![], None)); return vec![]; } - let pieces = self.edges(&places, issues); + let (pieces, outside) = self.edges(&places, issues); let hinged = self.hinges(&mut blanks, pieces, issues); - self.creases(&places, &hinged, issues); + self.creases(&places, &hinged, &outside, issues); self.slivers(issues); self.nested(issues); self.loose_panels(&blanks, &places, issues); @@ -980,9 +1169,10 @@ impl Context<'_> { } /// Overlaps, dangling creases and creases in holes, from the full map's edges → the hinge - /// pieces, by (blank, panel, panel). - fn edges(&self, places: &[Place], issues: &mut Vec) -> Vec<((usize, usize, usize), HingePiece)> { + /// pieces, by (blank, panel, panel), and how long each line runs outside every blank. + fn edges(&self, places: &[Place], issues: &mut Vec) -> (Vec, Vec) { let mut pieces = vec![]; + let mut outside = vec![0.0; self.lines.len()]; let mut seen: HashSet<(IssueCode, Vec)> = HashSet::new(); let mut report = |issues: &mut Vec, code: IssueCode, keys: Vec| { let issue = Issue::new(code, keys, None); @@ -1000,17 +1190,16 @@ impl Context<'_> { report(issues, IssueCode::CutOverCrease, self.keys(by_line.iter().copied())); continue; } - // Two subpaths of one kind on the same edge, from two lines or from one line's own - // subpaths (a compound path); the gap lines are left out. - let drawn: Vec = e.sources.iter().copied().filter(|&s| self.line_of(s).is_some()).collect(); - let mut duplicates: Vec = drawn - .iter() - .filter(|&&s| drawn.iter().any(|&o| o != s && self.kind_of(o) == self.kind_of(s))) - .filter_map(|&s| self.line_of(s)) - .collect(); - duplicates.sort_unstable(); - duplicates.dedup(); - if !duplicates.is_empty() { + // Two subpaths on the same edge, from two lines or from one line's own subpaths (a + // compound path); the gap lines are left out. Past the check above they are all Cut lines + // or all lines that fold. + let mut drawn: Vec = e.sources.iter().copied().filter(|&s| self.line_of(s).is_some()).collect(); + drawn.sort_unstable(); + drawn.dedup(); + if drawn.len() >= 2 { + let mut duplicates: Vec = drawn.iter().filter_map(|&s| self.line_of(s)).collect(); + duplicates.sort_unstable(); + duplicates.dedup(); report(issues, IssueCode::Duplicate, self.keys(duplicates)); } if creases.is_empty() { @@ -1024,14 +1213,34 @@ impl Context<'_> { report(issues, IssueCode::DanglingCrease, self.keys(creases)); } (Place::Hole, _) | (_, Place::Hole) => report(issues, IssueCode::Ambiguous, self.keys(creases)), - _ => {} + _ => { + // A side with no face can also be a sliver inside a blank: the edge counts when + // its middle lies in a face of the Cut lines that is neither material nor a hole + // (a notch), or in no face and outside every blank. + let segs: Vec = e.path.to_bezpath().segments().collect(); + let Some(mid) = segs.get(segs.len() / 2).map(|s| s.eval(0.5)) else { continue }; + let m = self.material; + let away = match m.face_at(mid) { + Some(f) => m.material.get(f) != Some(&true) && m.hole.get(f) != Some(&true), + None => !m.in_a_blank(mid), + }; + if !away { + continue; + } + let length: f64 = segs.iter().map(|s| s.arclen(1e-3)).sum(); + for &line in &creases { + if let Some(o) = outside.get_mut(line) { + *o += length; + } + } + } } } - pieces + (pieces, outside) } /// The hinges `pieces` make, added to `blanks` → the lines with a hinge. - fn hinges(&self, blanks: &mut [Blank], mut pieces: Vec<((usize, usize, usize), HingePiece)>, issues: &mut Vec) -> Vec { + fn hinges(&self, blanks: &mut [Blank], mut pieces: Vec, issues: &mut Vec) -> Vec { pieces.sort_by_key(|p| p.0); let mut hinged = vec![]; let mut start = 0; @@ -1067,29 +1276,24 @@ impl Context<'_> { let sp = p.path.subpaths.first()?; Some((sp.anchors.first()?.p, sp.anchors.last()?.p)) }; - let longest = group.iter().filter_map(|p| Some((*p, chord(p)?))).max_by(|x, y| { - let (lx, ly) = (x.1.0.distance(x.1.1), y.1.0.distance(y.1.1)); - lx.total_cmp(&ly) - })?; - let (p0, p1) = longest.1; + let (p0, p1) = group.iter().filter_map(|p| chord(p)).max_by(|x, y| x.0.distance(x.1).total_cmp(&y.0.distance(y.1)))?; let len = p0.distance(p1); // The longest piece only sets the direction; the length check is on the whole hinge below. if len.is_nan() || len <= 1e-9 { return None; } let d = (p1 - p0) / len; - let off = |p: Point| ((p - p0).cross(d)).abs(); + // Each segment turned so the line through `p0` along `d` is the x axis: the exact bounds + // give how far it strays from the line (y) and its extent along it (x). + let turn = Affine::rotate(-d.y.atan2(d.x)) * Affine::translate(-p0.to_vec2()); let mut straight = true; let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY); for p in group { for seg in p.path.to_bezpath().segments() { - for t in [0.0, 0.25, 0.5, 0.75, 1.0] { - let q = seg.eval(t); - straight &= off(q) <= self.tolerance; - let s = (q - p0).dot(d); - lo = lo.min(s); - hi = hi.max(s); - } + let b = (turn * seg).bounding_box(); + straight &= b.y0.abs() <= self.tolerance && b.y1.abs() <= self.tolerance; + lo = lo.min(b.x0); + hi = hi.max(b.x1); } } // The pieces' own length, not the span from the first to the last, which takes in the gaps @@ -1101,23 +1305,21 @@ impl Context<'_> { let mut lines: Vec = group.iter().flat_map(|p| p.lines.iter().copied()).collect(); lines.sort_unstable(); lines.dedup(); - let angle = longest - .0 - .lines - .first() - .and_then(|&l| self.lines.get(l)) - .map(|l| l.angle.filter(|a| a.is_finite()).unwrap_or_else(|| l.kind.default_angle())) - .unwrap_or(90.0); let mut keys = self.keys(lines); keys.sort_unstable(); keys.dedup(); - Some(Hinge { a, b, from: p0 + d * lo, to: p0 + d * hi, angle, keys, straight }) + Some(Hinge { a, b, from: p0 + d * lo, to: p0 + d * hi, keys, straight }) } - /// Creases with no hinge: outside every blank, or dividing no two panels. - fn creases(&self, places: &[Place], hinged: &[usize], issues: &mut Vec) { - let named: HashSet = - issues.iter().filter(|i| i.code != IssueCode::LooseEnd && i.code != IssueCode::Gap).flat_map(|i| i.keys.iter().copied()).collect(); + /// Creases with no hinge: outside every blank, or dividing no two panels; and creases beside a + /// panel that run `outside` every blank (by line) for the tolerance or more. + fn creases(&self, places: &[Place], hinged: &[usize], outside: &[f64], issues: &mut Vec) { + // A line drawn twice is still checked for where it lies. + let named: HashSet = issues + .iter() + .filter(|i| !matches!(i.code, IssueCode::LooseEnd | IssueCode::Gap | IssueCode::Duplicate)) + .flat_map(|i| i.keys.iter().copied()) + .collect(); // Whether each line is drawn (has a usable subpath), and whether one of its edges touches a // panel. let mut drawn = vec![false; self.lines.len()]; @@ -1137,11 +1339,16 @@ impl Context<'_> { } } for (line, l) in self.lines.iter().enumerate() { - if l.kind == LineKind::Cut || hinged.binary_search(&line).is_ok() || named.contains(&l.key) || drawn.get(line) != Some(&true) { + if l.kind == LineKind::Cut || drawn.get(line) != Some(&true) { continue; } - let code = if on_panel.get(line) == Some(&true) { IssueCode::NoSplit } else { IssueCode::Outside }; - issues.push(Issue::new(code, vec![l.key], None)); + let beside = on_panel.get(line) == Some(&true); + if hinged.binary_search(&line).is_err() && !named.contains(&l.key) { + issues.push(Issue::new(if beside { IssueCode::NoSplit } else { IssueCode::Outside }, vec![l.key], None)); + } + if beside && outside.get(line).is_some_and(|&o| o >= self.tolerance) { + issues.push(Issue::new(IssueCode::Outside, vec![l.key], None)); + } } } @@ -1219,7 +1426,7 @@ impl Context<'_> { /// The base panel of `panels`: the largest by area; panels whose areas differ by less than 1e-9 of /// the larger tie, and the tie goes to the one whose inside point is highest on the page, then /// leftmost. -pub fn base_panel(panels: &[Panel]) -> Option { +fn base_panel(panels: &[Panel]) -> Option { let top = panels.iter().map(|p| p.area).fold(f64::NEG_INFINITY, f64::max); if !top.is_finite() { return None; diff --git a/crates/three-d/src/fold/tests.rs b/crates/three-d/src/fold/tests.rs index a3f2c68d37..ef014300c0 100644 --- a/crates/three-d/src/fold/tests.rs +++ b/crates/three-d/src/fold/tests.rs @@ -13,7 +13,7 @@ fn poly(points: &[(f64, f64)], closed: bool) -> PathData { } fn line(kind: LineKind, points: &[(f64, f64)], closed: bool, key: u64) -> FoldLine { - FoldLine { path: poly(points, closed), kind, angle: None, key } + FoldLine { path: poly(points, closed), kind, key } } fn cut(points: &[(f64, f64)], key: u64) -> FoldLine { @@ -131,7 +131,7 @@ fn a_tray_has_a_base_four_walls_and_four_hinges() { assert_eq!(areas(&b[0]), vec![1_800_000, 1_800_000, 3_000_000, 3_000_000, 6_000_000]); assert_eq!(b[0].hinges.len(), 4); for h in &b[0].hinges { - assert!(h.straight && h.angle == 90.0 && h.keys.len() == 1, "{h:?}"); + assert!(h.straight && h.keys.len() == 1, "{h:?}"); assert!((h.from.distance(h.to) - if h.keys[0] % 2 == 0 { 100.0 } else { 60.0 }).abs() < 1e-6, "{h:?}"); } assert_eq!(base_panel(&b[0].panels).map(|i| (b[0].panels[i].area).round()), Some(6000.0)); @@ -188,7 +188,7 @@ fn a_round_tuck_flap_folds_like_any_panel() { bp.curve_to(p(100.0, 10.0), p(80.0, 0.0), p(50.0, 0.0)); bp.curve_to(p(20.0, 0.0), p(0.0, 10.0), p(0.0, 40.0)); bp.close_path(); - let lines = vec![FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Cut, angle: None, key: 1 }, crease((0.0, 40.0), (100.0, 40.0), 2)]; + let lines = vec![FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Cut, key: 1 }, crease((0.0, 40.0), (100.0, 40.0), 2)]; let (b, issues) = check(&lines); assert!(issues.is_empty(), "{issues:?}"); assert_eq!(b[0].panels.len(), 2); @@ -353,7 +353,7 @@ fn an_outline_drawn_twice_keeps_its_material() { // The same two squares as the subpaths of one compound path. let mut twice = poly(&square, true); twice.subpaths.extend(poly(&square, true).subpaths); - let (b, issues) = check(&[FoldLine { path: twice, kind: LineKind::Cut, angle: None, key: 1 }]); + let (b, issues) = check(&[FoldLine { path: twice, kind: LineKind::Cut, key: 1 }]); assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}"); assert_eq!(issues[0].keys, vec![1]); assert_eq!(areas(&b[0]), vec![10_000_000]); @@ -412,6 +412,150 @@ fn a_window_of_open_lines_with_a_slit_to_its_corner_is_still_a_hole() { let (b, issues) = check(&lines); assert!(issues.is_empty(), "{issues:?}"); assert_eq!((b[0].holes.len(), areas(&b[0])), (1, areas(&closed[0]))); + // A cut across the window of open lines, so that three lines meet at two of its corners. + let mut lines = vec![cut(&corners, 1), line(LineKind::Cut, &[(40.0, 0.0), (40.0, 40.0)], false, 2)]; + for k in 0..4 { + lines.push(line(LineKind::Cut, &[window[k], window[(k + 1) % 4]], false, 3 + k as u64)); + } + lines.push(line(LineKind::Cut, &[(40.0, 40.0), (60.0, 60.0)], false, 20)); + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!((b[0].holes.len(), areas(&b[0])), (1, areas(&closed[0]))); + // The outline and the window both as open lines, joined by two slits: the same as when both are + // closed. + let slits = [line(LineKind::Cut, &[(0.0, 0.0), (40.0, 40.0)], false, 30), line(LineKind::Cut, &[(100.0, 100.0), (60.0, 60.0)], false, 31)]; + let (want, want_issues) = check(&[cut(&corners, 1), cut(&window, 3), slits[0].clone(), slits[1].clone()]); + let mut lines: Vec = (0..4).map(|k| line(LineKind::Cut, &[corners[k], corners[(k + 1) % 4]], false, 10 + k as u64)).collect(); + for k in 0..4 { + lines.push(line(LineKind::Cut, &[window[k], window[(k + 1) % 4]], false, 3 + k as u64)); + } + lines.extend(slits); + let (b, issues) = check(&lines); + assert_eq!(codes(&issues), codes(&want_issues), "{issues:?}"); + assert_eq!((b[0].holes.len(), areas(&b[0])), (want[0].holes.len(), areas(&want[0]))); + assert_eq!(want[0].holes.len(), 1); +} + +#[test] +fn a_slot_drawn_across_the_outline_is_a_notch_not_a_hole() { + let outline = || cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1); + let (b, issues) = check(&[outline(), cut(&[(48.0, -10.0), (52.0, -10.0), (52.0, 20.0), (48.0, 20.0)], 2)]); + assert!(issues.is_empty(), "{issues:?}"); + assert!(b[0].holes.is_empty(), "{:?}", b[0].holes); + let notched = cut(&[(0.0, 0.0), (48.0, 0.0), (48.0, 20.0), (52.0, 20.0), (52.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1); + assert_eq!(areas(&b[0]), areas(&check(std::slice::from_ref(¬ched)).0[0])); + // A crease in the notch lies outside the blank, and one that runs on into it from a panel too. + let slot = || cut(&[(48.0, -10.0), (52.0, -10.0), (52.0, 20.0), (48.0, 20.0)], 2); + let (_, issues) = check(&[outline(), slot(), crease((49.0, 5.0), (51.0, 5.0), 3)]); + assert_eq!(codes(&issues), vec!["outside"], "{issues:?}"); + let (_, issues) = check(&[outline(), slot(), crease((50.0, 5.0), (50.0, 100.0), 3)]); + let (_, want) = check(&[notched, crease((50.0, 5.0), (50.0, 100.0), 3)]); + assert_eq!(codes(&issues), codes(&want), "{issues:?}"); + assert!(codes(&issues).contains(&"outside"), "{issues:?}"); + // A cutout whose top side lies on the outline opens onto the outside directly. + let flush = || cut(&[(48.0, 0.0), (52.0, 0.0), (52.0, 20.0), (48.0, 20.0)], 2); + let (b, issues) = check(&[outline(), flush()]); + assert!(b[0].holes.is_empty() && !codes(&issues).contains(&"ambiguous"), "{:?} {issues:?}", b[0].holes); + let (_, issues) = check(&[outline(), flush(), crease((49.0, 5.0), (51.0, 5.0), 3)]); + assert!(codes(&issues).contains(&"outside") && !codes(&issues).contains(&"ambiguous"), "{issues:?}"); + // A window joined to the outline by a slit stays a hole when a cut across it leaves a sliver. + let window = || cut(&[(40.0, 40.0), (60.0, 40.0), (60.0, 60.0), (40.0, 60.0)], 4); + let slit = || line(LineKind::Cut, &[(40.0, 0.0), (40.0, 40.0)], false, 5); + let (b, _) = check(&[outline(), window(), slit(), line(LineKind::Cut, &[(40.0, 40.004), (60.0, 40.004)], false, 6)]); + assert_eq!(b[0].holes.len(), 1, "{:?}", b[0].holes); + // And a window 0.004 pt below the outline, joined to it at both corners, leaving a sliver. + let near = cut(&[(40.0, 0.004), (60.0, 0.004), (60.0, 20.0), (40.0, 20.0)], 4); + let joins = [line(LineKind::Cut, &[(40.0, 0.0), (40.0, 0.004)], false, 5), line(LineKind::Cut, &[(60.0, 0.0), (60.0, 0.004)], false, 6)]; + let (b, _) = check(&[outline(), near, joins[0].clone(), joins[1].clone()]); + assert_eq!(b[0].holes.len(), 1, "{:?}", b[0].holes); +} + +#[test] +fn many_small_outlines_of_open_lines_fit_the_gap_search() { + // 784 unit squares 3 pt apart, each four open lines, at a tolerance of 0.5 pt. + let mut lines = vec![]; + for i in 0..28u64 { + for j in 0..28u64 { + let (x, y) = (3.0 * i as f64, 3.0 * j as f64); + let c = [(x, y), (x + 1.0, y), (x + 1.0, y + 1.0), (x, y + 1.0)]; + for k in 0..4 { + lines.push(line(LineKind::Cut, &[c[k], c[(k + 1) % 4]], false, 4 * (28 * i + j) + k as u64)); + } + } + } + let (b, issues) = blanks(&lines, 0.5); + assert!(!codes(&issues).contains(&"tooComplex"), "{issues:?}"); + assert_eq!(b.len(), 784); +} + +#[test] +fn thousands_of_cut_lines_on_top_of_each_other_are_too_complex_before_the_gap_search() { + let lines: Vec = (0..3000u64).map(|k| line(LineKind::Cut, &[(0.0, 0.0), (100.0, 0.0)], false, k)).collect(); + let (b, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["tooComplex"], "{issues:?}"); + assert!(b.is_empty()); +} + +#[test] +fn cut_lines_that_cross_an_outline_of_open_lines_leave_every_cell_material() { + // A 90 pt square whose sides are open lines ending every 30 pt, and four cut lines right across + // it: nine pieces of material, as with a closed outline. + let mut lines = vec![]; + for k in 0..3 { + let (a, b) = (30.0 * k as f64, 30.0 * (k + 1) as f64); + for (i, seg) in [[(a, 0.0), (b, 0.0)], [(90.0, a), (90.0, b)], [(b, 90.0), (a, 90.0)], [(0.0, b), (0.0, a)]].iter().enumerate() { + lines.push(line(LineKind::Cut, seg, false, 10 + 4 * k as u64 + i as u64)); + } + } + let across = [[(30.0, 0.0), (30.0, 90.0)], [(60.0, 0.0), (60.0, 90.0)], [(0.0, 30.0), (90.0, 30.0)], [(0.0, 60.0), (90.0, 60.0)]]; + for (i, seg) in across.iter().enumerate() { + lines.push(line(LineKind::Cut, seg, false, 30 + i as u64)); + } + let mut closed = vec![cut(&[(0.0, 0.0), (90.0, 0.0), (90.0, 90.0), (0.0, 90.0)], 1)]; + closed.extend(lines.iter().skip(12).cloned()); + let (want, want_issues) = check(&closed); + let (b, issues) = check(&lines); + assert_eq!(codes(&issues), codes(&want_issues), "{issues:?}"); + let pieces = |b: &[Blank]| b.iter().map(|x| (x.panels.len(), x.holes.len())).collect::>(); + assert_eq!(pieces(&b), pieces(&want)); + assert_eq!(b.iter().map(|x| x.panels.len()).sum::(), 9); + // With the crossing lines drawn in 30 pt pieces, the four pieces round the middle cell meet end + // to end and count as one closed cut line, whether the outline is closed or drawn in pieces. + let mut split = vec![]; + for (i, seg) in across.iter().enumerate() { + let (a, b) = (seg[0], seg[1]); + for k in 0..3 { + let at = |t: f64| (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t); + split.push(line(LineKind::Cut, &[at(k as f64 / 3.0), at((k + 1) as f64 / 3.0)], false, 40 + 3 * i as u64 + k as u64)); + } + } + let mut closed = vec![cut(&[(0.0, 0.0), (90.0, 0.0), (90.0, 90.0), (0.0, 90.0)], 1)]; + closed.extend(split.iter().cloned()); + let (want, want_issues) = check(&closed); + let mut open: Vec = lines.iter().take(12).cloned().collect(); + open.extend(split); + let (b, issues) = check(&open); + assert_eq!(codes(&issues), codes(&want_issues), "{issues:?}"); + assert_eq!(pieces(&b), pieces(&want)); +} + +#[test] +fn a_curved_crease_is_measured_at_its_farthest_point_from_its_line() { + // A crease from corner to corner of a square: its curve strays about 10.1 pt from the diagonal, + // where samples at quarters of it see 9.8 pt. + let off = 35.0 / 2f64.sqrt(); + let mut bp = BezPath::new(); + bp.move_to(p(0.0, 0.0)); + bp.curve_to(p(10000.0 / 3.0 - off, 10000.0 / 3.0 + off), p(20000.0 / 3.0 + off, 20000.0 / 3.0 - off), p(10000.0, 10000.0)); + let lines = vec![ + cut(&[(0.0, 0.0), (10000.0, 0.0), (10000.0, 10000.0), (0.0, 10000.0)], 1), + FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Crease, key: 2 }, + ]; + let (b, issues) = blanks(&lines, 10.0); + assert_eq!(codes(&issues), vec!["notStraight"], "{issues:?}"); + assert_eq!(b[0].hinges.len(), 1); + let (_, issues) = blanks(&lines, 10.5); + assert!(issues.is_empty(), "{issues:?}"); } #[test] @@ -541,6 +685,38 @@ fn lines_on_top_of_each_other_are_reported() { assert_eq!(issues[0].keys, vec![10, 20]); assert_eq!(b[0].hinges.len(), 4); assert_eq!(b[0].hinges.iter().find(|h| h.keys.contains(&20)).map(|h| h.keys.clone()), Some(vec![10, 20])); + + // A perforation over a crease, lines of two kinds that fold. + let mut lines = tray(); + lines.push(line(LineKind::Perforation, &[(130.0, 30.0), (30.0, 30.0)], false, 20)); + let (_, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}"); + assert_eq!(issues[0].keys, vec![10, 20]); + + // A crease drawn twice outside the blank is reported where it lies as well. + let mut lines = tray(); + lines.push(crease((200.0, 0.0), (250.0, 0.0), 20)); + lines.push(crease((250.0, 0.0), (200.0, 0.0), 21)); + let (_, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["duplicate", "outside", "outside"], "{issues:?}"); + assert_eq!((issues[1].keys.clone(), issues[2].keys.clone()), (vec![20], vec![21])); +} + +#[test] +fn a_crease_that_runs_past_the_outline_is_reported() { + let outline = || cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)], 1); + // 5 pt past the outline at each end: the hinge is built, and the line is reported. + let (b, issues) = check(&[outline(), crease((50.0, -5.0), (50.0, 55.0), 2)]); + assert_eq!(codes(&issues), vec!["outside"], "{issues:?}"); + assert_eq!(issues[0].keys, vec![2]); + assert_eq!(b[0].hinges.len(), 1); + // Past it by less than the tolerance: no issue. + let (b, issues) = check(&[outline(), crease((50.0, -0.05), (50.0, 50.0), 2)]); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(b[0].hinges.len(), 1); + // A crease drawn round a sliver inside the blank does not run outside it. + let (_, issues) = check(&[outline(), line(LineKind::Crease, &[(50.0, 10.0), (50.004, 10.0), (50.004, 40.0), (50.0, 40.0)], true, 2)]); + assert!(!codes(&issues).contains(&"outside"), "{issues:?}"); } #[test] @@ -682,15 +858,15 @@ fn lines_in_a_hole_are_ambiguous() { } #[test] -fn partial_cuts_fold_the_other_way_and_a_line_s_own_angle_wins() { +fn partial_cuts_and_perforations_make_hinges_as_creases_do() { let mut lines = tray(); lines[1].kind = LineKind::PartialCut; - lines[2].angle = Some(45.0); lines[3].kind = LineKind::Perforation; let (b, issues) = check(&lines); assert!(issues.is_empty(), "{issues:?}"); - let angle = |key: u64| b[0].hinges.iter().find(|h| h.keys == vec![key]).map(|h| h.angle); - assert_eq!((angle(10), angle(11), angle(12), angle(13)), (Some(-90.0), Some(45.0), Some(90.0), Some(90.0))); + let mut keys: Vec> = b[0].hinges.iter().map(|h| h.keys.clone()).collect(); + keys.sort_unstable(); + assert_eq!(keys, vec![vec![10], vec![11], vec![12], vec![13]]); } #[test] diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index 01b5c75d9f..f232d265e9 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -4,6 +4,8 @@ //! Open profiles optionally close their circular ends with caps, and a partial sweep its cut sides. Faces are projected and sorted back to front, //! then flat or smoothly shaded with vector gradients. This preview uses a painter's algorithm, not a depth buffer: //! intersecting profiles can have ambiguous visibility and are not solid modelling inputs. +//! +//! [`fold`] finds the panels and hinges of a flat packaging blank from its fold lines. #![forbid(unsafe_code)] pub mod fold; diff --git a/crates/ui-egui/src/addons/packaging.rs b/crates/ui-egui/src/addons/packaging.rs index 1e827a7efc..54f233d945 100644 --- a/crates/ui-egui/src/addons/packaging.rs +++ b/crates/ui-egui/src/addons/packaging.rs @@ -92,7 +92,7 @@ impl Checked { fn summary(&self) -> String { let errors = self.issues.iter().filter(|i| i.error).count(); crate::i18n::fmt( - "Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings}", + "Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings}", &[ ("panels", &self.panels.to_string()), ("hinges", &self.hinges.to_string()), diff --git a/crates/ui-egui/src/addons/packaging/tests.rs b/crates/ui-egui/src/addons/packaging/tests.rs index 808956e4d7..93fbb2b8d2 100644 --- a/crates/ui-egui/src/addons/packaging/tests.rs +++ b/crates/ui-egui/src/addons/packaging/tests.rs @@ -183,10 +183,10 @@ fn check_fold_lines_lists_its_issues_in_the_panel_until_the_document_changes() { assert!(!crate::panel_docking::showing(&app.ui, ID)); menus::invoke(&mut app, CHECK, item.params.clone()); assert!(crate::panel_docking::showing(&app.ui, ID), "the panel opens"); - assert_eq!(app.ui.status, "Panels: 2, creases: 1, errors: 1, warnings: 0"); + assert_eq!(app.ui.status, "Panels: 2, hinges: 1, errors: 1, warnings: 0"); let text = frames(&mut app, &ctx, None); assert!(text.contains("A cut line ends without meeting another cut line."), "{text}"); - assert!(text.contains("Panels: 2, creases: 1, errors: 1, warnings: 0") && text.contains("Select"), "{text}"); + assert!(text.contains("Panels: 2, hinges: 1, errors: 1, warnings: 0") && text.contains("Select"), "{text}"); // Any change to the document takes the list away. app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap(); let text = frames(&mut app, &ctx, None); @@ -209,7 +209,7 @@ fn the_check_button_checks_and_clicking_an_issue_selects_its_lines() { // A clean blank: no issues. app.run("edit.clear", json!({})).unwrap(); let text = frames(&mut app, &ctx, Some("Check")); - assert!(text.contains("No issues found.") && text.contains("Panels: 2, creases: 1, errors: 0, warnings: 0"), "{text}"); + assert!(text.contains("No issues found.") && text.contains("Panels: 2, hinges: 1, errors: 0, warnings: 0"), "{text}"); } #[test] @@ -220,25 +220,27 @@ fn issues_and_the_summary_show_in_the_interface_language() { let text = frames(&mut app, &ctx, Some(crate::i18n::t("Check"))); crate::i18n::set_current(crate::i18n::Lang::EN); assert!(!text.contains("A cut line ends") && !text.contains("Panels:"), "{text}"); - assert!(text.contains("Schnittlinie") && text.contains('2'), "{text}"); + assert!(text.contains("Eine Schnittlinie endet, ohne auf eine andere Schnittlinie zu treffen."), "{text}"); + assert!(text.contains("Felder: 2, Scharniere: 1, Fehler: 1, Warnungen: 0"), "{text}"); } -/// The messages `addon.packaging.check` gives its issues, one for each code (two for `noCut`). -const ISSUE_MESSAGES: [&str; 16] = [ +/// The messages `addon.packaging.check` gives its issues, one for each code (three for `noCut`). +const ISSUE_MESSAGES: [&str; 17] = [ "No cut lines are in the selection.", "No cut lines are in the document.", + "No cut lines are among the given objects.", "The cut lines do not enclose an area.", "A cut line ends without meeting another cut line.", "A gap between cut lines was closed.", "The fold lines are too complex to check.", "A cut line and a crease lie on top of each other.", - "Two lines of the same role lie on top of each other.", + "Two fold lines lie on top of each other.", "A crease ends inside a panel.", "A crease does not divide two panels.", - "A crease lies outside the cut outline.", - "A crease that is not straight is folded along one straight line.", + "A crease lies outside the cut outline, wholly or in part.", + "The pieces of a hinge are not on one straight line.", "A gap between cut lines is too narrow to tell apart.", - "A cut-out area holds other fold lines.", + "A cut-out area holds other fold lines or another blank.", "A panel is not joined to the rest by a crease.", "A fold line is on a non-printing layer.", ]; @@ -250,7 +252,7 @@ fn every_issue_message_translates_in_every_complete_message_catalog() { "ca", "nl", "da", ] { let lang = crate::i18n::Lang::from_code(code).unwrap(); - for m in ISSUE_MESSAGES.into_iter().chain(["Panels: 3, creases: 2, errors: 1, warnings: 0"]) { + for m in ISSUE_MESSAGES.into_iter().chain(["Panels: 3, hinges: 2, errors: 1, warnings: 0"]) { assert_ne!(crate::i18n::message(lang, m), m, "{code}: {m}"); } } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index ab9ed92de5..7beb9f89eb 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -7093,14 +7093,15 @@ breakText Glyphs Глифи @msg A gap between cut lines was closed. Процеп между линии за рязане беше затворен. @msg The fold lines are too complex to check. Линиите на сгъване са твърде сложни за проверка. @msg A cut line and a crease lie on top of each other. Линия за рязане и линия за биговане лежат една върху друга. -@msg Two lines of the same role lie on top of each other. Две линии от един и същи вид лежат една върху друга. +@msg No cut lines are among the given objects. Сред дадените обекти няма линии за рязане. +@msg Two fold lines lie on top of each other. Две линии на сгъване лежат една върху друга. @msg A crease ends inside a panel. Линия за биговане завършва вътре в панел. @msg A crease does not divide two panels. Линия за биговане не разделя два панела. -@msg A crease lies outside the cut outline. Линия за биговане лежи извън контура за рязане. -@msg A crease that is not straight is folded along one straight line. Линия за биговане, която не е права, се сгъва по една права линия. +@msg A crease lies outside the cut outline, wholly or in part. Линия за биговане лежи изцяло или отчасти извън контура за рязане. +@msg The pieces of a hinge are not on one straight line. Частите на една панта не лежат на една права линия. @msg A gap between cut lines is too narrow to tell apart. Процеп между линии за рязане е твърде тесен, за да се различи. -@msg A cut-out area holds other fold lines. Изрязана област съдържа други линии на сгъване. +@msg A cut-out area holds other fold lines or another blank. Изрязана област съдържа други линии на сгъване или друг разкрой. @msg A panel is not joined to the rest by a crease. Панел не е свързан с останалите с линия за биговане. @msg A fold line is on a non-printing layer. Линия на сгъване е на слой, който не се печата. -@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Панели: {panels}, бигове: {hinges}, грешки: {errors}, предупреждения: {warnings} +@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панели: {panels}, панти: {hinges}, грешки: {errors}, предупреждения: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer трябва да е "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index d6cc94f911..22c2d3b7c7 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -7146,14 +7146,15 @@ shape Open Otvoren @msg A gap between cut lines was closed. Razmak između linija rezanja je zatvoren. @msg The fold lines are too complex to check. Linije savijanja su previše složene za provjeru. @msg A cut line and a crease lie on top of each other. Linija rezanja i linija bigovanja leže jedna preko druge. -@msg Two lines of the same role lie on top of each other. Dvije linije iste vrste leže jedna preko druge. +@msg No cut lines are among the given objects. Među zadanim objektima nema linija rezanja. +@msg Two fold lines lie on top of each other. Dvije linije savijanja leže jedna preko druge. @msg A crease ends inside a panel. Linija bigovanja završava unutar panela. @msg A crease does not divide two panels. Linija bigovanja ne razdvaja dva panela. -@msg A crease lies outside the cut outline. Linija bigovanja leži izvan konture rezanja. -@msg A crease that is not straight is folded along one straight line. Linija bigovanja koja nije ravna savija se duž jedne prave linije. +@msg A crease lies outside the cut outline, wholly or in part. Linija bigovanja leži potpuno ili djelimično izvan konture rezanja. +@msg The pieces of a hinge are not on one straight line. Dijelovi jedne šarke ne leže na jednoj pravoj liniji. @msg A gap between cut lines is too narrow to tell apart. Razmak između linija rezanja je preuzak da bi se razlikovao. -@msg A cut-out area holds other fold lines. Izrezana površina sadrži druge linije savijanja. +@msg A cut-out area holds other fold lines or another blank. Izrezana površina sadrži druge linije savijanja ili drugi kroj. @msg A panel is not joined to the rest by a crease. Panel nije povezan s ostatkom nijednom linijom bigovanja. @msg A fold line is on a non-printing layer. Linija savijanja je na sloju koji se ne štampa. -@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Paneli: {panels}, bigovi: {hinges}, greške: {errors}, upozorenja: {warnings} +@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneli: {panels}, šarke: {hinges}, greške: {errors}, upozorenja: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer mora biti "singleLine", "everyLine", "standardSingleLine" ili "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 0089095906..683dcc0d93 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7954,14 +7954,15 @@ breakText Glyphs Glifs @msg A gap between cut lines was closed. S’ha tancat un buit entre línies de tall. @msg The fold lines are too complex to check. Les línies de plegat són massa complexes per comprovar-les. @msg A cut line and a crease lie on top of each other. Una línia de tall i una d’hendit estan superposades. -@msg Two lines of the same role lie on top of each other. Dues línies del mateix tipus estan superposades. +@msg No cut lines are among the given objects. No hi ha cap línia de tall entre els objectes indicats. +@msg Two fold lines lie on top of each other. Dues línies de plegat estan superposades. @msg A crease ends inside a panel. Una línia d’hendit acaba dins d’un panell. @msg A crease does not divide two panels. Una línia d’hendit no separa dos panells. -@msg A crease lies outside the cut outline. Una línia d’hendit és fora del contorn de tall. -@msg A crease that is not straight is folded along one straight line. Una línia d’hendit que no és recta es plega al llarg d’una sola línia recta. +@msg A crease lies outside the cut outline, wholly or in part. Una línia d’hendit és fora del contorn de tall, del tot o en part. +@msg The pieces of a hinge are not on one straight line. Els trams d’una frontissa no són en una sola línia recta. @msg A gap between cut lines is too narrow to tell apart. Un buit entre línies de tall és massa estret per distingir-lo. -@msg A cut-out area holds other fold lines. Una àrea retallada conté altres línies de plegat. +@msg A cut-out area holds other fold lines or another blank. Una àrea retallada conté altres línies de plegat o un altre troquelat. @msg A panel is not joined to the rest by a crease. Un panell no està unit a la resta per cap línia d’hendit. @msg A fold line is on a non-printing layer. Una línia de plegat és en una capa que no s’imprimeix. -@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Panells: {panels}, hendits: {hinges}, errors: {errors}, avisos: {warnings} +@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panells: {panels}, frontisses: {hinges}, errors: {errors}, avisos: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer ha de ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 299aa6cedc..69e387e26c 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -9751,13 +9751,14 @@ breakText Glyphs Glyfy @msg A gap between cut lines was closed. Mezera mezi liniemi řezu byla uzavřena. @msg The fold lines are too complex to check. Linie skladu jsou příliš složité na kontrolu. @msg A cut line and a crease lie on top of each other. Linie řezu a linie bigu leží přes sebe. -@msg Two lines of the same role lie on top of each other. Dvě linie stejného typu leží přes sebe. +@msg No cut lines are among the given objects. Mezi zadanými objekty nejsou žádné linie řezu. +@msg Two fold lines lie on top of each other. Dvě linie skladu leží přes sebe. @msg A crease ends inside a panel. Linie bigu končí uvnitř panelu. @msg A crease does not divide two panels. Linie bigu nerozděluje dva panely. -@msg A crease lies outside the cut outline. Linie bigu leží mimo obrys řezu. -@msg A crease that is not straight is folded along one straight line. Linie bigu, která není rovná, se ohýbá podél jedné přímky. +@msg A crease lies outside the cut outline, wholly or in part. Linie bigu leží zcela nebo zčásti mimo obrys řezu. +@msg The pieces of a hinge are not on one straight line. Části jednoho pantu neleží na jedné přímce. @msg A gap between cut lines is too narrow to tell apart. Mezera mezi liniemi řezu je příliš úzká na rozlišení. -@msg A cut-out area holds other fold lines. Vyříznutá oblast obsahuje další linie skladu. +@msg A cut-out area holds other fold lines or another blank. Vyříznutá oblast obsahuje další linie skladu nebo jiný přířez. @msg A panel is not joined to the rest by a crease. Panel není se zbytkem spojen žádnou linií bigu. @msg A fold line is on a non-printing layer. Linie skladu je na netisknutelné vrstvě. -@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Panely: {panels}, bigy: {hinges}, chyby: {errors}, upozornění: {warnings} +@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panely: {panels}, panty: {hinges}, chyby: {errors}, upozornění: {warnings} diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 647596237c..395a2d01c4 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -9853,14 +9853,15 @@ breakText Glyphs Glyffer @msg A gap between cut lines was closed. Et mellemrum mellem skærelinjer blev lukket. @msg The fold lines are too complex to check. Foldelinjerne er for komplekse til at kontrollere. @msg A cut line and a crease lie on top of each other. En skærelinje og en rillelinje ligger oven på hinanden. -@msg Two lines of the same role lie on top of each other. To linjer af samme type ligger oven på hinanden. +@msg No cut lines are among the given objects. Der er ingen skærelinjer blandt de angivne objekter. +@msg Two fold lines lie on top of each other. To foldelinjer ligger oven på hinanden. @msg A crease ends inside a panel. En rillelinje slutter inde i et panel. @msg A crease does not divide two panels. En rillelinje deler ikke to paneler. -@msg A crease lies outside the cut outline. En rillelinje ligger uden for skærekonturen. -@msg A crease that is not straight is folded along one straight line. En rillelinje, der ikke er lige, foldes langs én ret linje. +@msg A crease lies outside the cut outline, wholly or in part. En rillelinje ligger helt eller delvist uden for skærekonturen. +@msg The pieces of a hinge are not on one straight line. Delene af et hængsel ligger ikke på én ret linje. @msg A gap between cut lines is too narrow to tell apart. Et mellemrum mellem skærelinjer er for smalt til at skelne. -@msg A cut-out area holds other fold lines. Et udskåret område indeholder andre foldelinjer. +@msg A cut-out area holds other fold lines or another blank. Et udskåret område indeholder andre foldelinjer eller et andet emne. @msg A panel is not joined to the rest by a crease. Et panel er ikke forbundet med resten af en rillelinje. @msg A fold line is on a non-printing layer. En foldelinje ligger på et lag, der ikke udskrives. -@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Paneler: {panels}, riller: {hinges}, fejl: {errors}, advarsler: {warnings} +@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneler: {panels}, hængsler: {hinges}, fejl: {errors}, advarsler: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer skal være "singleLine", "everyLine", "standardSingleLine" eller "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 4be132dc4f..f9df67b2bc 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -9349,13 +9349,14 @@ breakText Glyphs Glyphen @msg A gap between cut lines was closed. Eine Lücke zwischen Schnittlinien wurde geschlossen. @msg The fold lines are too complex to check. Die Faltlinien sind zu komplex für die Prüfung. @msg A cut line and a crease lie on top of each other. Eine Schnittlinie und eine Rilllinie liegen übereinander. -@msg Two lines of the same role lie on top of each other. Zwei Linien derselben Linienart liegen übereinander. +@msg No cut lines are among the given objects. Die angegebenen Objekte enthalten keine Schnittlinien. +@msg Two fold lines lie on top of each other. Zwei Faltlinien liegen übereinander. @msg A crease ends inside a panel. Eine Rilllinie endet innerhalb eines Felds. @msg A crease does not divide two panels. Eine Rilllinie trennt keine zwei Felder. -@msg A crease lies outside the cut outline. Eine Rilllinie liegt außerhalb der Schnittkontur. -@msg A crease that is not straight is folded along one straight line. Eine nicht gerade Rilllinie wird entlang einer geraden Linie gefaltet. +@msg A crease lies outside the cut outline, wholly or in part. Eine Rilllinie liegt ganz oder teilweise außerhalb der Schnittkontur. +@msg The pieces of a hinge are not on one straight line. Die Teile eines Scharniers liegen nicht auf einer geraden Linie. @msg A gap between cut lines is too narrow to tell apart. Eine Lücke zwischen Schnittlinien ist zu schmal, um sie zu unterscheiden. -@msg A cut-out area holds other fold lines. Ein ausgeschnittener Bereich enthält weitere Faltlinien. +@msg A cut-out area holds other fold lines or another blank. Ein ausgeschnittener Bereich enthält weitere Faltlinien oder einen anderen Zuschnitt. @msg A panel is not joined to the rest by a crease. Ein Feld ist durch keine Rilllinie mit den übrigen verbunden. @msg A fold line is on a non-printing layer. Eine Faltlinie liegt auf einer nicht druckbaren Ebene. -@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Felder: {panels}, Rilllinien: {hinges}, Fehler: {errors}, Warnungen: {warnings} +@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Felder: {panels}, Scharniere: {hinges}, Fehler: {errors}, Warnungen: {warnings} diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 05c6a32103..b27f4b5867 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7928,14 +7928,15 @@ breakText Glyphs Γλύφοι @msg A gap between cut lines was closed. Ένα κενό ανάμεσα σε γραμμές κοπής κλείστηκε. @msg The fold lines are too complex to check. Οι γραμμές δίπλωσης είναι πολύ σύνθετες για έλεγχο. @msg A cut line and a crease lie on top of each other. Μια γραμμή κοπής και μια γραμμή πτύχωσης βρίσκονται η μία πάνω στην άλλη. -@msg Two lines of the same role lie on top of each other. Δύο γραμμές του ίδιου τύπου βρίσκονται η μία πάνω στην άλλη. +@msg No cut lines are among the given objects. Τα δοσμένα αντικείμενα δεν περιέχουν γραμμές κοπής. +@msg Two fold lines lie on top of each other. Δύο γραμμές δίπλωσης βρίσκονται η μία πάνω στην άλλη. @msg A crease ends inside a panel. Μια γραμμή πτύχωσης τελειώνει μέσα σε ένα πάνελ. @msg A crease does not divide two panels. Μια γραμμή πτύχωσης δεν χωρίζει δύο πάνελ. -@msg A crease lies outside the cut outline. Μια γραμμή πτύχωσης βρίσκεται έξω από το περίγραμμα κοπής. -@msg A crease that is not straight is folded along one straight line. Μια γραμμή πτύχωσης που δεν είναι ευθεία διπλώνεται κατά μήκος μίας ευθείας. +@msg A crease lies outside the cut outline, wholly or in part. Μια γραμμή πτύχωσης βρίσκεται εν όλω ή εν μέρει έξω από το περίγραμμα κοπής. +@msg The pieces of a hinge are not on one straight line. Τα τμήματα ενός μεντεσέ δεν βρίσκονται σε μία ευθεία. @msg A gap between cut lines is too narrow to tell apart. Ένα κενό ανάμεσα σε γραμμές κοπής είναι πολύ στενό για να διακριθεί. -@msg A cut-out area holds other fold lines. Μια αποκομμένη περιοχή περιέχει άλλες γραμμές δίπλωσης. +@msg A cut-out area holds other fold lines or another blank. Μια αποκομμένη περιοχή περιέχει άλλες γραμμές δίπλωσης ή άλλο ανάπτυγμα. @msg A panel is not joined to the rest by a crease. Ένα πάνελ δεν συνδέεται με τα υπόλοιπα με καμία γραμμή πτύχωσης. @msg A fold line is on a non-printing layer. Μια γραμμή δίπλωσης βρίσκεται σε επίπεδο που δεν εκτυπώνεται. -@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Πάνελ: {panels}, πτυχώσεις: {hinges}, σφάλματα: {errors}, προειδοποιήσεις: {warnings} +@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Πάνελ: {panels}, μεντεσέδες: {hinges}, σφάλματα: {errors}, προειδοποιήσεις: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" το composer πρέπει να είναι "singleLine", "everyLine", "standardSingleLine" ή "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 12e483f369..f2f1b14574 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7915,14 +7915,15 @@ breakText Glyphs Glifos @msg A gap between cut lines was closed. Se cerró un hueco entre líneas de corte. @msg The fold lines are too complex to check. Las líneas de plegado son demasiado complejas para comprobarlas. @msg A cut line and a crease lie on top of each other. Una línea de corte y una de hendido están superpuestas. -@msg Two lines of the same role lie on top of each other. Dos líneas del mismo tipo están superpuestas. +@msg No cut lines are among the given objects. No hay líneas de corte entre los objetos indicados. +@msg Two fold lines lie on top of each other. Dos líneas de plegado están superpuestas. @msg A crease ends inside a panel. Una línea de hendido termina dentro de un panel. @msg A crease does not divide two panels. Una línea de hendido no separa dos paneles. -@msg A crease lies outside the cut outline. Una línea de hendido está fuera del contorno de corte. -@msg A crease that is not straight is folded along one straight line. Una línea de hendido que no es recta se pliega a lo largo de una sola línea recta. +@msg A crease lies outside the cut outline, wholly or in part. Una línea de hendido está fuera del contorno de corte, total o parcialmente. +@msg The pieces of a hinge are not on one straight line. Los tramos de una bisagra no están en una sola línea recta. @msg A gap between cut lines is too narrow to tell apart. Un hueco entre líneas de corte es demasiado estrecho para distinguirlo. -@msg A cut-out area holds other fold lines. Un área recortada contiene otras líneas de plegado. +@msg A cut-out area holds other fold lines or another blank. Un área recortada contiene otras líneas de plegado u otro troquelado. @msg A panel is not joined to the rest by a crease. Un panel no está unido al resto por ninguna línea de hendido. @msg A fold line is on a non-printing layer. Una línea de plegado está en una capa que no se imprime. -@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Paneles: {panels}, hendidos: {hinges}, errores: {errors}, advertencias: {warnings} +@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneles: {panels}, bisagras: {hinges}, errores: {errors}, advertencias: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer debe ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index db6163e7e3..7350f840e6 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -8011,14 +8011,15 @@ breakText Glyphs Merkit @msg A gap between cut lines was closed. Leikkausviivojen välinen rako suljettiin. @msg The fold lines are too complex to check. Taittoviivat ovat liian monimutkaisia tarkistettaviksi. @msg A cut line and a crease lie on top of each other. Leikkausviiva ja nuuttausviiva ovat päällekkäin. -@msg Two lines of the same role lie on top of each other. Kaksi samantyyppistä viivaa on päällekkäin. +@msg No cut lines are among the given objects. Annetuissa objekteissa ei ole leikkausviivoja. +@msg Two fold lines lie on top of each other. Kaksi taittoviivaa on päällekkäin. @msg A crease ends inside a panel. Nuuttausviiva päättyy paneelin sisään. @msg A crease does not divide two panels. Nuuttausviiva ei jaa kahta paneelia. -@msg A crease lies outside the cut outline. Nuuttausviiva on leikkausääriviivan ulkopuolella. -@msg A crease that is not straight is folded along one straight line. Nuuttausviiva, joka ei ole suora, taitetaan yhtä suoraa viivaa pitkin. +@msg A crease lies outside the cut outline, wholly or in part. Nuuttausviiva on kokonaan tai osittain leikkausääriviivan ulkopuolella. +@msg The pieces of a hinge are not on one straight line. Saranan osat eivät ole yhdellä suoralla. @msg A gap between cut lines is too narrow to tell apart. Leikkausviivojen välinen rako on liian kapea erotettavaksi. -@msg A cut-out area holds other fold lines. Leikattu alue sisältää muita taittoviivoja. +@msg A cut-out area holds other fold lines or another blank. Leikattu alue sisältää muita taittoviivoja tai toisen aihion. @msg A panel is not joined to the rest by a crease. Paneelia ei ole liitetty muihin millään nuuttausviivalla. @msg A fold line is on a non-printing layer. Taittoviiva on tasolla, jota ei tulosteta. -@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Paneelit: {panels}, nuuttaukset: {hinges}, virheet: {errors}, varoitukset: {warnings} +@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneelit: {panels}, saranat: {hinges}, virheet: {errors}, varoitukset: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer on oltava "singleLine", "everyLine", "standardSingleLine" tai "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 7ae0eab9c6..d720f44899 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -9736,14 +9736,15 @@ breakText Glyphs Glyphes @msg A gap between cut lines was closed. Un écart entre des lignes de découpe a été fermé. @msg The fold lines are too complex to check. Les lignes de pliage sont trop complexes pour être vérifiées. @msg A cut line and a crease lie on top of each other. Une ligne de découpe et une ligne de rainage se superposent. -@msg Two lines of the same role lie on top of each other. Deux lignes du même type se superposent. +@msg No cut lines are among the given objects. Les objets indiqués ne contiennent aucune ligne de découpe. +@msg Two fold lines lie on top of each other. Deux lignes de pliage se superposent. @msg A crease ends inside a panel. Une ligne de rainage se termine à l’intérieur d’un panneau. @msg A crease does not divide two panels. Une ligne de rainage ne sépare pas deux panneaux. -@msg A crease lies outside the cut outline. Une ligne de rainage se trouve hors du contour de découpe. -@msg A crease that is not straight is folded along one straight line. Une ligne de rainage qui n’est pas droite est pliée le long d’une seule ligne droite. +@msg A crease lies outside the cut outline, wholly or in part. Une ligne de rainage se trouve en tout ou en partie hors du contour de découpe. +@msg The pieces of a hinge are not on one straight line. Les morceaux d’une charnière ne sont pas sur une seule ligne droite. @msg A gap between cut lines is too narrow to tell apart. Un écart entre des lignes de découpe est trop étroit pour être distingué. -@msg A cut-out area holds other fold lines. Une zone découpée contient d’autres lignes de pliage. +@msg A cut-out area holds other fold lines or another blank. Une zone découpée contient d’autres lignes de pliage ou un autre flan. @msg A panel is not joined to the rest by a crease. Un panneau n’est relié au reste par aucune ligne de rainage. @msg A fold line is on a non-printing layer. Une ligne de pliage se trouve sur un calque non imprimable. -@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} {panels} panneau(x), {hinges} rainage(s), {errors} erreur(s), {warnings} avertissement(s) +@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} {panels} panneau(x), {hinges} charnière(s), {errors} erreur(s), {warnings} avertissement(s) @msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} pixels, c’est trop grand pour le GIF (65535 pixels par côté au plus) : réduisez la résolution diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index d7b10bf7c0..ee792315ff 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -4855,16 +4855,17 @@ swatch [Registration] [રજિસ્ટ્રેશન] @msg A gap between cut lines was closed. કટ લાઇન્સ વચ્ચેનો ગેપ બંધ કરવામાં આવ્યો. @msg The fold lines are too complex to check. ફોલ્ડ લાઇન્સ ચેક કરવા માટે ખૂબ જટિલ છે. @msg A cut line and a crease lie on top of each other. એક કટ લાઇન અને એક ક્રીઝ લાઇન એકબીજા પર છે. -@msg Two lines of the same role lie on top of each other. એક જ પ્રકારની બે લાઇન્સ એકબીજા પર છે. +@msg No cut lines are among the given objects. આપેલા ઑબ્જેક્ટ્સમાં કોઈ કટ લાઇન નથી. +@msg Two fold lines lie on top of each other. બે ફોલ્ડ લાઇન્સ એકબીજા પર છે. @msg A crease ends inside a panel. એક ક્રીઝ લાઇન પેનલની અંદર પૂરી થાય છે. @msg A crease does not divide two panels. એક ક્રીઝ લાઇન બે પેનલને અલગ કરતી નથી. -@msg A crease lies outside the cut outline. એક ક્રીઝ લાઇન કટ આઉટલાઇનની બહાર છે. -@msg A crease that is not straight is folded along one straight line. સીધી ન હોય તેવી ક્રીઝ લાઇન એક સીધી લાઇન પર ફોલ્ડ થાય છે. +@msg A crease lies outside the cut outline, wholly or in part. એક ક્રીઝ લાઇન પૂરેપૂરી અથવા આંશિક રીતે કટ આઉટલાઇનની બહાર છે. +@msg The pieces of a hinge are not on one straight line. એક હિન્જના ભાગો એક સીધી લાઇન પર નથી. @msg A gap between cut lines is too narrow to tell apart. કટ લાઇન્સ વચ્ચેનો ગેપ ઓળખવા માટે ખૂબ સાંકડો છે. -@msg A cut-out area holds other fold lines. એક કટ-આઉટ વિસ્તારમાં બીજી ફોલ્ડ લાઇન્સ છે. +@msg A cut-out area holds other fold lines or another blank. એક કટ-આઉટ વિસ્તારમાં બીજી ફોલ્ડ લાઇન્સ અથવા બીજું બ્લેન્ક છે. @msg A panel is not joined to the rest by a crease. એક પેનલ કોઈ ક્રીઝ લાઇનથી બાકીના સાથે જોડાયેલી નથી. @msg A fold line is on a non-printing layer. એક ફોલ્ડ લાઇન નોન-પ્રિન્ટિંગ લેયર પર છે. -@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} પેનલ: {panels}, ક્રીઝ: {hinges}, ભૂલો: {errors}, ચેતવણીઓ: {warnings} +@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} પેનલ: {panels}, હિન્જ: {hinges}, ભૂલો: {errors}, ચેતવણીઓ: {warnings} Middle Eastern & South Asian Single-line Composer સિંગલ-લાઇન કમ્પોઝર (મધ્ય પૂર્વ અને દક્ષિણ એશિયા) Middle Eastern & South Asian Every-line Composer એવરી-લાઇન કમ્પોઝર (મધ્ય પૂર્વ અને દક્ષિણ એશિયા) Standard Single-line Composer સ્ટાન્ડર્ડ સિંગલ-લાઇન કમ્પોઝર diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index f632881023..7398511e77 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -9356,13 +9356,14 @@ theme Appearance अपीयरेंस @msg A gap between cut lines was closed. कट लाइनों के बीच का गैप बंद कर दिया गया। @msg The fold lines are too complex to check. फ़ोल्ड लाइनें चेक करने के लिए बहुत जटिल हैं। @msg A cut line and a crease lie on top of each other. एक कट लाइन और एक क्रीज़ लाइन एक-दूसरे के ऊपर हैं। -@msg Two lines of the same role lie on top of each other. एक ही प्रकार की दो लाइनें एक-दूसरे के ऊपर हैं। +@msg No cut lines are among the given objects. दिए गए ऑब्जेक्ट में कोई कट लाइन नहीं है। +@msg Two fold lines lie on top of each other. दो फ़ोल्ड लाइनें एक-दूसरे के ऊपर हैं। @msg A crease ends inside a panel. एक क्रीज़ लाइन किसी पैनल के अंदर खत्म होती है। @msg A crease does not divide two panels. एक क्रीज़ लाइन दो पैनलों को अलग नहीं करती। -@msg A crease lies outside the cut outline. एक क्रीज़ लाइन कट आउटलाइन के बाहर है। -@msg A crease that is not straight is folded along one straight line. जो क्रीज़ लाइन सीधी नहीं है, वह एक सीधी लाइन पर फ़ोल्ड होती है। +@msg A crease lies outside the cut outline, wholly or in part. एक क्रीज़ लाइन पूरी तरह या आंशिक रूप से कट आउटलाइन के बाहर है। +@msg The pieces of a hinge are not on one straight line. एक हिंज के हिस्से एक सीधी लाइन पर नहीं हैं। @msg A gap between cut lines is too narrow to tell apart. कट लाइनों के बीच का गैप पहचानने के लिए बहुत पतला है। -@msg A cut-out area holds other fold lines. एक कट-आउट एरिया में दूसरी फ़ोल्ड लाइनें हैं। +@msg A cut-out area holds other fold lines or another blank. एक कट-आउट एरिया में दूसरी फ़ोल्ड लाइनें या दूसरा ब्लैंक है। @msg A panel is not joined to the rest by a crease. कोई पैनल किसी क्रीज़ लाइन से बाकी से जुड़ा नहीं है। @msg A fold line is on a non-printing layer. एक फ़ोल्ड लाइन नॉन-प्रिंटिंग लेयर पर है। -@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} पैनल: {panels}, क्रीज़: {hinges}, एरर: {errors}, वॉर्निंग: {warnings} +@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} पैनल: {panels}, हिंज: {hinges}, एरर: {errors}, वॉर्निंग: {warnings} diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 5ecfe58e72..97cac8096b 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -9739,13 +9739,14 @@ breakText Glyphs Glifák @msg A gap between cut lines was closed. A vágóvonalak közötti rés le lett zárva. @msg The fold lines are too complex to check. A hajtásvonalak túl összetettek az ellenőrzéshez. @msg A cut line and a crease lie on top of each other. Egy vágóvonal és egy bigvonal egymáson fekszik. -@msg Two lines of the same role lie on top of each other. Két azonos típusú vonal egymáson fekszik. +@msg No cut lines are among the given objects. A megadott objektumok között nincs vágóvonal. +@msg Two fold lines lie on top of each other. Két hajtásvonal egymáson fekszik. @msg A crease ends inside a panel. Egy bigvonal egy panelen belül ér véget. @msg A crease does not divide two panels. Egy bigvonal nem választ el két panelt. -@msg A crease lies outside the cut outline. Egy bigvonal a vágási körvonalon kívül van. -@msg A crease that is not straight is folded along one straight line. Egy nem egyenes bigvonal egyetlen egyenes mentén hajlik. +@msg A crease lies outside the cut outline, wholly or in part. Egy bigvonal teljesen vagy részben a vágási körvonalon kívül van. +@msg The pieces of a hinge are not on one straight line. Egy zsanér részei nem egy egyenesen vannak. @msg A gap between cut lines is too narrow to tell apart. A vágóvonalak közötti rés túl keskeny a megkülönböztetéshez. -@msg A cut-out area holds other fold lines. Egy kivágott terület további hajtásvonalakat tartalmaz. +@msg A cut-out area holds other fold lines or another blank. Egy kivágott terület további hajtásvonalakat vagy egy másik kiterítéket tartalmaz. @msg A panel is not joined to the rest by a crease. Egy panelt egyetlen bigvonal sem köt a többihez. @msg A fold line is on a non-printing layer. Egy hajtásvonal nem nyomtatható rétegen van. -@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Panelek: {panels}, bigek: {hinges}, hibák: {errors}, figyelmeztetések: {warnings} +@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelek: {panels}, zsanérok: {hinges}, hibák: {errors}, figyelmeztetések: {warnings} diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index cd2ad82864..5e7d456bc2 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -7108,14 +7108,15 @@ breakText Glyphs Glif @msg A gap between cut lines was closed. Celah di antara garis potong telah ditutup. @msg The fold lines are too complex to check. Garis lipat terlalu rumit untuk diperiksa. @msg A cut line and a crease lie on top of each other. Sebuah garis potong dan sebuah garis lekuk bertumpuk. -@msg Two lines of the same role lie on top of each other. Dua garis dengan jenis yang sama bertumpuk. +@msg No cut lines are among the given objects. Tidak ada garis potong di antara objek yang diberikan. +@msg Two fold lines lie on top of each other. Dua garis lipat bertumpuk. @msg A crease ends inside a panel. Sebuah garis lekuk berakhir di dalam panel. @msg A crease does not divide two panels. Sebuah garis lekuk tidak membagi dua panel. -@msg A crease lies outside the cut outline. Sebuah garis lekuk berada di luar kontur potong. -@msg A crease that is not straight is folded along one straight line. Garis lekuk yang tidak lurus dilipat di sepanjang satu garis lurus. +@msg A crease lies outside the cut outline, wholly or in part. Sebuah garis lekuk berada seluruhnya atau sebagian di luar kontur potong. +@msg The pieces of a hinge are not on one straight line. Bagian-bagian sebuah engsel tidak berada pada satu garis lurus. @msg A gap between cut lines is too narrow to tell apart. Celah di antara garis potong terlalu sempit untuk dibedakan. -@msg A cut-out area holds other fold lines. Area yang dipotong berisi garis lipat lain. +@msg A cut-out area holds other fold lines or another blank. Area yang dipotong berisi garis lipat lain atau bentangan lain. @msg A panel is not joined to the rest by a crease. Sebuah panel tidak tersambung ke bagian lain oleh garis lekuk apa pun. @msg A fold line is on a non-printing layer. Sebuah garis lipat berada di lapisan yang tidak dicetak. -@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Panel: {panels}, lekuk: {hinges}, galat: {errors}, peringatan: {warnings} +@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panel: {panels}, engsel: {hinges}, galat: {errors}, peringatan: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer harus "singleLine", "everyLine", "standardSingleLine", atau "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index b34cf145a7..366a9f6940 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -9383,13 +9383,14 @@ breakText Glyphs Glifi @msg A gap between cut lines was closed. È stato chiuso uno spazio tra linee di taglio. @msg The fold lines are too complex to check. Le linee di piega sono troppo complesse da verificare. @msg A cut line and a crease lie on top of each other. Una linea di taglio e una di cordonatura sono sovrapposte. -@msg Two lines of the same role lie on top of each other. Due linee dello stesso tipo sono sovrapposte. +@msg No cut lines are among the given objects. Tra gli oggetti indicati non ci sono linee di taglio. +@msg Two fold lines lie on top of each other. Due linee di piega sono sovrapposte. @msg A crease ends inside a panel. Una linea di cordonatura termina all’interno di un pannello. @msg A crease does not divide two panels. Una linea di cordonatura non divide due pannelli. -@msg A crease lies outside the cut outline. Una linea di cordonatura si trova fuori dal contorno di taglio. -@msg A crease that is not straight is folded along one straight line. Una linea di cordonatura non diritta viene piegata lungo un’unica linea retta. +@msg A crease lies outside the cut outline, wholly or in part. Una linea di cordonatura si trova del tutto o in parte fuori dal contorno di taglio. +@msg The pieces of a hinge are not on one straight line. I tratti di una cerniera non sono su un’unica linea retta. @msg A gap between cut lines is too narrow to tell apart. Uno spazio tra linee di taglio è troppo stretto per essere distinto. -@msg A cut-out area holds other fold lines. Un’area ritagliata contiene altre linee di piega. +@msg A cut-out area holds other fold lines or another blank. Un’area ritagliata contiene altre linee di piega o un altro fustellato. @msg A panel is not joined to the rest by a crease. Un pannello non è unito al resto da alcuna linea di cordonatura. @msg A fold line is on a non-printing layer. Una linea di piega si trova su un livello non stampabile. -@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Pannelli: {panels}, cordonature: {hinges}, errori: {errors}, avvisi: {warnings} +@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Pannelli: {panels}, cerniere: {hinges}, errori: {errors}, avvisi: {warnings} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index a224dec9f0..70dc053e36 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -9450,13 +9450,14 @@ breakText Glyphs 字形 @msg A gap between cut lines was closed. カット線間の隙間を閉じました。 @msg The fold lines are too complex to check. 折り線が複雑すぎるためチェックできません。 @msg A cut line and a crease lie on top of each other. カット線と筋入れ線が重なっています。 -@msg Two lines of the same role lie on top of each other. 同じ種類の線が 2 本重なっています。 +@msg No cut lines are among the given objects. 指定したオブジェクトにカット線がありません。 +@msg Two fold lines lie on top of each other. 折り線が 2 本重なっています。 @msg A crease ends inside a panel. 筋入れ線がパネルの内側で終わっています。 @msg A crease does not divide two panels. 筋入れ線が 2 つのパネルを分けていません。 -@msg A crease lies outside the cut outline. 筋入れ線がカットの輪郭の外側にあります。 -@msg A crease that is not straight is folded along one straight line. まっすぐでない筋入れ線は 1 本の直線に沿って折られます。 +@msg A crease lies outside the cut outline, wholly or in part. 筋入れ線の全体または一部がカットの輪郭の外側にあります。 +@msg The pieces of a hinge are not on one straight line. ヒンジの各部分が 1 本の直線上にありません。 @msg A gap between cut lines is too narrow to tell apart. カット線間の隙間が狭すぎて区別できません。 -@msg A cut-out area holds other fold lines. 切り抜かれた領域に他の折り線があります。 +@msg A cut-out area holds other fold lines or another blank. 切り抜かれた領域に他の折り線または別の展開図があります。 @msg A panel is not joined to the rest by a crease. パネルがどの筋入れ線でも他とつながっていません。 @msg A fold line is on a non-printing layer. 折り線が印刷しないレイヤーにあります。 -@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} パネル: {panels}、筋入れ: {hinges}、エラー: {errors}、警告: {warnings} +@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} パネル: {panels}、ヒンジ: {hinges}、エラー: {errors}、警告: {warnings} diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 406a43c301..70016438d2 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -10019,14 +10019,15 @@ font-script Japanese იაპონური @msg A gap between cut lines was closed. ჭრის ხაზებს შორის ღრეჩო დაიხურა. @msg The fold lines are too complex to check. მოკეცვის ხაზები შესამოწმებლად ზედმეტად რთულია. @msg A cut line and a crease lie on top of each other. ჭრის ხაზი და ბიგის ხაზი ერთმანეთზე დევს. -@msg Two lines of the same role lie on top of each other. ერთი ტიპის ორი ხაზი ერთმანეთზე დევს. +@msg No cut lines are among the given objects. მითითებულ ობიექტებში ჭრის ხაზები არ არის. +@msg Two fold lines lie on top of each other. მოკეცვის ორი ხაზი ერთმანეთზე დევს. @msg A crease ends inside a panel. ბიგის ხაზი პანელის შიგნით მთავრდება. @msg A crease does not divide two panels. ბიგის ხაზი ორ პანელს არ ყოფს. -@msg A crease lies outside the cut outline. ბიგის ხაზი ჭრის კონტურის გარეთაა. -@msg A crease that is not straight is folded along one straight line. ბიგის ხაზი, რომელიც სწორი არ არის, ერთი სწორი ხაზის გასწვრივ იკეცება. +@msg A crease lies outside the cut outline, wholly or in part. ბიგის ხაზი მთლიანად ან ნაწილობრივ ჭრის კონტურის გარეთაა. +@msg The pieces of a hinge are not on one straight line. ანჯამის ნაწილები ერთ სწორ ხაზზე არ დევს. @msg A gap between cut lines is too narrow to tell apart. ჭრის ხაზებს შორის ღრეჩო ზედმეტად ვიწროა გასარჩევად. -@msg A cut-out area holds other fold lines. ამოჭრილი არე სხვა მოკეცვის ხაზებს შეიცავს. +@msg A cut-out area holds other fold lines or another blank. ამოჭრილი არე სხვა მოკეცვის ხაზებს ან სხვა ნამზადს შეიცავს. @msg A panel is not joined to the rest by a crease. პანელი დანარჩენს არცერთი ბიგის ხაზით არ უერთდება. @msg A fold line is on a non-printing layer. მოკეცვის ხაზი არასაბეჭდ შრეზეა. -@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} პანელები: {panels}, ბიგები: {hinges}, შეცდომები: {errors}, გაფრთხილებები: {warnings} +@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} პანელები: {panels}, ანჯამები: {hinges}, შეცდომები: {errors}, გაფრთხილებები: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer უნდა იყოს "singleLine", "everyLine", "standardSingleLine" ან "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 219bd8aa76..7b2822cb49 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -9346,13 +9346,14 @@ breakText Glyphs 글리프 @msg A gap between cut lines was closed. 재단선 사이의 틈을 닫았습니다. @msg The fold lines are too complex to check. 접는 선이 너무 복잡해서 검사할 수 없습니다. @msg A cut line and a crease lie on top of each other. 재단선과 오시선이 겹쳐 있습니다. -@msg Two lines of the same role lie on top of each other. 같은 종류의 선 두 개가 겹쳐 있습니다. +@msg No cut lines are among the given objects. 지정한 개체에 재단선이 없습니다. +@msg Two fold lines lie on top of each other. 접는 선 두 개가 겹쳐 있습니다. @msg A crease ends inside a panel. 오시선이 패널 안에서 끝납니다. @msg A crease does not divide two panels. 오시선이 두 패널을 나누지 않습니다. -@msg A crease lies outside the cut outline. 오시선이 재단 윤곽선 밖에 있습니다. -@msg A crease that is not straight is folded along one straight line. 곧지 않은 오시선은 하나의 직선을 따라 접힙니다. +@msg A crease lies outside the cut outline, wholly or in part. 오시선의 전체 또는 일부가 재단 윤곽선 밖에 있습니다. +@msg The pieces of a hinge are not on one straight line. 힌지의 조각들이 한 직선 위에 있지 않습니다. @msg A gap between cut lines is too narrow to tell apart. 재단선 사이의 틈이 너무 좁아 구별할 수 없습니다. -@msg A cut-out area holds other fold lines. 잘라 낸 영역에 다른 접는 선이 있습니다. +@msg A cut-out area holds other fold lines or another blank. 잘라 낸 영역에 다른 접는 선이나 다른 전개도가 있습니다. @msg A panel is not joined to the rest by a crease. 패널이 어떤 오시선으로도 나머지와 연결되어 있지 않습니다. @msg A fold line is on a non-printing layer. 접는 선이 인쇄되지 않는 레이어에 있습니다. -@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} 패널: {panels}, 오시: {hinges}, 오류: {errors}, 경고: {warnings} +@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 패널: {panels}, 힌지: {hinges}, 오류: {errors}, 경고: {warnings} diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 62c2566f13..4d8b5b3170 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -9784,13 +9784,14 @@ breakText Glyphs Glyphs @msg A gap between cut lines was closed. Een opening tussen snijlijnen is gesloten. @msg The fold lines are too complex to check. De vouwlijnen zijn te complex om te controleren. @msg A cut line and a crease lie on top of each other. Een snijlijn en een rillijn liggen over elkaar. -@msg Two lines of the same role lie on top of each other. Twee lijnen van dezelfde soort liggen over elkaar. +@msg No cut lines are among the given objects. De opgegeven objecten bevatten geen snijlijnen. +@msg Two fold lines lie on top of each other. Twee vouwlijnen liggen over elkaar. @msg A crease ends inside a panel. Een rillijn eindigt binnen een paneel. @msg A crease does not divide two panels. Een rillijn verdeelt geen twee panelen. -@msg A crease lies outside the cut outline. Een rillijn ligt buiten de snijcontour. -@msg A crease that is not straight is folded along one straight line. Een rillijn die niet recht is, wordt langs één rechte lijn gevouwen. +@msg A crease lies outside the cut outline, wholly or in part. Een rillijn ligt geheel of gedeeltelijk buiten de snijcontour. +@msg The pieces of a hinge are not on one straight line. De delen van een scharnier liggen niet op één rechte lijn. @msg A gap between cut lines is too narrow to tell apart. Een opening tussen snijlijnen is te smal om te onderscheiden. -@msg A cut-out area holds other fold lines. Een uitgesneden gebied bevat andere vouwlijnen. +@msg A cut-out area holds other fold lines or another blank. Een uitgesneden gebied bevat andere vouwlijnen of een andere uitslag. @msg A panel is not joined to the rest by a crease. Een paneel is door geen rillijn met de rest verbonden. @msg A fold line is on a non-printing layer. Een vouwlijn staat op een laag die niet wordt afgedrukt. -@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Panelen: {panels}, rillijnen: {hinges}, fouten: {errors}, waarschuwingen: {warnings} +@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelen: {panels}, scharnieren: {hinges}, fouten: {errors}, waarschuwingen: {warnings} diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 587884f787..22fd391c14 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -9604,13 +9604,14 @@ breakText Glyphs Glify @msg A gap between cut lines was closed. Zamknięto przerwę między liniami cięcia. @msg The fold lines are too complex to check. Linie zgięcia są zbyt złożone, aby je sprawdzić. @msg A cut line and a crease lie on top of each other. Linia cięcia i linia bigowania leżą na sobie. -@msg Two lines of the same role lie on top of each other. Dwie linie tego samego rodzaju leżą na sobie. +@msg No cut lines are among the given objects. Wśród podanych obiektów nie ma linii cięcia. +@msg Two fold lines lie on top of each other. Dwie linie zgięcia leżą na sobie. @msg A crease ends inside a panel. Linia bigowania kończy się wewnątrz panelu. @msg A crease does not divide two panels. Linia bigowania nie rozdziela dwóch paneli. -@msg A crease lies outside the cut outline. Linia bigowania leży poza konturem cięcia. -@msg A crease that is not straight is folded along one straight line. Linia bigowania, która nie jest prosta, jest zginana wzdłuż jednej linii prostej. +@msg A crease lies outside the cut outline, wholly or in part. Linia bigowania leży całkowicie lub częściowo poza konturem cięcia. +@msg The pieces of a hinge are not on one straight line. Części zawiasu nie leżą na jednej linii prostej. @msg A gap between cut lines is too narrow to tell apart. Przerwa między liniami cięcia jest zbyt wąska, aby ją rozróżnić. -@msg A cut-out area holds other fold lines. Wycięty obszar zawiera inne linie zgięcia. +@msg A cut-out area holds other fold lines or another blank. Wycięty obszar zawiera inne linie zgięcia lub inny wykrój. @msg A panel is not joined to the rest by a crease. Panel nie jest połączony z resztą żadną linią bigowania. @msg A fold line is on a non-printing layer. Linia zgięcia znajduje się na warstwie niedrukowanej. -@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Panele: {panels}, bigi: {hinges}, błędy: {errors}, ostrzeżenia: {warnings} +@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panele: {panels}, zawiasy: {hinges}, błędy: {errors}, ostrzeżenia: {warnings} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 4e1f704ec8..3802eda3d0 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -9822,13 +9822,14 @@ swatch Yellow Green Verde-amarelado @msg A gap between cut lines was closed. Uma lacuna entre linhas de corte foi fechada. @msg The fold lines are too complex to check. As linhas de dobra são complexas demais para verificar. @msg A cut line and a crease lie on top of each other. Uma linha de corte e uma de vinco estão sobrepostas. -@msg Two lines of the same role lie on top of each other. Duas linhas do mesmo tipo estão sobrepostas. +@msg No cut lines are among the given objects. Não há linhas de corte entre os objetos indicados. +@msg Two fold lines lie on top of each other. Duas linhas de dobra estão sobrepostas. @msg A crease ends inside a panel. Uma linha de vinco termina dentro de um painel. @msg A crease does not divide two panels. Uma linha de vinco não divide dois painéis. -@msg A crease lies outside the cut outline. Uma linha de vinco está fora do contorno de corte. -@msg A crease that is not straight is folded along one straight line. Uma linha de vinco que não é reta é dobrada ao longo de uma única linha reta. +@msg A crease lies outside the cut outline, wholly or in part. Uma linha de vinco está total ou parcialmente fora do contorno de corte. +@msg The pieces of a hinge are not on one straight line. As partes de uma dobradiça não estão em uma única linha reta. @msg A gap between cut lines is too narrow to tell apart. Uma lacuna entre linhas de corte é estreita demais para ser distinguida. -@msg A cut-out area holds other fold lines. Uma área recortada contém outras linhas de dobra. +@msg A cut-out area holds other fold lines or another blank. Uma área recortada contém outras linhas de dobra ou outra planificação. @msg A panel is not joined to the rest by a crease. Um painel não está unido ao restante por nenhuma linha de vinco. @msg A fold line is on a non-printing layer. Uma linha de dobra está em uma camada não imprimível. -@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Painéis: {panels}, vincos: {hinges}, erros: {errors}, avisos: {warnings} +@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Painéis: {panels}, dobradiças: {hinges}, erros: {errors}, avisos: {warnings} diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 2c6dec01d4..dae5c2fb75 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -9843,15 +9843,16 @@ shape Open Открытый @msg A gap between cut lines was closed. Зазор между линиями реза закрыт. @msg The fold lines are too complex to check. Линии сгиба слишком сложны для проверки. @msg A cut line and a crease lie on top of each other. Линия реза и линия биговки лежат друг на друге. -@msg Two lines of the same role lie on top of each other. Две линии одного типа лежат друг на друге. +@msg No cut lines are among the given objects. Среди указанных объектов нет линий реза. +@msg Two fold lines lie on top of each other. Две линии сгиба лежат друг на друге. @msg A crease ends inside a panel. Линия биговки заканчивается внутри панели. @msg A crease does not divide two panels. Линия биговки не разделяет две панели. -@msg A crease lies outside the cut outline. Линия биговки лежит за пределами контура реза. -@msg A crease that is not straight is folded along one straight line. Непрямая линия биговки сгибается по одной прямой. +@msg A crease lies outside the cut outline, wholly or in part. Линия биговки целиком или частично лежит за пределами контура реза. +@msg The pieces of a hinge are not on one straight line. Части шарнира не лежат на одной прямой. @msg A gap between cut lines is too narrow to tell apart. Зазор между линиями реза слишком узок, чтобы его различить. -@msg A cut-out area holds other fold lines. Вырезанная область содержит другие линии сгиба. +@msg A cut-out area holds other fold lines or another blank. Вырезанная область содержит другие линии сгиба или другую развёртку. @msg A panel is not joined to the rest by a crease. Панель не соединена с остальными ни одной линией биговки. @msg A fold line is on a non-printing layer. Линия сгиба находится на непечатаемом слое. -@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Панели: {panels}, биговки: {hinges}, ошибки: {errors}, предупреждения: {warnings} +@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панели: {panels}, шарниры: {hinges}, ошибки: {errors}, предупреждения: {warnings} @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} пикселей — слишком большой размер для PSD (не более {MAX_SIDE} пикселей по стороне): уменьшите разрешение @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer должен быть "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c0ac175345..dd66fc3bee 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -9434,14 +9434,15 @@ digits Hindi Hindi @msg A gap between cut lines was closed. Ett mellanrum mellan skärlinjer stängdes. @msg The fold lines are too complex to check. Falslinjerna är för komplexa för att kontrollera. @msg A cut line and a crease lie on top of each other. En skärlinje och en biglinje ligger ovanpå varandra. -@msg Two lines of the same role lie on top of each other. Två linjer av samma typ ligger ovanpå varandra. +@msg No cut lines are among the given objects. Det finns inga skärlinjer bland de angivna objekten. +@msg Two fold lines lie on top of each other. Två falslinjer ligger ovanpå varandra. @msg A crease ends inside a panel. En biglinje slutar inuti en panel. @msg A crease does not divide two panels. En biglinje delar inte två paneler. -@msg A crease lies outside the cut outline. En biglinje ligger utanför skärkonturen. -@msg A crease that is not straight is folded along one straight line. En biglinje som inte är rak falsas längs en rak linje. +@msg A crease lies outside the cut outline, wholly or in part. En biglinje ligger helt eller delvis utanför skärkonturen. +@msg The pieces of a hinge are not on one straight line. Delarna av ett gångjärn ligger inte på en rak linje. @msg A gap between cut lines is too narrow to tell apart. Ett mellanrum mellan skärlinjer är för smalt för att skilja ut. -@msg A cut-out area holds other fold lines. Ett utskuret område innehåller andra falslinjer. +@msg A cut-out area holds other fold lines or another blank. Ett utskuret område innehåller andra falslinjer eller ett annat ämne. @msg A panel is not joined to the rest by a crease. En panel är inte förbunden med resten av någon biglinje. @msg A fold line is on a non-printing layer. En falslinje ligger på ett lager som inte skrivs ut. -@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Paneler: {panels}, bigningar: {hinges}, fel: {errors}, varningar: {warnings} +@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneler: {panels}, gångjärn: {hinges}, fel: {errors}, varningar: {warnings} @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pixlar är för stort för PSD (högst {MAX_SIDE} pixlar per sida): sänk upplösningen diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 6dded8c1d7..72c2146903 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -9705,13 +9705,14 @@ breakText Glyphs Glifler @msg A gap between cut lines was closed. Kesim çizgileri arasındaki bir boşluk kapatıldı. @msg The fold lines are too complex to check. Katlama çizgileri denetlenemeyecek kadar karmaşık. @msg A cut line and a crease lie on top of each other. Bir kesim çizgisi ile bir pilyaj çizgisi üst üste. -@msg Two lines of the same role lie on top of each other. Aynı türden iki çizgi üst üste. +@msg No cut lines are among the given objects. Belirtilen nesneler arasında kesim çizgisi yok. +@msg Two fold lines lie on top of each other. İki katlama çizgisi üst üste. @msg A crease ends inside a panel. Bir pilyaj çizgisi bir panelin içinde bitiyor. @msg A crease does not divide two panels. Bir pilyaj çizgisi iki paneli ayırmıyor. -@msg A crease lies outside the cut outline. Bir pilyaj çizgisi kesim konturunun dışında. -@msg A crease that is not straight is folded along one straight line. Düz olmayan bir pilyaj çizgisi tek bir düz çizgi boyunca katlanır. +@msg A crease lies outside the cut outline, wholly or in part. Bir pilyaj çizgisi tamamen veya kısmen kesim konturunun dışında. +@msg The pieces of a hinge are not on one straight line. Bir menteşenin parçaları tek bir düz çizgi üzerinde değil. @msg A gap between cut lines is too narrow to tell apart. Kesim çizgileri arasındaki bir boşluk ayırt edilemeyecek kadar dar. -@msg A cut-out area holds other fold lines. Kesilip çıkarılmış bir alan başka katlama çizgileri içeriyor. +@msg A cut-out area holds other fold lines or another blank. Kesilip çıkarılmış bir alan başka katlama çizgileri veya başka bir açınım içeriyor. @msg A panel is not joined to the rest by a crease. Bir panel geri kalanlara hiçbir pilyaj çizgisiyle bağlı değil. @msg A fold line is on a non-printing layer. Bir katlama çizgisi yazdırılmayan bir katmanda. -@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Paneller: {panels}, pilyajlar: {hinges}, hatalar: {errors}, uyarılar: {warnings} +@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneller: {panels}, menteşeler: {hinges}, hatalar: {errors}, uyarılar: {warnings} diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 84eb22f968..912ae3ac65 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -9358,13 +9358,14 @@ breakText Glyphs Гліфи @msg A gap between cut lines was closed. Зазор між лініями різу закрито. @msg The fold lines are too complex to check. Лінії згину надто складні для перевірки. @msg A cut line and a crease lie on top of each other. Лінія різу та лінія біговки лежать одна на одній. -@msg Two lines of the same role lie on top of each other. Дві лінії одного типу лежать одна на одній. +@msg No cut lines are among the given objects. Серед указаних об’єктів немає ліній різу. +@msg Two fold lines lie on top of each other. Дві лінії згину лежать одна на одній. @msg A crease ends inside a panel. Лінія біговки закінчується всередині панелі. @msg A crease does not divide two panels. Лінія біговки не розділяє двох панелей. -@msg A crease lies outside the cut outline. Лінія біговки лежить поза контуром різу. -@msg A crease that is not straight is folded along one straight line. Непряма лінія біговки згинається вздовж однієї прямої. +@msg A crease lies outside the cut outline, wholly or in part. Лінія біговки повністю або частково лежить поза контуром різу. +@msg The pieces of a hinge are not on one straight line. Частини шарніра не лежать на одній прямій. @msg A gap between cut lines is too narrow to tell apart. Зазор між лініями різу надто вузький, щоб його розрізнити. -@msg A cut-out area holds other fold lines. Вирізана область містить інші лінії згину. +@msg A cut-out area holds other fold lines or another blank. Вирізана область містить інші лінії згину або іншу розгортку. @msg A panel is not joined to the rest by a crease. Панель не з’єднана з рештою жодною лінією біговки. @msg A fold line is on a non-printing layer. Лінія згину лежить на шарі, що не друкується. -@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Панелі: {panels}, біговки: {hinges}, помилки: {errors}, попередження: {warnings} +@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панелі: {panels}, шарніри: {hinges}, помилки: {errors}, попередження: {warnings} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 00ac3f7289..8edb621949 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7468,16 +7468,17 @@ breakText Glyphs Glyph @msg A gap between cut lines was closed. Đã đóng một khe hở giữa các đường cắt. @msg The fold lines are too complex to check. Các đường gấp quá phức tạp để kiểm tra. @msg A cut line and a crease lie on top of each other. Một đường cắt và một đường cấn nằm chồng lên nhau. -@msg Two lines of the same role lie on top of each other. Hai đường cùng loại nằm chồng lên nhau. +@msg No cut lines are among the given objects. Các đối tượng đã chỉ định không có đường cắt nào. +@msg Two fold lines lie on top of each other. Hai đường gấp nằm chồng lên nhau. @msg A crease ends inside a panel. Một đường cấn kết thúc bên trong một mặt. @msg A crease does not divide two panels. Một đường cấn không chia tách hai mặt. -@msg A crease lies outside the cut outline. Một đường cấn nằm ngoài đường viền cắt. -@msg A crease that is not straight is folded along one straight line. Đường cấn không thẳng được gấp theo một đường thẳng. +@msg A crease lies outside the cut outline, wholly or in part. Một đường cấn nằm hoàn toàn hoặc một phần ngoài đường viền cắt. +@msg The pieces of a hinge are not on one straight line. Các đoạn của một bản lề không nằm trên một đường thẳng. @msg A gap between cut lines is too narrow to tell apart. Khe hở giữa các đường cắt quá hẹp để phân biệt. -@msg A cut-out area holds other fold lines. Một vùng bị cắt bỏ chứa các đường gấp khác. +@msg A cut-out area holds other fold lines or another blank. Một vùng bị cắt bỏ chứa các đường gấp khác hoặc một khuôn trải khác. @msg A panel is not joined to the rest by a crease. Một mặt không được nối với phần còn lại bằng đường cấn nào. @msg A fold line is on a non-printing layer. Một đường gấp nằm trên lớp không in. -@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Mặt: {panels}, đường cấn: {hinges}, lỗi: {errors}, cảnh báo: {warnings} +@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Mặt: {panels}, bản lề: {hinges}, lỗi: {errors}, cảnh báo: {warnings} # Messages of the effects, 3D, image export, color profiles, swatch exchange files, color books and DXF import. @msg 3D effects require finite coordinates within 100 million points Hiệu ứng 3D yêu cầu tọa độ hữu hạn trong phạm vi 100 triệu điểm diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 40f821ffe4..c6b454a593 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -9589,14 +9589,15 @@ breakText Glyphs 字形 @msg A gap between cut lines was closed. 已闭合切割线之间的间隙。 @msg The fold lines are too complex to check. 折线过于复杂,无法检查。 @msg A cut line and a crease lie on top of each other. 一条切割线与一条压痕线重叠。 -@msg Two lines of the same role lie on top of each other. 两条同类线条重叠。 +@msg No cut lines are among the given objects. 指定的对象中没有切割线。 +@msg Two fold lines lie on top of each other. 两条折线重叠。 @msg A crease ends inside a panel. 一条压痕线在面板内部结束。 @msg A crease does not divide two panels. 一条压痕线没有分隔两个面板。 -@msg A crease lies outside the cut outline. 一条压痕线位于切割轮廓之外。 -@msg A crease that is not straight is folded along one straight line. 不直的压痕线沿一条直线折叠。 +@msg A crease lies outside the cut outline, wholly or in part. 一条压痕线全部或部分位于切割轮廓之外。 +@msg The pieces of a hinge are not on one straight line. 铰链的各段不在一条直线上。 @msg A gap between cut lines is too narrow to tell apart. 切割线之间的间隙太窄,无法区分。 -@msg A cut-out area holds other fold lines. 一个镂空区域包含其他折线。 +@msg A cut-out area holds other fold lines or another blank. 一个镂空区域包含其他折线或另一个展开图。 @msg A panel is not joined to the rest by a crease. 一个面板没有通过任何压痕线与其余部分相连。 @msg A fold line is on a non-printing layer. 一条折线位于不打印的图层上。 -@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} 面板:{panels},压痕:{hinges},错误:{errors},警告:{warnings} +@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 面板:{panels},铰链:{hinges},错误:{errors},警告:{warnings} @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} 像素对 PSD 而言过大 (每边最多 {MAX_SIDE} 像素):请降低分辨率 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 434723a718..576eea439e 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -9399,14 +9399,15 @@ breakText Glyphs 字符 @msg A gap between cut lines was closed. 已封閉切割線之間的間隙。 @msg The fold lines are too complex to check. 摺線過於複雜,無法檢查。 @msg A cut line and a crease lie on top of each other. 一條切割線與一條壓痕線重疊。 -@msg Two lines of the same role lie on top of each other. 兩條同類線條重疊。 +@msg No cut lines are among the given objects. 指定的物件中沒有切割線。 +@msg Two fold lines lie on top of each other. 兩條摺線重疊。 @msg A crease ends inside a panel. 一條壓痕線在面板內部結束。 @msg A crease does not divide two panels. 一條壓痕線沒有分隔兩個面板。 -@msg A crease lies outside the cut outline. 一條壓痕線位於切割輪廓之外。 -@msg A crease that is not straight is folded along one straight line. 不直的壓痕線沿一條直線摺疊。 +@msg A crease lies outside the cut outline, wholly or in part. 一條壓痕線全部或部分位於切割輪廓之外。 +@msg The pieces of a hinge are not on one straight line. 鉸鏈的各段不在一條直線上。 @msg A gap between cut lines is too narrow to tell apart. 切割線之間的間隙太窄,無法區分。 -@msg A cut-out area holds other fold lines. 一個鏤空區域包含其他摺線。 +@msg A cut-out area holds other fold lines or another blank. 一個鏤空區域包含其他摺線或另一個展開圖。 @msg A panel is not joined to the rest by a crease. 一個面板沒有透過任何壓痕線與其餘部分相連。 @msg A fold line is on a non-printing layer. 一條摺線位於不列印的圖層上。 -@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} 面板:{panels},壓痕:{hinges},錯誤:{errors},警告:{warnings} +@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 面板:{panels},鉸鏈:{hinges},錯誤:{errors},警告:{warnings} @msg {what} would print on more than {MAX_TILES} tiles: scale it down {what} 會列印在超過 {MAX_TILES} 個拼貼上:請縮小 diff --git a/docs/mcp.md b/docs/mcp.md index e552ec49b7..97e4907ea6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13087,8 +13087,8 @@ panel's menu opens it as Role Swatches…. `addon.packaging.check` (`{ids?, select?: false, tolerance?: 0.1}`) finds the blanks, panels and hinges that the fold lines make and lists what is wrong with them. It checks the fold lines among the objects (the selection by default), -through groups and clip groups, or every fold line of the document that is shown while nothing is selected and `ids` is -left out. `tolerance` is in points, from 0.01 to 10; a value outside that range, or one that is not a number or a length +through groups and clip groups, or every fold line of the document while nothing is selected and `ids` is left out. +Hidden lines are left out in every case, also inside a selected group. `tolerance` is in points, from 0.01 to 10; a value outside that range, or one that is not a number or a length such as `"2 mm"`, is an error. The command does not change the document and records no undo step. - Cut lines bound the material. Each connected piece of cut lines that encloses material is one blank. Its outline is its @@ -13105,17 +13105,17 @@ warnings. | Code | Reported when | |---|---| -| `noCut` | No cut line is among the objects. | +| `noCut` | No cut line is among the objects. The message names the selection, the objects `ids` gives, or the document. | | `open` | The cut lines enclose no area. | | `looseEnd` | An end of a cut line meets no other fold line within `tolerance`, and no gap is closed at it. `at` is the end. | | `gap` | An end of a cut line lies within `tolerance` of another cut line without touching it; the panels are built with the gap closed. `at` is the end. | | `tooComplex` | The lines have more than 65,536 segments, or a blank has more than 256 panels. | | `cutOverCrease` | A cut line and a crease, partial cut or perforation lie on top of each other. | -| `duplicate` | Two lines of the same role, or two subpaths of one line, lie on top of each other. | +| `duplicate` | Two cut lines, two crease, partial cut or perforation lines (of the same role or not), or two subpaths of one line, lie on top of each other. | | `danglingCrease` | A crease ends inside a panel. | | `noSplit` | A crease divides no two panels. | -| `outside` | A crease lies outside every blank. | -| `notStraight` | The pieces of a hinge are not on one straight line within `tolerance`; it folds along the line through its longest piece. | +| `outside` | A crease lies outside every blank, or runs outside it for `tolerance` or more. | +| `notStraight` | The pieces of a hinge are not on one straight line within `tolerance`. | | `sliver` | A gap between lines inside a blank is narrower than 0.01 pt. | | `ambiguous` | A hole holds creases, or a blank lies inside another blank's hole. | | `loosePanel` | A panel is joined to its blank's largest panel by no chain of hinges. | @@ -13125,7 +13125,7 @@ Result: `{ok, blanks, panels, hinges, holes, issues: [{severity, code, message, no issue is an error. `message` is in English, and the Fold Lines panel shows it in the interface language. `ids` names the objects each issue is about. With `select: true`, those objects become the selection; when no issue names an object, the selection stays as it is. The Fold Lines panel's Check button runs the same check, shows a summary line -(panels, creases, errors and warnings) and lists the issues; clicking an issue or its Select button selects its objects. +(panels, hinges, errors and warnings) and lists the issues; clicking an issue or its Select button selects its objects. The list is shown until the document changes. ```json From 4e8ff28cb4de26a1be893c4fcc54bbe8f008e70f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 04:36:43 -0800 Subject: [PATCH 14/31] .ai graphs: a filled-line series keeps no stroke, so turning Draw Filled Lines off draws its thin line A series read from bands with unstroked markers, or bands alone, kept an explicit no-stroke paint. With Draw Filled Lines turned off, the thin line took that paint and was not drawn. Such a series now keeps no stroke, as a graph drawn here does, and its thin line is drawn in the series color at 1 pt. A series whose markers carry a stroke keeps it. --- crates/engine/src/cmd/graph/tests.rs | 13 +++++++++++-- crates/eps/src/import/ai/read/graph.rs | 17 +++++++++++------ crates/eps/src/import/ai/tests.rs | 2 +- 3 files changed, 23 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 9624e8dbb7..b74dd97454 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -9538,11 +9538,20 @@ fn a_drawn_graph_with_filled_lines_saved_as_ai_opens_with_them() { let mut again = Session::new(); again.execute("document.open", &json!({"path": path})).unwrap(); let mut graphs = vec![]; - again.doc().unwrap().doc.walk(|n| graphs.extend(n.extras().graph.as_deref().cloned())); + again.doc().unwrap().doc.walk(|n| graphs.extend(n.extras().graph.as_deref().map(|g| (n.id, g.clone())))); assert_eq!(graphs.len(), usize::from(live), "{width:?} {name}"); - if let Some(g) = graphs.first() { + if let Some((gid, g)) = graphs.first() { assert_eq!((g.kind, g.cells(), g.filled_lines, g.line_width), (written.kind, written.cells(), true, width), "{width:?} {name}"); assert_eq!(g.filled_line_width(), written.filled_line_width(), "{width:?} {name}"); + // With Draw Filled Lines turned off, each series draws its thin 1 pt line again. + again.execute("select.set", &json!({"ids": [gid.0]})).unwrap(); + again.execute("graph.setType", &json!({"id": gid.0, "filledLines": false})).unwrap(); + for series in 0..2 { + let line = series_parts(&again, *gid, series) + .into_iter() + .any(|p| p.appearance.fill_paint().is_none() && !p.appearance.stroke_paint().is_none() && p.appearance.stroke_width() == 1.0); + assert!(line, "{width:?} {name}: series {series} draws no thin line"); + } } } } diff --git a/crates/eps/src/import/ai/read/graph.rs b/crates/eps/src/import/ai/read/graph.rs index 49d9ba7aa5..ea7fd2e673 100644 --- a/crates/eps/src/import/ai/read/graph.rs +++ b/crates/eps/src/import/ai/read/graph.rs @@ -487,7 +487,9 @@ fn as_drawn(n: &Node) -> bool { /// graph (`line`) has paths without a fill: its lines. With filled lines (`bands`), a filled path /// outlined as [`band_outline`] says is a band or a mark drawn like one and gives no stroke; any /// other filled path but a [`square`] marker or legend swatch is a band outlined otherwise. The -/// other paths give the series' stroke, and without them the series has none. `None` when they +/// other paths give the series' stroke, and without them the series has none. A series with a band +/// and no stroke on its other paths keeps no stroke at all, so with filled lines turned off its thin +/// line is drawn in the series color at 1 pt, as for a graph drawn here. `None` when they /// differ, a band has another outline, or the group, its own appearance or a path is drawn /// otherwise than [`as_drawn`]. fn series_paints(art: &Node, tags: &HashMap, line: bool, bands: bool) -> Option> { @@ -497,13 +499,14 @@ fn series_paints(art: &Node, tags: &HashMap, line: bool, bands: boo (as_drawn(group) && *group.appearance == Appearance::default()).then_some(())?; let paths: Vec<&Arc> = group.children().into_iter().flatten().collect(); (!paths.is_empty() && paths.iter().all(|p| matches!(p.kind, NodeKind::Path { .. }))).then_some(())?; - let (mut fills, mut strokes) = (vec![], vec![]); + let (mut fills, mut strokes, mut banded) = (vec![], vec![], false); for p in &paths { as_drawn(p).then_some(())?; let filled = shown(p, true).ok()?; let outline = shown(p, false).ok()?; if bands && filled.is_some() && band_outline(&outline) { // A band, or a mark outlined as one: the graph keeps no stroke for a series that draws bands. + banded = true; } else if bands && filled.is_some() && !square(p) { // A band outlined otherwise: the graph draws it again with the thin black outline only. return None; @@ -520,6 +523,7 @@ fn series_paints(art: &Node, tags: &HashMap, line: bool, bands: boo slot.fill = fill; (slot.stroke, slot.stroke_width) = match stroke { Some((paint, width)) => (Some(paint), Some(width)), + None if banded => (None, None), None => (Some(Paint::None), None), }; } @@ -699,7 +703,8 @@ mod tests { } /// With filled lines, a band's thin black outline is not the series' stroke: its markers' stroke - /// is, or none. A band outlined otherwise than its markers has no one stroke. + /// is, and with unstroked markers or none the series keeps no stroke. A band outlined otherwise + /// than its markers has no one stroke. #[test] fn a_filled_line_bands_outline_is_not_its_series_stroke() { let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); @@ -712,7 +717,7 @@ mod tests { let outlined = Appearance::basic(red.clone(), Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)), FILLED_LINE_OUTLINE_WIDTH); let marker = Appearance::basic(red.clone(), Paint::None, 0.0); let kept = series_paints(&series(outlined.clone(), marker.clone()), &tags, true, true).expect("a band and a marker"); - assert_eq!((kept[0].fill.as_ref(), kept[0].stroke.as_ref(), kept[0].stroke_width), (Some(&red), Some(&Paint::None), None)); + assert_eq!((kept[0].fill.as_ref(), kept[0].stroke.as_ref(), kept[0].stroke_width), (Some(&red), None, None)); let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0)); let stroked = Appearance::basic(red.clone(), blue.clone(), 2.0); let kept = series_paints(&series(outlined.clone(), stroked), &tags, true, true).expect("a band and a stroked marker"); @@ -725,7 +730,7 @@ mod tests { ))], ); let kept = series_paints(&bands_only, &tags, true, true).expect("a band alone"); - assert_eq!((kept[0].stroke.as_ref(), kept[0].stroke_width), (Some(&Paint::None), None), "a band alone"); + assert_eq!((kept[0].stroke.as_ref(), kept[0].stroke_width), (None, None), "a band alone"); // A band as long as it is wide is a square, and still a band: its outline is not the series' stroke. let square_band = |marker: Appearance| { let band = Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 3.0, 3.0)), outlined.clone())); @@ -733,7 +738,7 @@ mod tests { Node::group(NodeId(1), vec![Arc::new(Node::group(NodeId(2), vec![band, marker]))]) }; let kept = series_paints(&square_band(marker.clone()), &tags, true, true).expect("a square band and a marker"); - assert_eq!((kept[0].stroke.as_ref(), kept[0].stroke_width), (Some(&Paint::None), None), "a square band"); + assert_eq!((kept[0].stroke.as_ref(), kept[0].stroke_width), (None, None), "a square band"); assert!(series_paints(&series(outlined, marker.clone()), &tags, true, false).is_none(), "lines not filled"); let thick = Appearance::basic(red.clone(), Paint::solid(Color::BLACK), 1.0); assert!(series_paints(&series(thick, marker), &tags, true, true).is_none(), "a 1 pt outline"); diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 5fc5c97629..5ed9e90344 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -11408,7 +11408,7 @@ fn a_line_graph_drawn_with_filled_lines_keeps_them_and_their_width() { let (g, tagged) = live(band_graph("%_7 0 0 14 1 1 1 0 8 44 Gy\n")); assert_eq!((g.kind, g.filled_lines, g.line_width, tagged), (GraphKind::Line, true, Some(8.0), 2)); let fill = Some(Paint::solid(Color::cmyk(0.5, 0.0, 0.0, 0.0))); - assert!(g.series_paints.iter().all(|p| p.fill == fill && p.stroke == Some(Paint::None) && p.stroke_width.is_none()), "{:?}", g.series_paints); + assert!(g.series_paints.iter().all(|p| p.fill == fill && p.stroke.is_none() && p.stroke_width.is_none()), "{:?}", g.series_paints); assert_eq!(live(band_graph("%_7 0 0 14 1 1 1 0 3 44 Gy\n")).0.line_width, None, "3 pt"); assert_eq!(live(band_graph("%_7 0 0 14 1 1 1 0 6 44 Gy\n")).0.line_width, Some(6.0), "6 pt"); assert_eq!(live(band_graph("%_7 0 0 14 1 1 1 0 100 44 Gy\n")).0.line_width, Some(100.0), "100 pt"); From bf8c08e2a1f20aba0182985c08e37a6a21b5385d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 04:50:45 -0800 Subject: [PATCH 15/31] Recolor Artwork: the Edit tab's wheel can show brightness and hue A button under the Add Color and Remove Color tools switches both Edit tab wheels between hue with saturation and hue with brightness. On the brightness wheel a marker's distance from the center is its brightness (black at the center, full at the edge), a drag sets hue and brightness, the slider under the wheel edits saturation, and Add Color adds the hue and brightness clicked at the base color's saturation. The segmented wheel's five rings become brightness steps. Switching changes no color, the button is off for the color bars, and each opening shows hue and saturation. The dialog field is `wheelAxes` (`hueSaturation`, `hueBrightness`). --- crates/ui-egui/src/dialogs/recolor.rs | 83 +++++++++++--- crates/ui-egui/src/i18n/bg.tsv | 2 + crates/ui-egui/src/i18n/bs.tsv | 2 + crates/ui-egui/src/i18n/ca.tsv | 2 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/da.tsv | 2 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/el.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/fi.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/gu.tsv | 2 + crates/ui-egui/src/i18n/hi.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/id.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/ka.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/nl.tsv | 2 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt-br.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 2 + crates/ui-egui/src/i18n/sv.tsv | 2 + crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + crates/ui-egui/src/tests/recolor.rs | 156 +++++++++++++++++++++++++- crates/ui-egui/src/widgets.rs | 6 +- crates/ui-egui/src/widgets/color.rs | 137 ++++++++++++++++------ docs/control-protocol.md | 6 +- docs/target-app-parity.md | 1 + 34 files changed, 388 insertions(+), 57 deletions(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index e617c1710f..ae49d90a87 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -30,7 +30,11 @@ //! Remove Color tool removes the color whose marker is clicked; a bar's right-click menu has Remove //! Color too. The base color can't be removed. A removed color's row goes, unless it has current //! colors and art or a group is open: it then keeps them, with no new color, so that art keeps its -//! colors and the group's swatch at that place goes. With art, the Prominent Colors bar under the wheel shows the new +//! colors and the group's swatch at that place goes. Under the tools, a button switches both wheels +//! to hue and brightness (black at the center, full brightness at the edge, at the base color's +//! saturation; a marker drag sets hue and brightness, Add Color adds the hue and brightness clicked +//! at the base color's saturation, and the slider under the wheel is a Saturation slider) and back; +//! switching changes no color, and the dialog opens on hue and saturation. With art, the Prominent Colors bar under the wheel shows the new //! colors, each part as wide as its row's share of the art's uses, the largest first; dragging the //! edge between two parts moves width between them, and when the drag ends the rows' current //! colors move toward those widths (`recolor.weigh`), and the art previews them. The New Color @@ -60,7 +64,8 @@ //! (`{saturation, brightness, temperature, luminosity}` in percent, sent as `recolor.apply`'s //! `globalAdjust` in every slider mode), `display` (the Edit tab's `smooth`, `segmented` or `bars`; //! unset: `smooth`), `wheelTool` (`add`: the Add Color tool, `remove`: the Remove Color tool; -//! unset: neither, a click on the wheel selects a marker), `themePicker` (the Color Theme Picker is on), `themePicks` (its picks, as +//! unset: neither, a click on the wheel selects a marker), `wheelAxes` (`hueBrightness`: the wheels +//! show hue and brightness; `hueSaturation`, unset or any other value: hue and saturation), `themePicker` (the Color Theme Picker is on), `themePicks` (its picks, as //! `recolor.pickTheme`'s `picks`; a new list recolors the rows), `weights` (one per row, as //! `recolor.weigh`'s; a new list moves the rows' current colors toward them), `findColors` (Find is //! on; it shows the art so on the Assign tab, with art and rows selected). Changing `colors`, a @@ -1446,12 +1451,27 @@ const DRAG: &str = "__drag"; /// The field of the Edit tab's wheel tools: `add` (Add Color) or `remove` (Remove Color). const WHEEL_TOOL: &str = "wheelTool"; -/// The new color the Add Color tool gives a click at hue `h` (degrees) and saturation `s`: at the -/// brightness of `base` (the base color, whose brightness the wheel shows; full without one), the -/// segmented wheel's patch color with `segmented`, in `base`'s model. -fn added_color(base: Option, h: f32, s: f32, segmented: bool) -> Color { - let v = base.map_or(1.0, |b| b.to_hsb()[2]); - let c = if segmented { widgets::segment_color(h, s, v) } else { Color::from_hsb(h, s, v) }; +/// The field of what the Edit tab's wheels show: `hueBrightness` (hue and brightness), or anything +/// else (hue and saturation). +const WHEEL_AXES: &str = "wheelAxes"; + +/// What the Edit tab's wheels show, from [`WHEEL_AXES`]. +fn wheel_axes(d: &Dialog) -> widgets::WheelAxes { + if d.str(WHEEL_AXES) == "hueBrightness" { widgets::WheelAxes::HueBrightness } else { widgets::WheelAxes::HueSaturation } +} + +/// The new color the Add Color tool gives a click at hue `h` (degrees) and `t`, the saturation (or +/// with [`widgets::WheelAxes::HueBrightness`] the brightness) clicked: with the other component of +/// `base` (the base color, whose other component the wheel shows; full without one), the segmented +/// wheel's patch color with `segmented`, in `base`'s model. +fn added_color(base: Option, h: f32, t: f32, segmented: bool, axes: widgets::WheelAxes) -> Color { + let o = base.map_or(1.0, |b| b.to_hsb()[axes.other()]); + let c = if segmented { + widgets::segment_color_on(axes, h, t, o) + } else { + let [h, s, v] = axes.hsb(h, t, o); + Color::from_hsb(h, s, v) + }; base.map_or(c, |b| keep_model(b, c)) } @@ -1552,6 +1572,7 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut Vec w = widgets::segmented_wheel(ui, "recolor-wheel", WHEEL, &colors, marked), "bars" => changed |= color_bars(ui, d, rows, &active, base), - _ => w = widgets::harmony_wheel(ui, "recolor-wheel", WHEEL, &colors, marked), + _ => w = widgets::wheel_of(ui, "recolor-wheel", WHEEL, &colors, marked, display == "segmented", axes), }); }); // A click with a wheel tool adds a color there, or removes the color of the marker clicked. let clicked = w.clicked.filter(|_| on_wheel && matches!(tool.as_str(), "add" | "remove")); - if let Some((hit, [h, s])) = clicked { + if let Some((hit, [h, out])) = clicked { if tool == "add" { - let c = added_color(base.and_then(|b| to_color(&rows[b])), h, s, display == "segmented"); + let c = added_color(base.and_then(|b| to_color(&rows[b])), h, out, display == "segmented", axes); let i = add_color(rows, &c); d.fields.insert("__sel".into(), json!([i])); d.fields.remove(COMPS); @@ -1839,12 +1867,35 @@ mod tests { #[test] fn an_added_color_takes_the_base_colors_brightness_and_model() { let near = |a: [f32; 3], b: [f32; 3]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3); + let sat = widgets::WheelAxes::HueSaturation; let base = Color::from_hsb(10.0, 0.8, 0.6); - assert!(near(added_color(Some(base), 120.0, 0.5, false).to_hsb(), [120.0, 0.5, 0.6])); - assert!(near(added_color(None, 200.0, 0.25, false).to_hsb(), [200.0, 0.25, 1.0])); - assert!(near(added_color(None, 7.0, 0.95, true).to_hsb(), [0.0, 0.9, 1.0]), "the patch's color"); + assert!(near(added_color(Some(base), 120.0, 0.5, false, sat).to_hsb(), [120.0, 0.5, 0.6])); + assert!(near(added_color(None, 200.0, 0.25, false, sat).to_hsb(), [200.0, 0.25, 1.0])); + assert!(near(added_color(None, 7.0, 0.95, true, sat).to_hsb(), [0.0, 0.9, 1.0]), "the patch's color"); let cmyk = color_value(&json!("cmyk 0 100 100 0")).unwrap(); - assert!(matches!(added_color(Some(cmyk), 120.0, 0.5, false), Color::Cmyk { .. })); + assert!(matches!(added_color(Some(cmyk), 120.0, 0.5, false, sat), Color::Cmyk { .. })); + } + + /// On the hue and brightness wheel an added color is the hue and brightness clicked at the base + /// color's saturation (full without one), the patch's color on the segmented wheel (its ring is + /// a brightness step), in the base color's model. A black base adds a gray of the brightness + /// clicked, and the wheel's center is black. + #[test] + fn an_added_color_on_the_brightness_wheel_takes_the_base_colors_saturation() { + let near = |a: [f32; 3], b: [f32; 3]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3); + let bright = widgets::WheelAxes::HueBrightness; + let base = Color::from_hsb(10.0, 0.8, 0.6); + assert!(near(added_color(Some(base), 120.0, 0.5, false, bright).to_hsb(), [120.0, 0.8, 0.5])); + assert!(near(added_color(None, 200.0, 0.25, false, bright).to_hsb(), [200.0, 1.0, 0.25])); + assert!(near(added_color(Some(base), 7.0, 0.95, true, bright).to_hsb(), [0.0, 0.8, 0.9]), "the patch's color"); + assert!(near(added_color(Some(base), 7.0, 0.0, true, bright).to_hsb(), [0.0, 0.8, 0.1]), "the innermost ring"); + let black = Color::from_hsb(0.0, 0.0, 0.0); + let [_, s, v] = added_color(Some(black), 90.0, 0.4, false, bright).to_hsb(); + assert!(s.abs() < 1e-3 && (v - 0.4).abs() < 1e-3, "a gray: {s} {v}"); + let [_, _, v] = added_color(Some(base), 33.0, 0.0, false, bright).to_hsb(); + assert!(v.abs() < 1e-3, "black at the center"); + let cmyk = color_value(&json!("cmyk 0 100 100 0")).unwrap(); + assert!(matches!(added_color(Some(cmyk), 120.0, 0.5, false, bright), Color::Cmyk { .. })); } /// With a color group and art, a row without a new color removes its swatch in its place, the diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 71e443a399..d578b5015a 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1504,6 +1504,8 @@ font-technology Variable Променливи Show smooth color wheel Показване на плавно цветово колело Show segmented color wheel Показване на сегментирано цветово колело Show color bars Показване на цветни ленти + Show brightness and hue on wheel Показване на яркост и оттенък на колелото + Show saturation and hue on wheel Показване на насищане и оттенък на колелото Add Color Tool Инструмент „Добавяне на цвят“ Remove Color Tool Инструмент „Премахване на цвят“ Remove Color Премахване на цвят diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 883d6dd387..b0db56e1b6 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2927,6 +2927,8 @@ digits Malayalam Malajalam Show smooth color wheel Prikaži glatki kotač boja Show segmented color wheel Prikaži segmentirani kotač boja Show color bars Prikaži trake boja + Show brightness and hue on wheel Prikaži svjetlinu i nijansu na kotaču + Show saturation and hue on wheel Prikaži zasićenje i nijansu na kotaču Add Color Tool Alat za dodavanje boje Remove Color Tool Alat za uklanjanje boje Remove Color Ukloni boju diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a8a63cbf55..0321757241 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -2044,6 +2044,8 @@ digits Malayalam Malaiàlam Show smooth color wheel Mostra la roda de color contínua Show segmented color wheel Mostra la roda de color segmentada Show color bars Mostra les barres de color + Show brightness and hue on wheel Mostra la lluentor i el to a la roda + Show saturation and hue on wheel Mostra la saturació i el to a la roda Add Color Tool Eina Afegeix color Remove Color Tool Eina Elimina color Remove Color Elimina el color diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 569b1347ec..0378df7c53 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3012,6 +3012,8 @@ digits Malayalam Malajálamské Show smooth color wheel Zobrazit plynulé barevné kolo Show segmented color wheel Zobrazit segmentované barevné kolo Show color bars Zobrazit barevné pruhy + Show brightness and hue on wheel Zobrazit jas a odstín na kole + Show saturation and hue on wheel Zobrazit sytost a odstín na kole Add Color Tool Nástroj Přidat barvu Remove Color Tool Nástroj Odstranit barvu Remove Color Odstranit barvu diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 4578e4efc1..6e7ad5458f 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5460,6 +5460,8 @@ digits Malayalam Malayalam Show smooth color wheel Vis glat farvehjul Show segmented color wheel Vis segmenteret farvehjul Show color bars Vis farvebjælker + Show brightness and hue on wheel Vis lysstyrke og farvetone på hjulet + Show saturation and hue on wheel Vis mætning og farvetone på hjulet Add Color Tool Værktøjet Tilføj farve Remove Color Tool Værktøjet Fjern farve Remove Color Fjern farve diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c943c89dd2..a62d6e51ab 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1554,6 +1554,8 @@ file-filter Templates Vorlagen Show smooth color wheel Stufenlosen Farbkreis anzeigen Show segmented color wheel Segmentierten Farbkreis anzeigen Show color bars Farbbalken anzeigen + Show brightness and hue on wheel Helligkeit und Farbton im Farbkreis anzeigen + Show saturation and hue on wheel Sättigung und Farbton im Farbkreis anzeigen Add Color Tool Farbe-hinzufügen-Werkzeug Remove Color Tool Farbe-entfernen-Werkzeug Remove Color Farbe entfernen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 906640aa0a..a3060a3d1d 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1486,6 +1486,8 @@ font-technology Variable Μεταβλητές Show smooth color wheel Εμφάνιση ομαλού χρωματικού τροχού Show segmented color wheel Εμφάνιση τμηματοποιημένου χρωματικού τροχού Show color bars Εμφάνιση χρωματικών ράβδων + Show brightness and hue on wheel Εμφάνιση φωτεινότητας και απόχρωσης στον τροχό + Show saturation and hue on wheel Εμφάνιση κορεσμού και απόχρωσης στον τροχό Add Color Tool Εργαλείο προσθήκης χρώματος Remove Color Tool Εργαλείο αφαίρεσης χρώματος Remove Color Αφαίρεση χρώματος diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9239c93a73..7d59e871c7 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1569,6 +1569,8 @@ font-technology Variable Variables Show smooth color wheel Mostrar rueda de color continua Show segmented color wheel Mostrar rueda de color segmentada Show color bars Mostrar barras de color + Show brightness and hue on wheel Mostrar brillo y tono en la rueda + Show saturation and hue on wheel Mostrar saturación y tono en la rueda Add Color Tool Herramienta Añadir color Remove Color Tool Herramienta Eliminar color Remove Color Eliminar color diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 423703e5c1..e75154859c 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2956,6 +2956,8 @@ digits Malayalam Malajalam Show smooth color wheel Näytä liukuva väriympyrä Show segmented color wheel Näytä segmentoitu väriympyrä Show color bars Näytä väripalkit + Show brightness and hue on wheel Näytä kirkkaus ja sävy ympyrässä + Show saturation and hue on wheel Näytä kylläisyys ja sävy ympyrässä Add Color Tool Lisää väri -työkalu Remove Color Tool Poista väri -työkalu Remove Color Poista väri diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 1cff1c8ad0..52e05800f2 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1558,6 +1558,8 @@ font-technology Variable Variables Show smooth color wheel Afficher la roue chromatique continue Show segmented color wheel Afficher la roue chromatique segmentée Show color bars Afficher les barres de couleur + Show brightness and hue on wheel Afficher la luminosité et la teinte sur la roue + Show saturation and hue on wheel Afficher la saturation et la teinte sur la roue Add Color Tool Outil Ajouter une couleur Remove Color Tool Outil Supprimer une couleur Remove Color Supprimer la couleur diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 4eed343e3d..358c85c84a 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -3607,6 +3607,8 @@ Show all plates બધી પ્લેટ બતાવો Show axis અક્ષ બતાવો Show color bars રંગ બાર બતાવો + Show brightness and hue on wheel વ્હીલ પર તેજ અને હ્યૂ બતાવો + Show saturation and hue on wheel વ્હીલ પર સંતૃપ્તિ અને હ્યૂ બતાવો Add Color Tool રંગ ઉમેરો સાધન Remove Color Tool રંગ દૂર કરો સાધન Remove Color રંગ દૂર કરો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index de33cdbd92..2eac73fb49 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -4687,6 +4687,8 @@ antiAlias Sharp शार्प Show Center Mark शो सेंटर मार्क Show Code कोड दिखाएं Show color bars रंग सलाखों दिखाएँ + Show brightness and hue on wheel व्हील पर ब्राइटनेस और ह्यू दिखाएँ + Show saturation and hue on wheel व्हील पर सैचुरेशन और ह्यू दिखाएँ Add Color Tool रंग जोड़ें टूल Remove Color Tool रंग हटाएँ टूल Remove Color रंग हटाएँ diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index f869e7d07b..29cc03b42c 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1972,6 +1972,8 @@ file-filter Templates Sablonok Show smooth color wheel Folytonos színkör megjelenítése Show segmented color wheel Szegmentált színkör megjelenítése Show color bars Színsávok megjelenítése + Show brightness and hue on wheel Fényesség és színárnyalat megjelenítése a színkörön + Show saturation and hue on wheel Telítettség és színárnyalat megjelenítése a színkörön Add Color Tool Szín hozzáadása eszköz Remove Color Tool Szín eltávolítása eszköz Remove Color Szín eltávolítása diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c5f865e69b..751872fed7 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2737,6 +2737,8 @@ digits Malayalam Malayalam Show smooth color wheel Tampilkan roda warna halus Show segmented color wheel Tampilkan roda warna bersegmen Show color bars Tampilkan bilah warna + Show brightness and hue on wheel Tampilkan kecerahan dan rona pada roda + Show saturation and hue on wheel Tampilkan saturasi dan rona pada roda Add Color Tool Alat Tambah Warna Remove Color Tool Alat Hapus Warna Remove Color Hapus Warna diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 08cefdbed7..6b9f95466f 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1588,6 +1588,8 @@ file-filter Templates Modelli Show smooth color wheel Mostra ruota dei colori continua Show segmented color wheel Mostra ruota dei colori segmentata Show color bars Mostra barre di colore + Show brightness and hue on wheel Mostra luminosità e tonalità sulla ruota + Show saturation and hue on wheel Mostra saturazione e tonalità sulla ruota Add Color Tool Strumento Aggiungi colore Remove Color Tool Strumento Rimuovi colore Remove Color Rimuovi colore diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 59c7628f40..ddab274aa5 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1959,6 +1959,8 @@ antiAlias Sharp シャープ Show smooth color wheel 滑らかなカラーホイールを表示 Show segmented color wheel 分割カラーホイールを表示 Show color bars カラーバーを表示 + Show brightness and hue on wheel ホイールに明るさと色相を表示 + Show saturation and hue on wheel ホイールに彩度と色相を表示 Add Color Tool カラー追加ツール Remove Color Tool カラー削除ツール Remove Color カラーを削除 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 9393433cdb..fde3d6f292 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -4788,6 +4788,8 @@ digits Malayalam მალაიალამური Show smooth color wheel გლუვი ფერთა წრის ჩვენება Show segmented color wheel სეგმენტირებული ფერთა წრის ჩვენება Show color bars ფერთა ზოლების ჩვენება + Show brightness and hue on wheel სიკაშკაშისა და ფერის ტონის ჩვენება წრეზე + Show saturation and hue on wheel გაჯერებისა და ფერის ტონის ჩვენება წრეზე Add Color Tool ფერის დამატების ხელსაწყო Remove Color Tool ფერის წაშლის ხელსაწყო Remove Color ფერის წაშლა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 49d5e10dc1..cd27e23ecd 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1949,6 +1949,8 @@ antiAlias Sharp 날카롭게 Show smooth color wheel 부드러운 색상환 표시 Show segmented color wheel 분할 색상환 표시 Show color bars 색상 막대 표시 + Show brightness and hue on wheel 색상환에 밝기 및 색조 표시 + Show saturation and hue on wheel 색상환에 채도 및 색조 표시 Add Color Tool 색상 추가 도구 Remove Color Tool 색상 제거 도구 Remove Color 색상 제거 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index f071ebd0e2..58af2264ba 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3354,6 +3354,8 @@ digits Malayalam Malayalam Show smooth color wheel Vloeiend kleurenwiel tonen Show segmented color wheel Gesegmenteerd kleurenwiel tonen Show color bars Kleurbalken tonen + Show brightness and hue on wheel Helderheid en tint op het wiel tonen + Show saturation and hue on wheel Verzadiging en tint op het wiel tonen Add Color Tool Gereedschap Kleur toevoegen Remove Color Tool Gereedschap Kleur verwijderen Remove Color Kleur verwijderen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 2477c73abd..93f3dccc30 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2922,6 +2922,8 @@ digits Malayalam Malajalam Show smooth color wheel Pokaż płynne koło kolorów Show segmented color wheel Pokaż segmentowe koło kolorów Show color bars Pokaż paski kolorów + Show brightness and hue on wheel Pokaż jasność i barwę na kole + Show saturation and hue on wheel Pokaż nasycenie i barwę na kole Add Color Tool Narzędzie Dodaj kolor Remove Color Tool Narzędzie Usuń kolor Remove Color Usuń kolor diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 333351b9af..be033e13cc 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1354,6 +1354,8 @@ antiAlias Sharp Nítido Show smooth color wheel Mostrar roda de cores contínua Show segmented color wheel Mostrar roda de cores segmentada Show color bars Mostrar barras de cores + Show brightness and hue on wheel Mostrar brilho e tom na roda + Show saturation and hue on wheel Mostrar saturação e tom na roda Add Color Tool Ferramenta Adicionar cor Remove Color Tool Ferramenta Remover cor Remove Color Remover cor diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ae33aa0d55..dad34e78c0 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1579,6 +1579,8 @@ file-filter Templates Шаблоны Show smooth color wheel Показать плавный цветовой круг Show segmented color wheel Показать сегментированный цветовой круг Show color bars Показать цветовые полосы + Show brightness and hue on wheel Показать яркость и оттенок на круге + Show saturation and hue on wheel Показать насыщенность и оттенок на круге Add Color Tool Инструмент «Добавить цвет» Remove Color Tool Инструмент «Удалить цвет» Remove Color Удалить цвет diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1bd4fd0692..140c478265 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1522,6 +1522,8 @@ font-technology Variable Variabla Show smooth color wheel Visa steglöst färghjul Show segmented color wheel Visa segmenterat färghjul Show color bars Visa färgstaplar + Show brightness and hue on wheel Visa ljusstyrka och nyans på hjulet + Show saturation and hue on wheel Visa mättnad och nyans på hjulet Add Color Tool Verktyget Lägg till färg Remove Color Tool Verktyget Ta bort färg Remove Color Ta bort färg diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index a2a38c679a..3437945ffe 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1479,6 +1479,8 @@ font-technology Variable Değişken Show smooth color wheel Kesintisiz renk tekerleğini göster Show segmented color wheel Bölümlü renk tekerleğini göster Show color bars Renk çubuklarını göster + Show brightness and hue on wheel Tekerlekte parlaklık ve renk tonunu göster + Show saturation and hue on wheel Tekerlekte doygunluk ve renk tonunu göster Add Color Tool Renk Ekle aracı Remove Color Tool Renk Kaldır aracı Remove Color Rengi kaldır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 17c673885d..53d56eb1a8 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1582,6 +1582,8 @@ file-filter Templates Шаблони Show smooth color wheel Показати плавне колірне коло Show segmented color wheel Показати сегментоване колірне коло Show color bars Показати колірні смуги + Show brightness and hue on wheel Показати яскравість і відтінок на колі + Show saturation and hue on wheel Показати насиченість і відтінок на колі Add Color Tool Інструмент «Додати колір» Remove Color Tool Інструмент «Вилучити колір» Remove Color Вилучити колір diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index da89525314..a1434deff4 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1819,6 +1819,8 @@ file-filter Templates Mẫu Show smooth color wheel Hiện bánh xe màu liền mạch Show segmented color wheel Hiện bánh xe màu phân đoạn Show color bars Hiện các thanh màu + Show brightness and hue on wheel Hiện độ sáng và sắc độ trên bánh xe + Show saturation and hue on wheel Hiện độ bão hòa và sắc độ trên bánh xe Add Color Tool Công cụ Thêm màu Remove Color Tool Công cụ Xóa màu Remove Color Xóa màu diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5f612cb0d4..a57f43b4ef 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1516,6 +1516,8 @@ file-filter Templates 模板 Show smooth color wheel 显示平滑色轮 Show segmented color wheel 显示分段色轮 Show color bars 显示颜色条 + Show brightness and hue on wheel 在色轮上显示亮度和色相 + Show saturation and hue on wheel 在色轮上显示饱和度和色相 Add Color Tool 添加颜色工具 Remove Color Tool 删除颜色工具 Remove Color 删除颜色 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e0b5a13ee2..dad48cf74c 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1553,6 +1553,8 @@ file-filter Templates 範本 Show smooth color wheel 顯示平滑色輪 Show segmented color wheel 顯示分段色輪 Show color bars 顯示顏色條 + Show brightness and hue on wheel 在色輪上顯示亮度和色相 + Show saturation and hue on wheel 在色輪上顯示飽和度和色相 Add Color Tool 新增顏色工具 Remove Color Tool 移除顏色工具 Remove Color 移除顏色 diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index ec6921500b..db8d298940 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -1059,6 +1059,159 @@ fn a_segmented_wheel_marker_moves_freely() { assert!((new_hsb(h.state())[red][2] - 0.25).abs() < 0.02, "the Brightness slider: {:?}", new_hsb(h.state())); } +/// The segmented hue and brightness wheel's patches: 24 hues by 5 brightness steps, at the +/// saturation asked; the innermost ring is the darkest. +#[test] +fn the_segmented_brightness_wheel_has_24_hues_by_5_brightnesses() { + let bright = crate::widgets::WheelAxes::HueBrightness; + let seg = |h, v, s| crate::widgets::segment_color_on(bright, h, v, s).to_hsb(); + let near = |a: [f32; 3], b: [f32; 3]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3); + assert!(near(seg(7.0, 0.95, 1.0), [0.0, 1.0, 0.9]), "{:?}", seg(7.0, 0.95, 1.0)); + assert!(near(seg(8.0, 0.0, 0.5), [15.0, 0.5, 0.1]), "{:?}", seg(8.0, 0.0, 0.5)); + assert!(near(seg(120.0, 0.5, 0.25), [120.0, 0.25, 0.5]), "{:?}", seg(120.0, 0.5, 0.25)); + let mut patches = std::collections::BTreeSet::new(); + for h in 0..360 { + for v in 0..=100 { + patches.insert(ColorKey::of(&crate::widgets::segment_color_on(bright, h as f32, v as f32 / 100.0, 1.0)).to_string()); + } + } + assert_eq!(patches.len(), 24 * 5); +} + +/// The button under the wheel tools switches the wheel to hue and brightness: its name says what a +/// click shows next, the slider under the wheel becomes a Saturation slider, and switching changes +/// no color, previews nothing and records no undo step. The choice holds for the segmented wheel and +/// across the color bars, where the button is off; the next opening shows hue and saturation again. +#[test] +fn the_brightness_and_hue_wheel_swaps_the_wheel_axis_and_the_slider() { + let mut h = edit_harness(&["#ff0000", "#0000ff", "#00ff00"]); + let (rows, height) = (field(h.state(), "rows"), dialog_height(&h)); + let doc = h.state().session.doc().unwrap().doc.clone(); + let undo = h.state().session.doc().unwrap().history.undo.len(); + let slider = |h: &egui_kittest::Harness<'_, VectorcraftApp>, name: &str| h.query_by_role_and_label(egui::accesskit::Role::Slider, name).is_some(); + assert_eq!(field(h.state(), "wheelAxes"), Value::Null, "hue and saturation first"); + assert!(slider(&h, "Brightness") && !slider(&h, "Saturation")); + click_button(&mut h, "Show brightness and hue on wheel"); + assert_eq!(field(h.state(), "wheelAxes"), json!("hueBrightness")); + assert!(slider(&h, "Saturation") && !slider(&h, "Brightness"), "the slider edits the component the wheel leaves out"); + assert!(h.query_by_role_and_label(egui::accesskit::Role::Button, "Show saturation and hue on wheel").is_some(), "the button names the way back"); + assert_eq!(field(h.state(), "rows"), rows, "switching changes no color"); + assert_eq!(h.state().session.doc().unwrap().doc, doc, "nor the art"); + assert_eq!(h.state().session.doc().unwrap().history.undo.len(), undo); + show_display(&mut h, "Show segmented color wheel"); + assert_eq!(field(h.state(), "wheelAxes"), json!("hueBrightness"), "the segmented wheel keeps the choice"); + assert!(slider(&h, "Saturation")); + show_display(&mut h, "Show color bars"); + let button = h.get_by_role_and_label(egui::accesskit::Role::Button, "Show saturation and hue on wheel"); + assert!(button.accesskit_node().is_disabled(), "the button is for the wheels"); + assert_eq!(dialog_height(&h), height, "the button keeps the dialog's height"); + show_display(&mut h, "Show smooth color wheel"); + assert!(slider(&h, "Saturation"), "the bars keep the choice"); + click_button(&mut h, "Show saturation and hue on wheel"); + assert_eq!(field(h.state(), "wheelAxes"), json!("hueSaturation")); + assert!(slider(&h, "Brightness") && !slider(&h, "Saturation")); + assert_eq!(field(h.state(), "rows"), rows); + assert_eq!(dialog_height(&h), height); + set(h.state_mut(), "wheelAxes", json!("sideways")); + h.run_steps(3); + assert!(slider(&h, "Brightness"), "an unknown value shows hue and saturation"); + set(h.state_mut(), "wheelAxes", json!("hueBrightness")); + h.run_steps(3); + let app = h.state_mut(); + dialogs::cancel(app); + app.run("select.all", json!({})).unwrap(); + app.run("ui.recolorDialog", json!({})).unwrap(); + assert_eq!(field(app, "wheelAxes"), Value::Null, "a new opening shows hue and saturation"); +} + +/// On the hue and brightness wheel a marker sits at its color's brightness, and a drag sets hue and +/// brightness and keeps saturation; linked colors turn and darken with it. The art previews the +/// drag, Cancel restores it and OK keeps it as one undo step. The Saturation slider sets the +/// selected color's saturation and keeps its brightness. +#[test] +fn a_marker_on_the_brightness_wheel_sets_hue_and_brightness() { + for confirm in [false, true] { + let mut h = edit_harness(&["rgb 200 100 100", "rgb 100 200 200"]); + set(h.state_mut(), "__sel", json!([0])); + h.run_steps(4); + let before = h.state().session.doc().unwrap().doc.clone(); + let undo = h.state().session.doc().unwrap().history.undo.len(); + click_button(&mut h, "Show brightness and hue on wheel"); + let start = new_hsb(h.state()); + let [hue, s, v] = start[0]; + // Around by 30° and in to 40% brightness, a few points at a time from the marker. + let from = wheel_at(&h, hue, v); + h.hover_at(from); + h.run_steps(1); + h.drag_at(from); + h.run_steps(1); + let c = widget_of_size(&h, vec2(220.0, 220.0)).center(); + let to = |k: f32| { + let a = (hue + 30.0 * k).to_radians(); + c + vec2(a.cos(), -a.sin()) * 100.0 * (v + (0.4 - v) * k) + }; + let end = to(1.0); + for k in 1..=10 { + let p = to(k as f32 / 10.0); + h.hover_at(p); + h.run_steps(1); + } + h.drop_at(end); + h.run_steps(2); + let moved = new_hsb(h.state()); + let gap = |a: f32, b: f32| (a - b).rem_euclid(360.0).min((b - a).rem_euclid(360.0)); + assert!(gap(moved[0][0], hue + 30.0) < 1.0, "hue: {start:?} -> {moved:?}"); + assert!((moved[0][2] - 0.4).abs() < 0.02, "brightness: {start:?} -> {moved:?}"); + assert!((moved[0][1] - s).abs() < 0.02, "saturation stays: {start:?} -> {moved:?}"); + assert!(gap(moved[1][0], start[1][0] + 30.0) < 1.5, "linked, it turns: {start:?} -> {moved:?}"); + assert!((moved[1][2] - (start[1][2] - (v - 0.4))).abs() < 0.02, "and darkens alike: {start:?} -> {moved:?}"); + click_slider(&mut h, "Saturation", 0.25); + let slid = new_hsb(h.state()); + assert!((slid[0][1] - 0.25).abs() < 0.02, "the Saturation slider: {slid:?}"); + assert!((slid[0][2] - 0.4).abs() < 0.02, "keeps the brightness: {slid:?}"); + let after = h.state().session.doc().unwrap().doc.clone(); + assert_ne!(after, before, "the art previews the edit"); + h.get_by_label(if confirm { "OK" } else { "Cancel" }).click(); + h.run_steps(2); + assert!(h.state().ui.dialog.is_none()); + if confirm { + assert_eq!(h.state().session.doc().unwrap().doc, after); + assert_eq!(h.state().session.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + } else { + assert_eq!(h.state().session.doc().unwrap().history.undo.len(), undo, "Cancel records no undo step"); + } + assert_eq!(h.state().session.doc().unwrap().doc, before); + } +} + +/// On the hue and brightness wheels the Add Color tool adds the hue and brightness clicked at the +/// base color's saturation, the patch's color on the segmented wheel. +#[test] +fn the_add_color_tool_on_the_brightness_wheel_adds_the_brightness_clicked() { + let mut h = edit_harness(&["rgb 200 100 100", "rgb 100 200 200"]); + set(h.state_mut(), "__sel", json!([0])); + h.run_steps(4); + let s = new_hsb(h.state())[0][1]; + click_button(&mut h, "Show brightness and hue on wheel"); + click_button(&mut h, "Add Color Tool"); + let at = wheel_at(&h, 120.0, 0.5); + h.input_mut().events.extend(press(at, 1)); + h.run_steps(3); + let [hue, sat, b] = new_hsb(h.state())[2]; + assert!((hue - 120.0).abs() < 1.0 && (sat - s).abs() < 0.01 && (b - 0.5).abs() < 0.01, "{:?}", [hue, sat, b]); + assert_eq!(field(h.state(), "__sel"), json!([2])); + // The new color is now the base color; select the first one again. + set(h.state_mut(), "__sel", json!([0])); + h.run_steps(3); + show_display(&mut h, "Show segmented color wheel"); + let patch = wheel_at(&h, 187.0, 0.95); + h.input_mut().events.extend(press(patch, 1)); + h.run_steps(3); + let [hue, sat, b] = *new_hsb(h.state()).last().unwrap(); + assert!((hue - 180.0).abs() < 1.0 && (sat - s).abs() < 0.01 && (b - 0.9).abs() < 0.01, "the patch's color: {:?}", [hue, sat, b]); +} + /// The rows as `(current colors, new color)` pairs, sorted. fn row_pairs(app: &VectorcraftApp) -> Vec { let mut v: Vec = field(app, "rows").as_array().unwrap().iter().map(|r| format!("{} {}", r["from"], r["to"])).collect(); @@ -1173,7 +1326,8 @@ fn color_bars_scroll_and_show_when_nothing_is_recolored() { let _ = h.get_by_label("No colors to recolor (preserved colors are left out)."); } -/// Where the Edit tab's wheel draws a marker for hue `hue` and saturation `s`. +/// Where the Edit tab's wheel draws a marker for hue `hue` and saturation `s` (or brightness, on +/// the hue and brightness wheel). fn wheel_at(h: &egui_kittest::Harness<'_, VectorcraftApp>, hue: f32, s: f32) -> Pos2 { let c = widget_of_size(h, vec2(220.0, 220.0)).center(); c + vec2(hue.to_radians().cos(), -hue.to_radians().sin()) * 100.0 * s diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index d4d677a0a6..efc92e08e3 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -35,9 +35,9 @@ pub(crate) use buttons::{button_width, flat_button_fit_width, icon_button_info, use chips::gradient_chip_colors; pub use chips::{ProxyClicks, chip_button, chip_button_named, fill_stroke_proxy, gradient_chip, paint_chip, proxy_chip, swatch_tile}; pub use color::{ - FieldAxis, Live, RingResponse, SliderValue, WheelResponse, channel_slider, channel_slider_named, channel_slider_valued, color_field, color_mesh, - color_slider, color_slider_named, color_slider_stepped, color_slider_valued, harmony_wheel, hex_field, hex_field_named, hsb32, hue_ring, - region_texture, ring_square, segment_color, segmented_wheel, stepped_area, + FieldAxis, Live, RingResponse, SliderValue, WheelAxes, WheelResponse, channel_slider, channel_slider_named, channel_slider_valued, color_field, + color_mesh, color_slider, color_slider_named, color_slider_stepped, color_slider_valued, harmony_wheel, hex_field, hex_field_named, hsb32, + hue_ring, region_texture, ring_square, segment_color, segment_color_on, segmented_wheel, stepped_area, wheel_of, }; pub(crate) use color::{HEX_FIELD_CHARS, hex_text, pointer_phase}; pub use drag::{ diff --git a/crates/ui-egui/src/widgets/color.rs b/crates/ui-egui/src/widgets/color.rs index 04aae5be55..2c7711321d 100644 --- a/crates/ui-egui/src/widgets/color.rs +++ b/crates/ui-egui/src/widgets/color.rs @@ -700,17 +700,57 @@ fn wheel_pos(c: Pos2, r: f32, h: f32, s: f32) -> Pos2 { c + vec2(a.cos(), -a.sin()) * r * s } -/// The hue and saturation wheel at brightness `v`: hue around, saturation outwards. -fn wheel_shape(c: Pos2, r: f32, v: f32) -> egui::Shape { +/// Which HSB component the distance from a [`harmony_wheel`]'s center shows; hue is always the +/// angle. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum WheelAxes { + /// Saturation outwards (gray at the center), at the selected color's brightness. + #[default] + HueSaturation, + /// Brightness outwards (black at the center), at the selected color's saturation. + HueBrightness, +} + +impl WheelAxes { + /// The HSB index the distance from the center sets: 1 (saturation) or 2 (brightness). + pub fn radial(self) -> usize { + match self { + WheelAxes::HueSaturation => 1, + WheelAxes::HueBrightness => 2, + } + } + + /// The HSB index of the slider under the wheel: the component the wheel does not show. + pub fn other(self) -> usize { + 3 - self.radial() + } + + /// HSB `[h°, s, v]` of hue `h`, `t` for the component the distance from the center shows and + /// `o` for the other one. + pub fn hsb(self, h: f32, t: f32, o: f32) -> [f32; 3] { + match self { + WheelAxes::HueSaturation => [h, t, o], + WheelAxes::HueBrightness => [h, o, t], + } + } +} + +/// The wheel of `axes` with `o` for the component it does not show: hue around, the other +/// component outwards. +fn wheel_shape(c: Pos2, r: f32, axes: WheelAxes, o: f32) -> egui::Shape { const SEG: u32 = 72; const RINGS: u32 = 8; + let col = |h: f32, t: f32| { + let [h, s, v] = axes.hsb(h, t, o); + crate::panels::c32(&Color::from_hsb(h, s, v)) + }; let mut mesh = egui::Mesh::default(); - mesh.colored_vertex(c, crate::panels::c32(&Color::from_hsb(0.0, 0.0, v))); + mesh.colored_vertex(c, col(0.0, 0.0)); for ring in 1..=RINGS { - let s = ring as f32 / RINGS as f32; + let t = ring as f32 / RINGS as f32; for k in 0..SEG { let h = k as f32 * 360.0 / SEG as f32; - mesh.colored_vertex(wheel_pos(c, r, h, s), crate::panels::c32(&Color::from_hsb(h, s, v))); + mesh.colored_vertex(wheel_pos(c, r, h, t), col(h, t)); } } let at = |ring: u32, k: u32| if ring == 0 { 0 } else { 1 + (ring - 1) * SEG + k % SEG }; @@ -873,23 +913,31 @@ pub fn hue_ring(ui: &mut Ui, id: impl std::hash::Hash, name: &str, size: f32, hu out } -/// Hue sectors and saturation rings of the [`segmented_wheel`]: patches 15° of hue by 20% -/// saturation wide, the sectors centered on red at 0°. +/// Hue sectors and rings of the [`segmented_wheel`]: patches 15° of hue by 20% saturation (or +/// brightness) wide, the sectors centered on red at 0°. const WHEEL_SECTORS: u32 = 24; const WHEEL_RINGS: u32 = 5; /// The color of the [`segmented_wheel`] patch that holds hue `h` (degrees) and saturation `s` (0 to /// 1), at brightness `v`: the hue and saturation at the patch's center. pub fn segment_color(h: f32, s: f32, v: f32) -> Color { - let step = 360.0 / WHEEL_SECTORS as f32; - let sector = (h.rem_euclid(360.0) / step).round() % WHEEL_SECTORS as f32; - let ring = (s.clamp(0.0, 1.0) * WHEEL_RINGS as f32).floor().min((WHEEL_RINGS - 1) as f32); - Color::from_hsb(sector * step, (ring + 0.5) / WHEEL_RINGS as f32, v) + segment_color_on(WheelAxes::HueSaturation, h, s, v) } -/// The segmented hue and saturation wheel at brightness `v`: a solid patch per hue sector and -/// saturation ring, in its [`segment_color`]. -fn segmented_wheel_shape(c: Pos2, r: f32, v: f32) -> egui::Shape { +/// The color of the patch of the [`segmented_wheel`] of `axes` that holds hue `h` (degrees) and `t` +/// (0 to 1) for the component the wheel shows, with `o` for the other one: the hue and `t` at the +/// patch's center. +pub fn segment_color_on(axes: WheelAxes, h: f32, t: f32, o: f32) -> Color { + let step = 360.0 / WHEEL_SECTORS as f32; + let sector = (h.rem_euclid(360.0) / step).round() % WHEEL_SECTORS as f32; + let ring = (t.clamp(0.0, 1.0) * WHEEL_RINGS as f32).floor().min((WHEEL_RINGS - 1) as f32); + let [h, s, v] = axes.hsb(sector * step, (ring + 0.5) / WHEEL_RINGS as f32, o); + Color::from_hsb(h, s, v) +} + +/// The segmented wheel of `axes` with `o` for the component it does not show: a solid patch per +/// hue sector and ring, in its [`segment_color_on`]. +fn segmented_wheel_shape(c: Pos2, r: f32, axes: WheelAxes, o: f32) -> egui::Shape { // Points along each patch's arcs. const ARC: u32 = 4; let step = 360.0 / WHEEL_SECTORS as f32; @@ -898,7 +946,7 @@ fn segmented_wheel_shape(c: Pos2, r: f32, v: f32) -> egui::Shape { let (s0, s1) = (ring as f32 / WHEEL_RINGS as f32, (ring + 1) as f32 / WHEEL_RINGS as f32); for k in 0..WHEEL_SECTORS { let h = k as f32 * step; - let col = crate::panels::c32(&segment_color(h, (s0 + s1) / 2.0, v)); + let col = crate::panels::c32(&segment_color_on(axes, h, (s0 + s1) / 2.0, o)); let first = mesh.vertices.len() as u32; for j in 0..=ARC { let a = h - step / 2.0 + step * j as f32 / ARC as f32; @@ -920,11 +968,13 @@ fn segmented_wheel_shape(c: Pos2, r: f32, v: f32) -> egui::Shape { pub struct WheelResponse { /// The colour whose marker was pressed (it becomes the selected one). pub pressed: Option, - /// A colour moved by dragging its marker (a new hue and saturation) or, the selected colour, - /// the brightness slider (a new brightness): `[h°, s, v]`, `None` where the control kept it. + /// A colour moved by dragging its marker (a new hue and saturation, or with + /// [`WheelAxes::HueBrightness`] a new hue and brightness) or, the selected colour, the slider + /// under the wheel (a new brightness, or saturation): `[h°, s, v]`, `None` where the control + /// kept it. pub moved: Option<(usize, [Option; 3])>, /// A click on the wheel: the color whose marker is within reach of it (if any), and the hue - /// (degrees) and saturation under the pointer (1 for a marker past the wheel's edge). + /// (degrees) and the saturation (or brightness) under the pointer (1 past the wheel's edge). pub clicked: Option<(Option, [f32; 2])>, } @@ -933,32 +983,40 @@ pub struct WheelResponse { /// marker per colour joined to the centre (the selected colour, `base`, larger) and a Brightness /// slider for the selected colour below it. pub fn harmony_wheel(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: Option) -> WheelResponse { - wheel(ui, id, size, colors, base, false) + wheel_of(ui, id, size, colors, base, false, WheelAxes::HueSaturation) } /// [`harmony_wheel`] drawn as solid patches (24 hues by 5 saturations, each in its /// [`segment_color`]). The markers sit at their colors' own hue and /// saturation, and a drag moves them as freely as on the smooth wheel. pub fn segmented_wheel(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: Option) -> WheelResponse { - wheel(ui, id, size, colors, base, true) + wheel_of(ui, id, size, colors, base, true, WheelAxes::HueSaturation) } -/// [`harmony_wheel`], or with `segmented` [`segmented_wheel`]. -fn wheel(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: Option, segmented: bool) -> WheelResponse { +/// [`harmony_wheel`], or with `segmented` [`segmented_wheel`], showing `axes`. With +/// [`WheelAxes::HueBrightness`] the distance from the center is brightness (black at the center, +/// full brightness at the edge, a ring of patches per 20% on the segmented wheel), the wheel is drawn +/// at the selected colour's saturation (full without one), a marker drag sets hue and brightness, +/// and the slider under the wheel is a Saturation slider. +pub fn wheel_of(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: Option, segmented: bool, axes: WheelAxes) -> WheelResponse { let t = Tokens::get(ui.ctx()); let mut out = WheelResponse::default(); let base_hsb = base.and_then(|b| colors.get(b)).map(Color::to_hsb); - let v = base_hsb.map_or(1.0, |c| c[2]); + let (radial, other) = (axes.radial(), axes.other()); + // The component the wheel does not show: the slider's value, and the wheel's background at it. + let o = base_hsb.map_or(1.0, |c| c[other]); + // A dark wheel still shows its hues. + let shown = if axes == WheelAxes::HueSaturation { o.max(0.15) } else { o }; ui.horizontal(|ui| { ui.add_space(((ui.available_width() - size) / 2.0).max(0.0)); let (rect, resp) = ui.allocate_exact_size(vec2(size, size), Sense::click_and_drag()); let (c, r) = (rect.center(), size / 2.0 - 10.0); let painter = ui.painter_at(rect); - painter.add(if segmented { segmented_wheel_shape(c, r, v.max(0.15)) } else { wheel_shape(c, r, v.max(0.15)) }); + painter.add(if segmented { segmented_wheel_shape(c, r, axes, shown) } else { wheel_shape(c, r, axes, shown) }); painter.circle_stroke(c, r, Stroke::new(1.0, t.border)); let at = |col: &Color| { - let [h, s, _] = col.to_hsb(); - wheel_pos(c, r, h, s) + let hsb = col.to_hsb(); + wheel_pos(c, r, hsb[0], hsb[radial]) }; for (i, col) in colors.iter().enumerate() { let (p, big) = (at(col), Some(i) == base); @@ -974,7 +1032,8 @@ fn wheel(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: Option let near = colors.iter().map(at).enumerate().map(|(i, m)| (i, m.distance(p))).filter(|x| x.1 <= 14.0).min_by(|a, b| a.1.total_cmp(&b.1)); out.pressed = near.map(|x| x.0); ui.data_mut(|m| m.insert_temp(drag, out.pressed)); - // A click inside the wheel, or on a marker, gives the hue and saturation under it. + // A click inside the wheel, or on a marker, gives the hue and saturation (or + // brightness) under it. let dv = p - c; if resp.clicked() && (dv.length() <= r || out.pressed.is_some()) { let h = (-dv.y).atan2(dv.x).to_degrees().rem_euclid(360.0); @@ -986,8 +1045,10 @@ fn wheel(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: Option && i < colors.len() { let dv = p - c; - let h = (-dv.y).atan2(dv.x).to_degrees().rem_euclid(360.0); - out.moved = Some((i, [Some(h), Some((dv.length() / r).clamp(0.0, 1.0)), None])); + let mut set = [None; 3]; + set[0] = Some((-dv.y).atan2(dv.x).to_degrees().rem_euclid(360.0)); + set[radial] = Some((dv.length() / r).clamp(0.0, 1.0)); + out.moved = Some((i, set)); } let name = if segmented { tl!("Segmented color wheel") } else { tl!("Color wheel") }; resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Slider, ui.is_enabled(), name)); @@ -995,15 +1056,19 @@ fn wheel(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: Option ui.add_space(6.0); ui.horizontal(|ui| { ui.add_space(((ui.available_width() - size - 76.0) / 2.0).max(0.0)); - ui.add_sized([70.0, 22.0], egui::Label::new(egui::RichText::new(tl!("Brightness")).color(t.text_dim))); - // Screen readers get the brightness in percent, as the Color panel's HSB B field shows it. - let shown = SliderValue::field((f64::from(v) * 100.0).round(), 0.0..=100.0, "%", 0); - if let (Some(b), Some([h, s, _])) = (base, base_hsb) - && let (Some(nv), _) = color_slider_valued(ui, (id, "brightness"), tl!("Brightness"), Some(shown), v, size, &|x| { - crate::panels::c32(&Color::from_hsb(h, s, x)) + let (name, key) = if other == 2 { (tl!("Brightness"), "brightness") } else { (tl!("Saturation"), "saturation") }; + ui.add_sized([70.0, 22.0], egui::Label::new(egui::RichText::new(name).color(t.text_dim))); + // Screen readers get the value in percent, as the Color panel's HSB fields show it. + let shown = SliderValue::field((f64::from(o) * 100.0).round(), 0.0..=100.0, "%", 0); + if let (Some(b), Some(hsb)) = (base, base_hsb) + && let (Some(nv), _) = color_slider_valued(ui, (id, key), name, Some(shown), o, size, &|x| { + let [h, s, v] = axes.hsb(hsb[0], hsb[radial], x); + crate::panels::c32(&Color::from_hsb(h, s, v)) }) { - out.moved = Some((b, [None, None, Some(nv)])); + let mut set = [None; 3]; + set[other] = Some(nv); + out.moved = Some((b, set)); } }); out diff --git a/docs/control-protocol.md b/docs/control-protocol.md index df83c6eb04..275dbc569a 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -293,7 +293,11 @@ colors: `smooth` (the smooth wheel, also when unset; each opening starts there), selects its row for the sliders and a drag moves the row without changing a color). `wheelTool` turns on a wheel tool on either wheel: `add` (the Add Color tool) adds a click as a new color, the hue and saturation clicked at the base color's brightness (the patch's color on the segmented wheel), in a new row with no current colors (`from: []`) and -`added: true` that becomes the selected row; `remove` (the Remove Color tool) removes the color of the marker clicked. A color bar's +`added: true` that becomes the selected row; `remove` (the Remove Color tool) removes the color of the marker clicked. +`wheelAxes: "hueBrightness"` makes both wheels show hue and brightness: brightness runs from black at the center to +full at the edge, the wheel is drawn at the base color's saturation, a marker drag sets hue and brightness, the slider +under the wheel sets saturation, and Add Color adds the hue and brightness clicked at the base color's saturation. +`hueSaturation`, unset (each opening) or any other value shows hue and saturation; switching changes no color. A color bar's right-click menu has Remove Color too. The base color can't be removed. A removed color's row is dropped, unless it has current colors and art or a group is open: it then keeps them with `to: null`, that art keeps its colors, and the group's swatch at that place is removed. A row with no current colors recolors no art; with a group, the new color of diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..abe834ba80 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1675,6 +1675,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Recolor Artwork layout (#3416):** the Edit chip list uses the modal scroll helper and its actual remaining height; the tab's minimum-height space scrolls with the chips. `tests_recolor` covers 5/20/200/400 colors, window resizing, 100/125/150/200% UI scaling, scrolling to and editing the final chip, Preview, Cancel, Confirm and Undo, alongside the existing #1733 drag regressions. Scores and estimates unchanged. - **Recolor Artwork Edit displays:** buttons beside the Edit tab's wheel show the colors on a smooth color wheel, a segmented color wheel or as color bars ([Edit colors using Recolor Artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/edit-colors-using-edit-colors-dialog.html)). The segmented wheel draws 24 hues by 5 saturations as solid patches, and its markers move freely as on the smooth wheel. The bars show one solid bar per recolored color in row order: a click selects a bar for the color sliders, and a drag moves its row without changing a color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). The dialog opens on the smooth wheel; `display` (`smooth`, `segmented`, `bars`) is the dialog field. `tests_recolor` covers switching, the dialog height, segmented dragging and Brightness, and bar selection, editing, reordering, scrolling, Preview, Cancel and OK. Scores and estimates unchanged. - **Recolor Artwork Add Color and Remove Color tools:** under the display buttons beside the Edit tab's wheel, the Add Color tool adds the color clicked on either wheel to the color group, and the Remove Color tool removes the color whose marker is clicked; a color bar's right-click menu has Remove Color, and the base color can't be removed ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html), [Edit swatch groups using the color wheel](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/edit-color-groups-using-the-color-wheel.html)). An added color is a new row with no current colors and `added: true`; unlike a row made with New Row, it adds its new color to a rewritten color group, after the group's other colors. VectorCraft's own rules: an added color takes the base color's brightness, and with art or a group a removed color's row stays with its current colors and no new color, so that art keeps its colors and the group's swatch at that place is removed. `wheelTool` (`add`, `remove`) is the dialog field. Tests: `the_add_color_tool_adds_a_row_with_no_current_colors`, `an_added_color_joins_the_color_group`, `the_remove_color_tool_removes_a_marker_but_not_the_base_colors` and `a_color_bars_menu_removes_its_color` in `crates/ui-egui/src/tests/recolor.rs`, `apply_params_give_the_group_added_colors_and_keep_its_other_colors` in `crates/ui-egui/src/dialogs/recolor.rs`, and `an_added_empty_row_gives_the_group_its_color_after_the_others` in `crates/engine/src/tests/recolor.rs`. Scores and estimates unchanged. + - **Recolor Artwork brightness and hue wheel:** a button under the Edit tab's wheel tools switches the wheel between hue with saturation and hue with brightness; a marker's angle sets its hue, and its distance from the center sets the component the wheel shows ([Recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/recolor-options-overview.html), [archived help, Edit colors](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=144)). VectorCraft's own rules: brightness runs from black at the center to full at the edge, the segmented wheel's five rings become brightness steps, the slider under the wheel edits the component the wheel leaves out (Saturation on the brightness wheel), Add Color takes the hue and brightness clicked at the base color's saturation, the choice holds for both wheels while the dialog is open and the button is off for the color bars, and each opening shows hue and saturation. `wheelAxes` (`hueSaturation`, `hueBrightness`) is the dialog field. Tests: `the_brightness_and_hue_wheel_swaps_the_wheel_axis_and_the_slider`, `a_marker_on_the_brightness_wheel_sets_hue_and_brightness`, `the_add_color_tool_on_the_brightness_wheel_adds_the_brightness_clicked` and `the_segmented_brightness_wheel_has_24_hues_by_5_brightnesses` in `crates/ui-egui/src/tests/recolor.rs`, and `an_added_color_on_the_brightness_wheel_takes_the_base_colors_saturation` in `crates/ui-egui/src/dialogs/recolor.rs`. Scores and estimates unchanged. - **Recolor Artwork Find:** the Assign tab's Find button finds the colors of the selected rows in the art ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)): while it is on, their art shows as the preview shows it and the rest of the selected art shows dimmed, until a second click ([archived help, Recolor Artwork](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=149)). VectorCraft's own rules: a dimmed color is a 25% tint of its current color (or the nearest lighter tint when that one is a color a selected row lists), a color a selected row also lists is not dimmed, and Find records no undo step. `findColors` is the dialog field. Tests: `find_dims_the_colors_of_the_rows_not_selected` and `find_shows_the_selected_rows_art_and_dims_the_rest` in `crates/ui-egui/src/dialogs/recolor.rs`. Scores and estimates unchanged. - **Recolor Artwork New Row:** the Assign tab's New Row button adds a row with no current colors, so current colors can be moved into it and take its new color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html), [Assign new colors to selected artworks](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html)). VectorCraft's own rules: the row goes above the first selected row (at the top when none is selected) with that row's new color and becomes the selection, and Merge with it as the first selected row moves the other rows' colors into it. The button needs selected art. An empty row recolors nothing, does not count toward Colors, adds no library swatch and gives a rewritten color group no color. While it is empty, Save All Colors and a new color group saved from colors alone leave its new color out, the Edit tab's wheel, bars and chips do not show it and its sliders edit the base color instead, the harmony rules and linked moves leave its new color as it is, and the Color Theme Picker gives it no color. Tests: `a_new_row_goes_above_the_selection_and_takes_merged_colors`, `an_empty_row_gives_the_group_no_color`, `an_empty_row_gives_a_new_group_no_color`, `an_empty_row_takes_no_harmony_or_wheel_color`, `theme_picks_leave_an_empty_row_out`, `save_all_colors_leaves_an_empty_row_out` and `colors_merged_into_a_new_row_take_its_new_color` in `crates/ui-egui/src/dialogs/recolor.rs`, `an_empty_row_recolors_nothing` and `an_empty_row_adds_no_swatch_and_no_group_color` in `crates/engine/src/tests/recolor.rs`. - **Edit Colors parameters:** `edit.colors.saturate` needs a number `intensity`, the value from -100% to 100% that Saturate takes ([Adjusting colors](https://web.archive.org/web/20230128232631/https://helpx.adobe.com/illustrator/using/adjusting-colors.html)), and answers "missing number `intensity`" without one; a number outside the range counts as its nearest end. A value that is not a number, such as `"40"`, is refused with `` `intensity` must be a number, not "40" ``, as in every command that needs a number (`tests::params::a_malformed_required_number_is_not_reported_as_missing`). `edit.colors.adjustBalance` refuses a channel and `color.harmony` refuses `steps` or `amount` that is not a number; both read `null` as a value left out. `tests::editcolors` and `tests::colorguide` cover them. From 64dfd6ca1474d48278c3ce44e2d7691a3a188e5e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 04:50:48 -0800 Subject: [PATCH 16/31] Repeat: dragging a Radial Repeat's splitter hides instances and the others keep their places With one radial repeat selected, the Selection tool shows a splitter on its circle, half a step past the last instance shown. Dragging it back around the circle hides the instances it passes, and dragging it forward shows them again; one instance stays shown at least. The instances left keep their places: the repeat keeps the count shown in instances and spaces them a full circle's step apart with endAngle, and the full circle's count is read back from that step. Each drag previews and commits object.repeat.options as one undo step, Escape cancels it, and a drag that ends where it began leaves no undo step. There is no splitter when the step does not divide a full turn, for one instance to a turn or with a radius of 0. The radius handle of a single instance sits opposite it. --- crates/tools/src/repeat_radial.rs | 286 +++++++++++++++++++-- crates/ui-egui/src/canvas/tests.rs | 87 +++++++ crates/ui-egui/src/canvas/tool_overlays.rs | 14 +- docs/gaps.md | 2 +- docs/target-app-parity.md | 1 + docs/ui-parity.md | 2 +- 6 files changed, 367 insertions(+), 25 deletions(-) diff --git a/crates/tools/src/repeat_radial.rs b/crates/tools/src/repeat_radial.rs index 05eafc8d1b..42a9f4395f 100644 --- a/crates/tools/src/repeat_radial.rs +++ b/crates/tools/src/repeat_radial.rs @@ -1,8 +1,14 @@ -//! Radial Repeat's on-canvas handles: a handle below the repeat adds or removes instances, and a -//! handle on the circle the instances sit on sets its radius, as the public "Create radial -//! repeats" page describes. Drawing and hit testing share the document-space geometry of +//! Radial Repeat's on-canvas handles: a handle below the repeat adds or removes instances, a +//! handle on the circle the instances sit on sets its radius, and a splitter on the circle hides +//! instances at the end of the ring while the others keep their places, as the public "Create +//! radial repeats" page describes. Drawing and hit testing share the document-space geometry of //! [`RadialHandles::of`]; a drag previews the existing Repeat Options command and commits as one //! undo step. +//! +//! A split ring is kept in the repeat's existing options: `instances` counts the instances shown, +//! and `endAngle` places them a full ring's step apart from `startAngle` (one step past it for a +//! single instance). The full ring's slot count is read back from that step, so dragging the +//! splitter forward shows the hidden instances again. use serde_json::{Value, json}; use vectorcraft_doc::{Document, NodeId, NodeKind, OrientedBox, RepeatKind, Selection}; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; @@ -10,7 +16,7 @@ use vectorcraft_geom::{Affine, Point, Rect, Vec2}; use crate::bbox::Handle; use crate::{Action, Cursor, Mods, ToolContext}; -/// The radius of the instances and radius handles (screen points). +/// The radius of the instances, radius and splitter handles (screen points). pub const HANDLE_RADIUS: f32 = 5.0; /// How far (screen points) the instances handle sits below the bounding box, clear of its own @@ -34,6 +40,61 @@ pub enum RadialPart { /// On the circle, between the first two instances: drag outward for a larger radius, inward /// for a smaller one. Radius, + /// On the circle, half a step past the last instance shown: drag it back around the circle to + /// hide the instances it passes, forward to show them again. + Splitter, +} + +/// The full ring a radial repeat's instances sit on. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Ring { + /// The instances a full turn holds at the repeat's step. + slots: u32, + /// Degrees from one instance to the next (negative when the instances run the other way). + step: f64, +} + +impl Ring { + /// The ring of `instances` laid out from `start` to `end` degrees, when their step fits a + /// whole number of times (2 to 1,000, and no fewer than the instances) in a full turn. + fn of(instances: u32, start: f64, end: f64) -> Option { + let step = instance_step(instances, end - start); + let slots = 360.0 / step.abs(); + let whole = slots.round(); + ((slots - whole).abs() < 1e-6 && (2.0..=MAX_INSTANCES).contains(&whole) && whole >= f64::from(instances)) + .then(|| Self { slots: whole as u32, step: (360.0 / whole).copysign(step) }) + } + + /// The Repeat Options that show the first `shown` instances of the ring (1 to all of them), + /// laid out from `start` degrees. + fn options(&self, shown: u32, start: f64) -> Value { + let shown = shown.clamp(1, self.slots.max(1)); + let sweep = if shown == self.slots { 360.0_f64.copysign(self.step) } else { self.step * f64::from(shown.saturating_sub(1).max(1)) }; + json!({ "instances": shown, "endAngle": start + sweep }) + } + + /// The instances shown with the splitter `turn` degrees around the ring from the first + /// instance: those it has passed, one at least and the full ring at most. + fn shown(&self, turn: f64) -> u32 { + let k = (turn / self.step.abs()).floor() + 1.0; + if k.is_nan() { 1 } else { k.clamp(1.0, f64::from(self.slots)) as u32 } + } +} + +/// Degrees between neighboring instances, as `repeat_transforms` spaces `instances` over `sweep`. +fn instance_step(instances: u32, sweep: f64) -> f64 { + let full = (sweep.abs() - 360.0).abs() < 1e-9; + if full || instances <= 1 { sweep / f64::from(instances.max(1)) } else { sweep / f64::from(instances - 1) } +} + +/// `v` turned by `deg` degrees as `repeat_transforms` turns the instances. +fn turned(v: Vec2, deg: f64) -> Vec2 { + (Affine::rotate(deg.to_radians()) * v.to_point()).to_vec2() +} + +/// The direction of `v` in counter-clockwise screen degrees. +fn screen_angle(v: Vec2) -> f64 { + (-v.y).atan2(v.x).to_degrees() } /// The controls of a selected radial repeat, in document space. @@ -48,8 +109,13 @@ pub struct RadialHandles { out: Vec2, /// Document points of drag for each instance. step: f64, + start_angle: f64, + ring: Option, pub instances_at: Point, pub radius_at: Point, + /// Where the splitter is: none when the instances' step does not divide a full turn, for a + /// single instance to a turn, or with a radius of 0. + pub splitter_at: Option, } impl RadialHandles { @@ -78,12 +144,14 @@ impl RadialHandles { if d.hypot() < 1e-9 { d = Vec2::new(0.0, -1.0); } - let sweep = end_angle - start_angle; - let full = (sweep.abs() - 360.0).abs() < 1e-9; - let step = if full || instances == 1 { sweep / f64::from(instances) } else { sweep / f64::from(instances - 1) }; - // Halfway between the first two instances (opposite the only one of a full turn). - let out = (Affine::rotate((start_angle + step / 2.0).to_radians()) * d.normalize().to_point()).to_vec2(); + let first = turned(d.normalize(), start_angle); + let step = instance_step(instances, end_angle - start_angle); + // Halfway between the first two instances; opposite a single one. + let out = turned(first, if instances == 1 { 180.0 } else { step / 2.0 }); let radius = radius.max(0.0); + let ring = Ring::of(instances, start_angle, end_angle); + // Half a step past the last instance shown. + let splitter_at = ring.filter(|_| radius > 0.0).map(|r| center + turned(first, r.step * (f64::from(instances) - 0.5)) * radius); let frame = match frame { Some(f) => aabb(f.corners())?, None => n.geometric_bounds_with(&doc.symbol_boxes())?, @@ -95,15 +163,20 @@ impl RadialHandles { radius, out, step: INSTANCE_STEP / zoom, + start_angle, + ring, instances_at: Point::new(frame.center().x, frame.y1 + HANDLE_GAP / zoom), radius_at: center + out * radius, + splitter_at: splitter_at.filter(|p| finite(*p)), }; (finite(h.instances_at) && finite(h.radius_at) && h.step.is_finite() && h.step > 0.0).then_some(h) } - /// Both controls with where they are. - pub fn parts(&self) -> [(RadialPart, Point); 2] { - [(RadialPart::Instances, self.instances_at), (RadialPart::Radius, self.radius_at)] + /// The controls with where they are. + pub fn parts(&self) -> Vec<(RadialPart, Point)> { + let mut parts = vec![(RadialPart::Instances, self.instances_at), (RadialPart::Radius, self.radius_at)]; + parts.extend(self.splitter_at.map(|at| (RadialPart::Splitter, at))); + parts } /// The control under `p` (the nearer within reach) and the repeat's controls, unless a @@ -120,7 +193,8 @@ impl RadialHandles { } /// The Repeat Options that dragging `part` by `d` (document points) from the press gives; - /// none when the drag is too far to measure. + /// none when the drag is too far to measure. The splitter's options are those it shows at the + /// press. fn options(&self, part: RadialPart, d: Vec2) -> Option { match part { RadialPart::Instances => { @@ -133,12 +207,31 @@ impl RadialHandles { let r = ((self.radius + d.dot(self.out)).max(0.0) * 100.0).round() / 100.0; r.is_finite().then(|| json!({ "radius": r })) } + RadialPart::Splitter => self.ring.map(|r| r.options(self.instances, self.start_angle)), } } + /// Degrees around the ring from the first instance to the splitter, in the direction the + /// instances run. + fn splitter_turn(&self) -> f64 { + self.ring.map_or(0.0, |r| (f64::from(self.instances) - 0.5) * r.step.abs()) + } + + /// The direction of `p` from the center in degrees, as the instances are turned; none at the + /// center. + fn bearing(&self, p: Point) -> Option { + let v = p - self.center; + (finite(p) && v.hypot() > 1e-9).then(|| v.y.atan2(v.x).to_degrees()) + } + /// The direction (counter-clockwise degrees) in which the radius handle moves the circle out. fn out_angle(&self) -> f64 { - (-self.out.y).atan2(self.out.x).to_degrees() + screen_angle(self.out) + } + + /// The direction (counter-clockwise degrees) along the circle at the splitter. + fn splitter_angle(&self) -> f64 { + self.splitter_at.map_or(0.0, |at| screen_angle(at - self.center) + 90.0) } } @@ -153,11 +246,12 @@ fn finite(p: Point) -> bool { } /// The resize cursor of `part`, turned with the view: up and down for the instances handle, along -/// the line from the center for the radius handle. +/// the line from the center for the radius handle, and along the circle for the splitter. fn part_cursor(cx: &ToolContext, h: &RadialHandles, part: RadialPart) -> Cursor { match part { RadialPart::Instances => crate::select::handle_cursor(Handle::Bottom, -cx.view_angle()), RadialPart::Radius => crate::select::handle_cursor(Handle::Right, h.out_angle() - cx.view_angle()), + RadialPart::Splitter => crate::select::handle_cursor(Handle::Right, h.splitter_angle() - cx.view_angle()), } } @@ -176,6 +270,10 @@ pub struct RadialDrag { /// The options the press found, and the last ones previewed. from: Value, last: Option, + /// For the splitter: its degrees around the ring from the first instance, and the pointer's + /// last direction from the center. + turn: f64, + bearing: Option, } impl RadialDrag { @@ -185,7 +283,7 @@ impl RadialDrag { } let (handles, part) = RadialHandles::hit(cx, p)?; let from = handles.options(part, Vec2::ZERO)?; - Some(Self { handles, part, start: p, from, last: None }) + Some(Self { handles, part, start: p, from, last: None, turn: handles.splitter_turn(), bearing: handles.bearing(p) }) } /// Whether the drag has changed the repeat (and so previews it). @@ -197,13 +295,30 @@ impl RadialDrag { part_cursor(cx, &self.handles, self.part) } + /// The options of the splitter with the pointer at `p`: it follows the pointer around the + /// circle, each move counted by the shorter way round. + fn split(&mut self, p: Point) -> Option { + let ring = self.handles.ring?; + if let Some(b) = self.handles.bearing(p) { + if let Some(last) = self.bearing { + self.turn += ((b - last + 180.0).rem_euclid(360.0) - 180.0) * ring.step.signum(); + } + self.bearing = Some(b); + } + Some(ring.options(ring.shown(self.turn), self.handles.start_angle)) + } + /// Preview the options the pointer at `p` gives, when they change; the first change opens /// the undo step. pub fn drag(&mut self, p: Point) -> Vec { if !finite(p) { return vec![]; } - let Some(v) = self.handles.options(self.part, p - self.start) else { return vec![] }; + let v = match self.part { + RadialPart::Splitter => self.split(p), + part => self.handles.options(part, p - self.start), + }; + let Some(v) = v else { return vec![] }; if self.last.as_ref().unwrap_or(&self.from) == &v { return vec![]; } @@ -266,13 +381,44 @@ mod tests { }) } + /// The point on the 100 pt circle about (150, 250) at `deg` degrees clockwise from straight up. + fn on_circle(deg: f64) -> Point { + let a = deg.to_radians(); + Point::new(150.0 + 100.0 * a.sin(), 250.0 - 100.0 * a.cos()) + } + + /// Apply the `instances` and `endAngle` of a preview to the repeat. + fn apply(doc: &mut Document, selection: &Selection, v: &Value) { + let n = v["instances"].as_u64().unwrap() as u32; + let end = v["endAngle"].as_f64().unwrap(); + set(doc, selection, |i, _, _, e| (*i, *e) = (n, end)); + } + + /// Where the repeat's instances are, in paint order. + fn transforms(doc: &Document, selection: &Selection) -> Vec { + let NodeKind::Repeat(spec) = &doc.node(selection.objects[0]).unwrap().kind else { panic!("a repeat") }; + spec.transforms(Some(doc)) + } + + /// Drag the splitter from `from` to `to` degrees clockwise from straight up, 5° a move, and + /// return the last preview. + fn sweep(d: &mut RadialDrag, from: f64, to: f64) -> Option { + let mut last = None; + let moves = ((to - from).abs() / 5.0).ceil() as i32; + for k in 1..=moves { + if let Some(v) = preview(&d.drag(on_circle(from + (to - from) * f64::from(k) / f64::from(moves)))) { + last = Some(v.clone()); + } + } + last + } + #[test] fn the_handles_sit_below_the_repeat_and_on_its_circle_at_every_zoom() { let (doc, selection) = radial(); // Halfway between the first instance (straight up from the center) and the second, 45° // clockwise from it. - let half = 22.5_f64.to_radians(); - let on_circle = Point::new(150.0 + 100.0 * half.sin(), 250.0 - 100.0 * half.cos()); + let on_circle = on_circle(22.5); for zoom in [0.02, 1.0, 4.0] { let h = RadialHandles::of(&doc, &selection, None, zoom).unwrap(); assert!(near(h.instances_at, Point::new(150.0, 400.0 + HANDLE_GAP / zoom)), "{zoom}: {:?}", h.instances_at); @@ -433,4 +579,106 @@ mod tests { // The radius handle points 22.5° clockwise from straight up: the up-and-down cursor. assert_eq!(cursor(&c, h.radius_at), Some(Cursor::ResizeV)); } + + #[test] + fn the_splitter_sits_half_a_step_past_the_last_instance_shown() { + let (mut doc, selection) = radial(); + // A full ring of eight: between the last instance (315°) and the first. + for zoom in [0.02, 1.0, 4.0] { + let h = RadialHandles::of(&doc, &selection, None, zoom).unwrap(); + assert!(near(h.splitter_at.unwrap(), on_circle(337.5)), "{zoom}: {:?}", h.splitter_at); + assert!(h.parts().contains(&(RadialPart::Splitter, h.splitter_at.unwrap()))); + } + // Five of the eight shown: past the fifth (180°). + set(&mut doc, &selection, |n, _, _, e| (*n, *e) = (5, 180.0)); + let h = RadialHandles::of(&doc, &selection, None, 1.0).unwrap(); + assert!(near(h.splitter_at.unwrap(), on_circle(202.5)), "{:?}", h.splitter_at); + // The instances running the other way from 90°: three of six, the splitter at -60 - 30. + set(&mut doc, &selection, |n, _, a, e| (*n, *a, *e) = (3, 90.0, -30.0)); + let h = RadialHandles::of(&doc, &selection, None, 1.0).unwrap(); + assert!(near(h.splitter_at.unwrap(), on_circle(-60.0)), "{:?}", h.splitter_at); + // One of the eight shown: half a step past it, and the radius handle opposite it. + set(&mut doc, &selection, |n, _, a, e| (*n, *a, *e) = (1, 0.0, 45.0)); + let h = RadialHandles::of(&doc, &selection, None, 1.0).unwrap(); + assert!(near(h.splitter_at.unwrap(), on_circle(22.5)), "{:?}", h.splitter_at); + assert!(near(h.radius_at, on_circle(180.0)), "{:?}", h.radius_at); + } + + #[test] + fn no_splitter_where_the_ring_cannot_be_split() { + let (mut doc, selection) = radial(); + // A single instance to a full turn, no turn at all, a step that does not divide a full + // turn, and a radius of 0. + for (n, end, r) in [(1, 360.0, 100.0), (2, 0.0, 100.0), (3, 100.0, 100.0), (8, 360.0, 0.0), (8, f64::MAX, 100.0)] { + set(&mut doc, &selection, |i, rad, _, e| (*i, *rad, *e) = (n, r, end)); + let h = RadialHandles::of(&doc, &selection, None, 1.0).unwrap(); + assert_eq!(h.splitter_at, None, "{n} over {end}° at {r}"); + assert!(!h.parts().iter().any(|(p, _)| *p == RadialPart::Splitter)); + } + // Two instances to a turn can be split. + set(&mut doc, &selection, |i, rad, _, e| (*i, *rad, *e) = (2, 100.0, 360.0)); + assert!(RadialHandles::of(&doc, &selection, None, 1.0).unwrap().splitter_at.is_some()); + } + + #[test] + fn dragging_the_splitter_hides_instances_and_the_others_keep_their_places() { + let (mut doc, selection) = radial(); + let full = transforms(&doc, &selection); + assert_eq!(full.len(), 8); + let paint = paint(); + let (v, mut d) = { + let c = cx(&doc, &selection, &paint); + let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), 1.0).unwrap(); + let mut d = RadialDrag::hit(&c, h.splitter_at.unwrap(), Mods::default()).unwrap(); + assert!(cursor(&c, h.splitter_at.unwrap()).is_some()); + // Back to 320°, short of the last instance: nothing changes. + assert_eq!(sweep(&mut d, 337.5, 320.0), None); + assert!(!d.adjusting()); + // Back past the last instance (315°): seven shown, the full ring's step apart. + let out = d.drag(on_circle(300.0)); + assert!(matches!(out.first(), Some(Action::Begin(l)) if l == "Repeat Options"), "{out:?}"); + let v = preview(&out).unwrap().clone(); + assert_eq!(v, json!({"instances": 7, "endAngle": 270.0})); + (v, d) + }; + apply(&mut doc, &selection, &v); + let seven = transforms(&doc, &selection); + assert_eq!(seven.len(), 7); + for (k, (a, b)) in seven.iter().zip(&full).enumerate() { + assert!(a.as_coeffs().iter().zip(b.as_coeffs()).all(|(x, y)| (x - y).abs() < 1e-9), "instance {k} kept its place"); + } + // Further back, past 0°: one shown at least. + assert_eq!(sweep(&mut d, 300.0, -200.0), Some(json!({"instances": 1, "endAngle": 45.0}))); + // Forward again, past the start of the ring: all eight, a full turn. + assert_eq!(sweep(&mut d, -200.0, 400.0), Some(json!({"instances": 8, "endAngle": 360.0}))); + assert!(matches!(d.finish().as_slice(), [Action::Cancel]), "back where it began: no undo step"); + + // From the seven shown, forward past 315°: the eighth shows again where it was. + let c = cx(&doc, &selection, &paint); + let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), 1.0).unwrap(); + assert!(near(h.splitter_at.unwrap(), on_circle(292.5))); + let mut d = RadialDrag::hit(&c, h.splitter_at.unwrap(), Mods::default()).unwrap(); + let v = sweep(&mut d, 292.5, 330.0).unwrap(); + assert_eq!(v, json!({"instances": 8, "endAngle": 360.0})); + assert!(matches!(d.finish().as_slice(), [Action::Commit])); + let mut d = RadialDrag::hit(&c, h.splitter_at.unwrap(), Mods::default()).unwrap(); + assert!(d.drag(h.center).is_empty(), "the center gives no direction"); + assert_eq!(sweep(&mut d, 292.5, 250.0), Some(json!({"instances": 6, "endAngle": 225.0}))); + assert!(matches!(d.cancel().as_slice(), [Action::Cancel])); + apply(&mut doc, &selection, &v); + assert_eq!(transforms(&doc, &selection), full); + } + + #[test] + fn the_instances_handle_spreads_a_split_ring_over_the_same_arc() { + let (mut doc, selection) = radial(); + // Seven of eight shown: the handle sets the count alone, as for any partial repeat. + set(&mut doc, &selection, |n, _, _, e| (*n, *e) = (7, 270.0)); + let paint = paint(); + let c = cx(&doc, &selection, &paint); + let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), 1.0).unwrap(); + let mut d = RadialDrag::hit(&c, h.instances_at, Mods::default()).unwrap(); + assert_eq!(preview(&d.drag(h.instances_at + Vec2::new(0.0, 32.0))), Some(&json!({"instances": 9}))); + assert!(matches!(d.finish().as_slice(), [Action::Commit])); + } } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 3c58442e5e..885ba3dcc6 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -4920,6 +4920,93 @@ fn radial_repeat_handles_set_instances_and_radius_in_one_undo_step_each() { assert_eq!(radial(&app).0, 6, "the instances step is the one before"); } +/// A selected radial repeat draws its splitter on its circle. In a zoomed view turned 30°, +/// dragging the splitter back around the circle past two instances hides them while the other +/// four stay where they were, as one undo step; Escape puts a drag back. +#[test] +fn radial_repeat_splitter_hides_instances_in_one_undo_step() { + use vectorcraft_geom::Affine; + use vectorcraft_tools::repeat_radial::{HANDLE_RADIUS, RadialHandles}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 180, "y": 40, "width": 40, "height": 40})).unwrap(); + app.run("object.repeat.radial", json!({"instances": 6, "radius": 60})).unwrap(); + app.ui.task_bar = false; + app.ui.view.rulers = false; + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.view_mut().unwrap().zoom = 1.5; + app.view_mut().unwrap().rotation = 30.0; + frame(&mut app, &ctx, vec![]); + // Instances shown, end angle and where the instances are. + let radial = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + let n = st.doc.node(st.selection.objects[0]).unwrap(); + let vectorcraft_doc::NodeKind::Repeat(spec) = &n.kind else { panic!("a repeat") }; + let vectorcraft_doc::RepeatKind::Radial { instances, end_angle, .. } = spec.kind else { panic!("a radial repeat") }; + (instances, end_angle, spec.transforms(Some(&st.doc))) + }; + let handles = |app: &mut VectorcraftApp| { + let frame = app.selection_box(); + let st = app.session.active().unwrap(); + RadialHandles::of(&st.doc, &st.selection, frame, app.view().unwrap().zoom).unwrap() + }; + // `h`'s splitter turned `deg` degrees about the center (positive: the way the instances run). + let around = + |h: &RadialHandles, deg: f64| h.center + (Affine::rotate(deg.to_radians()) * (h.splitter_at.unwrap() - h.center).to_point()).to_vec2(); + let before = radial(&app); + assert_eq!((before.0, before.1, before.2.len()), (6, 360.0, 6)); + let h = handles(&mut app); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let drawn = shapes(&mut app, &ctx); + let at = xf.to_screen(h.splitter_at.unwrap()); + assert!( + drawn.iter().any(|s| matches!(s, Shape::Circle(c) if c.center.distance(at) < 0.01 && c.radius == HANDLE_RADIUS)), + "the splitter is drawn" + ); + frame(&mut app, &ctx, vec![]); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let drag = |app: &mut VectorcraftApp, from: Pos2, to: Pos2| { + frame(app, &ctx, vec![egui::Event::PointerMoved(from), button(from, true)]); + for k in 1..=4 { + frame(app, &ctx, vec![egui::Event::PointerMoved(from + (to - from) * k as f32 / 4.0)]); + } + }; + let release = |app: &mut VectorcraftApp, at: Pos2| frame(app, &ctx, vec![button(at, false)]); + // Back 120° (two instances 60° apart): four shown, the rest in place. + let to = xf.to_screen(around(&h, -120.0)); + drag(&mut app, xf.to_screen(h.splitter_at.unwrap()), to); + assert_eq!(radial(&app).0, 4, "the drag previews"); + release(&mut app, to); + let after = radial(&app); + assert_eq!((after.0, after.1, after.2.len()), (4, 180.0, 4)); + for (k, (a, b)) in after.2.iter().zip(&before.2).enumerate() { + assert!(a.as_coeffs().iter().zip(b.as_coeffs()).all(|(x, y)| (x - y).abs() < 1e-9), "instance {k} stays where it was"); + } + app.run("edit.undo", json!({})).unwrap(); + assert_eq!((radial(&app).0, radial(&app).1), (6, 360.0), "one undo step"); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!((radial(&app).0, radial(&app).1), (4, 180.0)); + // Escape during a drag forward puts the split back and leaves no undo step. + frame(&mut app, &ctx, vec![]); + let h = handles(&mut app); + let to = xf.to_screen(around(&h, 120.0)); + drag(&mut app, xf.to_screen(h.splitter_at.unwrap()), to); + assert_eq!((radial(&app).0, radial(&app).1), (6, 360.0), "the drag previews"); + let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); + let mut full = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events: vec![escape], ..Default::default() }, |ui| { + crate::shortcuts::handle(&mut app, ui.ctx()); + show(&mut app, ui) + }); + full.textures_delta.clear(); + assert_eq!((radial(&app).0, radial(&app).1), (4, 180.0)); + release(&mut app, to); + assert_eq!(radial(&app).0, 4, "the release after Escape changes nothing"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!((radial(&app).0, radial(&app).1), (6, 360.0), "the split was the step before"); +} + /// While a symbol with 9-slice guides is edited, the canvas draws its four guides dotted across /// its art, with ruler guides hidden too, and none once the mode ends. Dragging the left guide in /// a zoomed view moves that guide alone, as one undo step. diff --git a/crates/ui-egui/src/canvas/tool_overlays.rs b/crates/ui-egui/src/canvas/tool_overlays.rs index b05259f8f6..bc94f19e2b 100644 --- a/crates/ui-egui/src/canvas/tool_overlays.rs +++ b/crates/ui-egui/src/canvas/tool_overlays.rs @@ -535,10 +535,11 @@ pub(super) fn grid_repeat_overlay(app: &mut VectorcraftApp, p: &egui::Painter, x } } -/// A selected radial repeat's circle with its radius handle on it, and its instances handle below -/// it, at the places the Selection tool's hit testing finds them. +/// A selected radial repeat's circle with its radius handle and its splitter on it, and its +/// instances handle below it, at the places the Selection tool's hit testing finds them. The +/// splitter also has a short line across the circle. pub(super) fn radial_repeat_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: &Xf) { - use vectorcraft_tools::repeat_radial::{HANDLE_RADIUS, RadialHandles}; + use vectorcraft_tools::repeat_radial::{HANDLE_RADIUS, RadialHandles, RadialPart}; if app.session.tool_id() != "selection" || !app.ui.view.bounding_box { return; } @@ -552,8 +553,13 @@ pub(super) fn radial_repeat_overlay(app: &mut VectorcraftApp, p: &egui::Painter, p.circle_stroke(c, r, Stroke::new(3.0, t.measure_bg)); p.circle_stroke(c, r, Stroke::new(1.0, t.selection)); } - for (_, at) in h.parts() { + for (part, at) in h.parts() { let c = xf.to_screen(at); + let across = (c - xf.to_screen(h.center)).normalized() * (HANDLE_RADIUS + 4.0); + if part == RadialPart::Splitter && c.is_finite() && across.is_finite() { + p.line_segment([c - across, c + across], Stroke::new(3.0, t.measure_bg)); + p.line_segment([c - across, c + across], Stroke::new(1.5, t.selection)); + } if c.is_finite() { p.circle_filled(c, HANDLE_RADIUS, t.measure_bg); p.circle_stroke(c, HANDLE_RADIUS, Stroke::new(2.0, t.selection)); diff --git a/docs/gaps.md b/docs/gaps.md index 088912552d..c7647a212d 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -139,7 +139,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Done:** the selection tools take a clipping path (a clip group's or a layer's clipping mask) on its outline, within the selection tolerance, before the art it clips, so Direct Selection reshapes a mask where the art covers its edge; Select Behind lists the same, and the eyedropper and the tools that act on what is drawn are unchanged. Broader G1 estimates unchanged. - **Done:** one selected clip group's Properties panel has Edit Clipping Path and Edit Contents at its top, which select its clipping path or its clipped art for the selection tools (public doc cited in target-app-parity.md). Broader G1 estimates unchanged. - **Done:** the Properties panel has the additional contextual controls of the public Properties panel overview: Blend Options in Quick Actions for one blend with the Blend tool, Merge Live Paint for a Live Paint group selected with more paths to merge (Live Paint Make and Merge refuse type, images and other objects that aren't paths, which used to vanish among the group's sources), the Width Profile list in Appearance with the Width tool or a variable-width stroke, an applied effect's Delete icon beside fx (with several effects it opens the Appearance panel), and Corner and Corner Radius for corners selected with Direct Selection (public doc cited in target-app-parity.md). Broader G1 estimates unchanged. -- **Done (#2691):** a selected Grid Repeat ([public page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html)) shows a handle below the grid, one right of it and one past its bottom-right corner: dragging them adds or removes rows, columns or both (1 to 500). A slider between the first two columns and one between the first two rows set the horizontal and vertical spacing, staying halfway across the gap under the pointer. Each drag is one undo step through `object.repeat.options` and Escape cancels it; the controls hide with the edges or the bounding box, and bounding-box handles keep priority where they meet. A selected Radial Repeat ([public page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/create-radial-repeats.html)) shows a handle below it, dragged down for more instances and up for fewer (16 px each, 1 to 1,000), and a handle on its circle between the first two instances, dragged outward or inward for a larger or smaller radius (0 or more); the same undo, Escape, visibility and priority rules apply. The radial splitter remains. Estimates unchanged. +- **Done (#2691):** a selected Grid Repeat ([public page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html)) shows a handle below the grid, one right of it and one past its bottom-right corner: dragging them adds or removes rows, columns or both (1 to 500). A slider between the first two columns and one between the first two rows set the horizontal and vertical spacing, staying halfway across the gap under the pointer. Each drag is one undo step through `object.repeat.options` and Escape cancels it; the controls hide with the edges or the bounding box, and bounding-box handles keep priority where they meet. A selected Radial Repeat ([public page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/create-radial-repeats.html)) shows a handle below it, dragged down for more instances and up for fewer (16 px each, 1 to 1,000), and a handle on its circle between the first two instances, dragged outward or inward for a larger or smaller radius (0 or more); the same undo, Escape, visibility and priority rules apply. Its splitter sits on the circle half a step past the last instance shown: dragging it back around the circle hides the instances it passes, the others keeping their places, and dragging it forward shows them again (one instance at least; VectorCraft's own rules). On a split circle, as on any partial one, the instances handle changes the count alone and spreads the instances over the same arc. Estimates unchanged. - **Done (#2651):** Object › Repeat › Options… for a Grid Repeat has a Preview checkbox ([public page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html)): while it is on the repeat on the canvas follows the fields, Cancel puts the original back without a history step and OK keeps the previewed values as one undo step. Radial and Mirror Repeat Options have none, as their public pages list none. Estimate unchanged. - **Done (#2877):** a selected Mirror Repeat shows its axis: drag the line or the center handle to move it, an end handle to rotate it (Shift: 45°); each drag is one undo step and Escape cancels it. Bounding-box handles take priority over the axis line; the center and end handles keep their actions. Broader G1 estimates unchanged. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3222960ef2..1fd3920773 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -642,6 +642,7 @@ since 2026-10-01. - **Graph section in the Properties panel:** with one graph selected, or series of one graph picked with Group Selection, the Properties panel shows a Graph section. Its Graph Type… button opens the dialog of Object › Graph › Type… ([Format pie graphs](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/format-pie-graphs.html)). Its Graph Data… button opens the dialog of Object › Graph › Data…; this button is VectorCraft's own. Column… shows when every series it would change draws columns or bars, and Marker… when every one draws lines, scatter points or radar lines; this is VectorCraft's own rule. Regression tests in `crates/ui-egui/src/panels/properties/tests.rs`. Scores unchanged. - **Selected Grid Repeat handles (#2691):** `tools/src/repeat_grid.rs` tests place the handles outside the grid at zoom 0.5, 1 and 4, preview rows, columns and spacing, leave no undo step for a drag that ends where it began, and give bounding-box handles priority; a headless canvas regression drags the row handle two tiles down in a zoomed view (3 → 5 rows, the source unchanged, one Undo back) and the column-spacing slider. Scores and hours unchanged. - **Selected Radial Repeat handles:** `tools/src/repeat_radial.rs` tests place the instances handle below the repeat and the radius handle on its circle between the first two instances at zoom 0.02, 1 and 4 (opposite a single instance, at the center with a radius of 0), step the count by whole instances within 1 to 1,000, set the radius from the outward part of a drag and stop it at 0, hide the handles for a locked, hidden or invalid repeat, leave no undo step for a drag that ends where it began, and give bounding-box handles priority; a headless canvas regression in a zoomed view turned 30° drags the instances handle (6 → 8 instances, the source unchanged, one Undo back) and the radius handle (60 → 80 pt), and Escape puts a radius drag back. Scores and hours unchanged. +- **Radial Repeat splitter:** dragging the splitter on a selected radial repeat's circle back hides the instances it passes, and the others keep their places ([Create radial repeats](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/create-radial-repeats.html)). The repeat keeps the instances shown in `instances` and spaces them a full circle's step apart with `endAngle`, so dragging the splitter forward shows the hidden ones again; the splitter's place half a step past the last instance shown and its limit of one instance shown are VectorCraft's own rules, and on a split circle the instances handle changes the count alone, as on any partial one. `tools/src/repeat_radial.rs` tests place the splitter at zoom 0.02, 1 and 4 and on rings running either way, hide it where the step does not divide a full turn, for one instance to a turn and with a radius of 0, and check that the instances left match the first ones of the full ring; a headless canvas regression in a zoomed view turned 30° drags the splitter back past two of six instances as one undo step, and Escape puts a drag back. Scores and hours unchanged. - **Selected Mirror Repeat handles:** a headless canvas regression creates the default mirror repeat and drags its Top bounding-box handle where the axis crosses it; the repeat grows vertically while its width stays fixed. Existing mirror-axis checks cover center movement and end-handle hit priority. The focused UI mirror tests pass. Scores and hours unchanged. - **Transform effect options (#885):** Effect › Distort & Transform › Transform… has visible Transform Objects, Transform Patterns and Scale Strokes & Effects checkboxes (`distort.transform` params `objects`, `patterns`, `strokes`; files without them draw as before). With Transform Objects off the geometry stays and makes no copies; Scale Strokes & Effects scales stroke weights, dashes and the fills' and strokes' effect distances by the mean scale, and Transform Patterns moves pattern tiles, each copy `k` by the transformation `k` times. Such objects draw, export and expand through the same per-copy art, so the canvas and Expand Appearance agree (engine `tests_transformfx`, effects `tests_transformfx`, the dialog test). A Transform effect in a fill's or stroke's own effects applies the same options to that fill or stroke: its weight and dashes and its pattern follow the transformation, and with copies each copy is an object of its own; the canvas, export, Expand Appearance and Use Preview Bounds use the same art (effects `tests_transformfx`). The effects listed after it in that fill's or stroke's list keep their own distances and apply to the transformed art and to each copy, as an object's later effects do after the object's Transform effect: a Drop Shadow after it keeps its offset, an Offset Path after it offsets by its own distance, and an SVG filter after it keeps its scale and the origin of its user space. With Transform Objects off, the effects before it keep their distances too. Before, Scale Strokes & Effects scaled a fill's or stroke's later effects by the mean scale, so existing documents with such effects draw differently. Effects apply in the order they are listed ([Appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)); how the two options treat the effects after a fill's or stroke's own Transform effect is VectorCraft's own rule, following that order (effects `tests::rasterfollow::a_fills_own_transform_leaves_the_shadow_after_it`, `tests::rasterfollow::a_fills_own_transform_leaves_the_offset_after_it`, `tests::rasterfollow::a_fills_own_transform_leaves_the_svg_filter_after_it`, `tests::transformfx::a_fills_own_transform_with_scale_strokes_and_effects_leaves_its_later_effects`; engine `plugins::a_transform_after_a_painted_fill_effect_leaves_the_later_shadow_on_every_paint`). Public reference: [Scale objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html), [How to apply effects](https://helpx.adobe.com/illustrator/using/effects.html), [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html). Scores and hours unchanged. - **Raster effects before a Transform effect:** effects apply in the order they are listed ([Appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)). A Drop Shadow, glow, blur, Feather or pixel filter listed before a Transform effect in the same list (an object's effects, or a fill's or stroke's own) now follows that Transform effect: its sizes scale by the mean scale, and a Drop Shadow's offset turns, reflects and scales with the art. VectorCraft applies this rule with Scale Strokes & Effects on or off. Before, such an effect was drawn at its own distances around the transformed art. The canvas, export, Expand Appearance, Object › Expand, Outline Stroke and the 3D effects use the same values (effects `tests::rasterfollow`; render `a_transform_after_a_drop_shadow_scales_the_shadow_with_the_art`; engine `objexpand::a_shadow_before_a_transform_expands_as_the_canvas_draws_it`, `outlinestroke::a_shadow_before_a_transform_outlines_as_the_canvas_draws_it`). Not yet: a Transform effect that makes copies or moves at random leaves the raster effects before it as they are. The light direction of Underpainting, Rough Pastels, Conté Crayon, Bas Relief, Plaster and Texturizer and the stroke direction of Sprayed Strokes and Graphic Pen now turn and reflect with such a Transform effect, each set to the nearest of its menu's choices (at a tie, the one clockwise of it; VectorCraft's own rule), and Color Halftone's four screen angles turn and reflect with the art ([Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html); effects `tests::rasterfollow::bas_relief_light_follows_rotation_and_reflection` and the tests after it). Not yet: filters whose strokes or patterns run along fixed page axes without a direction setting (Angled Strokes, Crosshatch, Mezzotint's lines, Halftone Pattern's lines, Grain's horizontal and vertical types, De-Interlace) keep those axes, and an uneven scale or a shear sets a direction from the one vector it maps, not a skewed pattern. Scores and hours unchanged. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 8c104ff5bc..8059d8f3af 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -395,7 +395,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Command search: Up and Down move through the results, Enter runs the highlighted one | done | #1798 (#1757) | | Learn panel: Window › Learn and Explore tutorials on the app bar open it; For you holds a Quick skill guide card, Skills lists VectorCraft's own skills with progress rings that fill and counts of tutorials finished, a tutorial shows its numbered steps with a check box each that marks the step done once its sample is open, a finished tutorial has a check mark, Back goes up a level; a tool's name in a step is a link that marks the tool where the toolbars show it (its button, its group's flyout, a torn-off strip, a toolbar made with New Toolbar or the All Tools drawer) without choosing it; View more opens the tutorial's practice sample as a new untitled document, Finish tutorial then marks it finished with all its steps, and Next Up shows the next tutorial in the same skill; Reset progress clears the progress (no video) | done | [the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html); `learn.list`, `learn.tab`, `learn.skills`, `learn.skill`, `learn.show`, `learn.back`, `learn.locateTool`, `learn.openSample`, `learn.markStep`, `learn.finish`, `learn.next`, `learn.resetProgress`; the mark's look and 3-second lifetime, marking steps by hand, keeping the progress in the preferences and Reset progress are VectorCraft's own rules; `panels::learn::tests`, `toolbar::tests` | | Pathfinder panel: a group selected alone counts its nested shapes, so an expanded stroked object keeps the Shape Modes enabled | done | #1642 (#1635) | -| Selected Grid Repeat shows row, column and corner handles and spacing sliders; bounding-box handles take priority where they meet | done | #2691, `tools/src/repeat_grid.rs`; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html); drags preview and commit `object.repeat.options` as one undo step, Escape cancels; a selected Radial Repeat shows an instances handle below it (16 px of drag per instance, 1 to 1,000) and a radius handle on its circle the same way (`tools/src/repeat_radial.rs`; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/create-radial-repeats.html)); its splitter has no handle yet | +| Selected Grid Repeat shows row, column and corner handles and spacing sliders; bounding-box handles take priority where they meet | done | #2691, `tools/src/repeat_grid.rs`; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html); drags preview and commit `object.repeat.options` as one undo step, Escape cancels; a selected Radial Repeat shows an instances handle below it (16 px of drag per instance, 1 to 1,000) and a radius handle on its circle the same way (`tools/src/repeat_radial.rs`; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/create-radial-repeats.html)), and a splitter on its circle that hides the instances it is dragged back past while the others keep their places, and shows them again when dragged forward (its place half a step past the last instance shown and its limit of one instance shown are VectorCraft's own rules) | | Grid Repeat Options (Object › Repeat › Options…) has a Preview checkbox: the repeat on the canvas follows the fields while the dialog is open, Cancel puts the original back without a history step, OK keeps the previewed values as one undo step | done | #2651; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html) lists the Preview option for the grid options only, so Radial and Mirror Repeat Options have none; `dialogs/command.rs` tests | | Type on a Path Options (Type › Type on a Path › Type on a Path Options…, or a double-click on the Type on a Path tools) has a Preview checkbox, off when it opens: the selected type on a path follows Effect, Flip, Align to Path and Spacing while the dialog is open, Cancel puts it back without a history step, OK keeps the previewed values as one undo step | done | #5360; the [public page](https://helpx.adobe.com/illustrator/using/creating-type-path.html) lists the dialog's options, and public tutorials of the dialog show its Preview checkbox; `tests/pathtype.rs` | | Graph Type (Object › Graph › Type…, or a double-click on a graph tool) is a dialog of its own: a menu at the top shows Graph Options or the page of an axis; Graph Options has a button per graph type, Value Axis with Separate Scales, the Style checkboxes (Add Drop Shadow, Add Legend Across Top, First Row in Front, First Column in Front) and the options of the type picked (Column or Bar Width and Cluster Width; Mark Data Points, Connect Data Points, Edge-to-Edge Lines and Draw Filled Lines; a pie graph's Legend, Position and Sort); the Value Axis page (Left Axis and Right Axis with the value axis on both sides) has Tick Values with Override Calculated Values, Tick Marks and Add Labels, and the Category Axis page has Tick Marks with Draw Tick Marks Between Labels; with series picked by Group Selection the type and value axis go to those series | done | Public pages: [graph types](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/change-graph-types.html), [value axes](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/change-graph-value-axes.html), [columns, bars and lines](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/format-columns-bars-and-lines.html), [pie graphs](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/format-pie-graphs.html), [separate scales](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/assign-different-scales-to-value-axes.html), [combined types](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/combine-different-graph-types.html). The options dimmed for a type, the pages listed and the Legend checkbox are VectorCraft's own rules. Dialog `graphType`; `dialogs/graph_type.rs` and its tests | From 9ecc8087c32b6bd408989d1b183fee76254d08f7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 04:44:31 -0800 Subject: [PATCH 17/31] 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 18/31] 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 0897b32a78af00a242599a8034e2f698ad2291e8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 04:46:28 -0800 Subject: [PATCH 19/31] Isolation mode: the canvas context menu isolates one selected path With one path selected, a member of a group or a compound path included, the canvas context menu now has Isolate Selected Path (object.isolate), next to where Isolate Selected Group shows for one group or compound path. Neither item shows for an object that object.isolate refuses: a hidden or locked object, one in a hidden or locked group or layer, a guide while Lock Guides is on, and, while a symbol is edited, an object outside the symbol's art. Help page: https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=324 --- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/menus/context.rs | 25 +++++- crates/ui-egui/src/menus/labels.rs | 1 + crates/ui-egui/src/tests/contextmenu.rs | 103 ++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 32 files changed, 156 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 71e443a399..a2390d1e36 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -4165,6 +4165,7 @@ imageTrace Outline Контур to set spacing and orientation за задаване на разстояние и ориентация : : Isolate Selected Group Изолиране на избраната група + Isolate Selected Path Изолиране на избрания път Release Clipping Mask Освобождаване на маска за изрязване Make Compound Path Създаване на съставен път Release Compound Path Освобождаване на съставен път diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 883d6dd387..0f82706633 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -880,6 +880,7 @@ Auto Color Automatska boja Automatic Automatski Isolate Selected Group Izoliraj odabranu grupu + Isolate Selected Path Izoliraj odabranu putanju Isolate Selected Object Izoliraj odabrani objekat Exit Isolation Mode Izađi iz načina izolacije Make Clipping Mask Napravi masku isijecanja diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a8a63cbf55..9b47734895 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -2265,6 +2265,7 @@ digits Malayalam Malaiàlam Isolate Blending Aïlla la fusió Isolate Group Aïlla el grup Isolate Selected Group Aïlla el grup seleccionat + Isolate Selected Path Aïlla el traçat seleccionat Isolate Selected Object Aïlla l’objecte seleccionat Isometric Bottom Isomètrica inferior Isometric Left Isomètrica esquerra diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 569b1347ec..5f970cb143 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -893,6 +893,7 @@ Auto Color Automatická barva Automatic Automaticky Isolate Selected Group Izolovat vybranou skupinu + Isolate Selected Path Izolovat vybranou cestu Isolate Selected Object Izolovat vybraný objekt Exit Isolation Mode Ukončit izolovaný režim Make Clipping Mask Vytvořit ořezovou masku diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 4578e4efc1..53420f4594 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3500,6 +3500,7 @@ liquify-list-end {0}, {1} {0} og {1} Auto Color Autofarve Automatic Automatisk Isolate Selected Group Isolér valgt gruppe + Isolate Selected Path Isolér valgt kurve Exit Isolation Mode Afslut isoleringstilstand Make Clipping Mask Opret beskæringsmask Release Clipping Mask Frigør beskæringsmask diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c943c89dd2..f3fb347bb0 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4223,6 +4223,7 @@ imageTrace Outline Kontur to set spacing and orientation legt Abstand und Ausrichtung fest : : Isolate Selected Group Ausgewählte Gruppe isolieren + Isolate Selected Path Ausgewählten Pfad isolieren Isolate Selected Object Ausgewähltes Objekt isolieren Release Clipping Mask Schnittmaske zurückwandeln Make Compound Path Zusammengesetzten Pfad erstellen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 906640aa0a..674eca73d2 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4685,6 +4685,7 @@ digits Malayalam Μαλαγιάλαμ “{file}” is protected by a password. Το «{file}» προστατεύεται με κωδικό. ● Recording ● Εγγραφή Isolate Selected Group Απομόνωση επιλεγμένης ομάδας + Isolate Selected Path Απομόνωση επιλεγμένης διαδρομής Make Compound Path Δημιουργία σύνθετης διαδρομής Release Compound Path Αποδέσμευση σύνθετης διαδρομής — substituted by {style} — αντικαταστάθηκε από {style} diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9239c93a73..a7c5256175 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4310,6 +4310,7 @@ imageTrace Outline Contorno to set spacing and orientation para definir espaciado y orientación : : Isolate Selected Group Aislar grupo seleccionado + Isolate Selected Path Aislar trazado seleccionado Isolate Selected Object Aislar objeto seleccionado Release Clipping Mask Soltar máscara de recorte Make Compound Path Crear trazado compuesto diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 423703e5c1..df9694d418 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -884,6 +884,7 @@ Auto Color Automaattinen väri Automatic Automaattinen Isolate Selected Group Eristä valittu ryhmä + Isolate Selected Path Eristä valittu polku Exit Isolation Mode Poistu eristystilasta Make Clipping Mask Luo leikkausmaski Release Clipping Mask Vapauta leikkausmaski diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 1cff1c8ad0..27c6d33ec9 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4295,6 +4295,7 @@ imageTrace Outline Contour to set spacing and orientation pour définir l’espacement et l’orientation :  : Isolate Selected Group Isoler le groupe sélectionné + Isolate Selected Path Isoler le tracé sélectionné Isolate Selected Object Isoler l’objet sélectionné Release Clipping Mask Annuler le masque d’écrêtage Make Compound Path Créer un tracé transparent diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 4eed343e3d..66b0c34756 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -1858,6 +1858,7 @@ Isolate Blending બ્લેન્ડિંગ અલગ કરો Isolate Group ગ્રૂપ અલગ કરો Isolate Selected Group પસંદ કરેલું ગ્રૂપ અલગ કરો + Isolate Selected Path પસંદ કરેલો પાથ અલગ કરો Isolate Selected Object પસંદ કરેલી ઑબ્જેક્ટ અલગ કરો Isometric Bottom આઇસોમેટ્રિક નીચે Isometric Left આઇસોમેટ્રિક ડાબે diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index de33cdbd92..0b8d97299f 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -2508,6 +2508,7 @@ antiAlias Sharp शार्प Isolate Blending ब्लेंडिंग अलग करें Isolate Group अलग समूह Isolate Selected Group सिलेक्टेड समूह अलग करें + Isolate Selected Path सिलेक्टेड पाथ अलग करें Isolate Selected Object सिलेक्टेड ऑब्जेक्ट को अलग करें Isometric Bottom आइसोमेट्रिक बॉटम Isometric Left आइसोमेट्रिक लेफ्ट diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index f869e7d07b..c8e4fa71cc 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -2266,6 +2266,7 @@ file-filter Templates Sablonok Isolate Blending Keverés elkülönítése Isolate Group Csoport elkülönítése Isolate Selected Group Kijelölt csoport elkülönítése + Isolate Selected Path Kijelölt útvonal elkülönítése Isolate Selected Object Kijelölt objektum elkülönítése Italian Olasz Italic Dőlt diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c5f865e69b..13211d084a 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -826,6 +826,7 @@ Auto Color Warna otomatis Automatic Otomatis Isolate Selected Group Isolasi grup terseleksi + Isolate Selected Path Isolasi jalur terseleksi Exit Isolation Mode Keluar dari mode isolasi Make Clipping Mask Buat masker kliping Release Clipping Mask Lepaskan masker kliping diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 08cefdbed7..2d0ada90bc 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4358,6 +4358,7 @@ imageTrace Outline Contorno to set spacing and orientation per impostare spaziatura e orientamento : : Isolate Selected Group Isola gruppo selezionato + Isolate Selected Path Isola tracciato selezionato Isolate Selected Object Isola oggetto selezionato Release Clipping Mask Rilascia maschera di ritaglio Make Compound Path Crea tracciato composto diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 59c7628f40..32048b16a7 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -950,6 +950,7 @@ digits Malayalam マラヤーラム数字 Auto Color 自動カラー Automatic 自動 Isolate Selected Group 選択したグループを分離 + Isolate Selected Path 選択したパスを分離 Isolate Selected Object 選択したオブジェクトを分離 Exit Isolation Mode 分離モードを終了 Make Clipping Mask クリッピングマスクを作成 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 9393433cdb..f1d6efda1c 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2874,6 +2874,7 @@ VectorCraft Help… VectorCraft-ის დახმარება… Automatic ავტომატური Isolate Selected Group მონიშნული ჯგუფის იზოლირება + Isolate Selected Path მონიშნული ტრაექტორიის იზოლირება Exit Isolation Mode იზოლაციის რეჟიმიდან გამოსვლა Make Clipping Mask მომჭრელი ნიღბის შექმნა Release Clipping Mask მომჭრელი ნიღბის მოხსნა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 49d5e10dc1..304f1b06a8 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -943,6 +943,7 @@ digits Malayalam 말라얄람어 Auto Color 자동 색상 Automatic 자동 Isolate Selected Group 선택한 그룹 격리 + Isolate Selected Path 선택한 패스 격리 Isolate Selected Object 선택한 개체 격리 Exit Isolation Mode 격리 모드 종료 Make Clipping Mask 클리핑 마스크 만들기 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index f071ebd0e2..65b88ee2fe 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1394,6 +1394,7 @@ liquify-list-end {0}, {1} {0} en {1} Auto Color Automatische kleur Automatic Automatisch Isolate Selected Group Geselecteerde groep isoleren + Isolate Selected Path Geselecteerd pad isoleren Exit Isolation Mode Isolatiemodus verlaten Make Clipping Mask Knipmasker maken Release Clipping Mask Knipmasker vrijgeven diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 2477c73abd..5727a0897e 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -840,6 +840,7 @@ Auto Color Kolor automatyczny Automatic Automatycznie Isolate Selected Group Izoluj zaznaczoną grupę + Isolate Selected Path Izoluj zaznaczoną ścieżkę Isolate Selected Object Izoluj zaznaczony obiekt Exit Isolation Mode Wyjdź z trybu izolacji Make Clipping Mask Utwórz maskę przycinającą diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 333351b9af..65d343ac32 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1573,6 +1573,7 @@ antiAlias Sharp Nítido Isolate Blending Isolar Mesclagem Isolate Group Isolar Grupo Isolate Selected Group Isolar Grupo Selecionado + Isolate Selected Path Isolar Caminho Selecionado Isolate Selected Object Isolar Objeto Selecionado Italian Italiano Join Unir diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ae33aa0d55..1fdf6c0fc1 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4343,6 +4343,7 @@ imageTrace Outline Контур to set spacing and orientation для задания интервала и ориентации : : Isolate Selected Group Изолировать выбранную группу + Isolate Selected Path Изолировать выбранный контур Isolate Selected Object Изолировать выбранный объект Release Clipping Mask Освободить маску обрезки Make Compound Path Создать составной контур diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1bd4fd0692..8a32e40842 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4227,6 +4227,7 @@ imageTrace Outline Kontur to set spacing and orientation för att ange avstånd och orientering : : Isolate Selected Group Isolera markerad grupp + Isolate Selected Path Isolera markerad bana Release Clipping Mask Släpp klippningsmask Make Compound Path Skapa sammansatt bana Release Compound Path Släpp sammansatt bana diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index a2a38c679a..5432cdce37 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4078,6 +4078,7 @@ imageTrace Outline Kontur to set spacing and orientation aralığı ve yönlendirmeyi ayarlamak için : : Isolate Selected Group Seçili Grubu İzole Et + Isolate Selected Path Seçili Yolu İzole Et Isolate Selected Object Seçili Nesneyi Ayır Release Clipping Mask Kırpma Maskesini Serbest Bırakın Make Compound Path Bileşik Yol Yap diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 17c673885d..7e83a1799e 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4351,6 +4351,7 @@ imageTrace Outline Контур to set spacing and orientation для завдання інтервалу та орієнтації : : Isolate Selected Group Ізолювати обрану групу + Isolate Selected Path Ізолювати обраний контур Isolate Selected Object Ізолювати обраний об’єкт Release Clipping Mask Звільнити відсічну маску Make Compound Path Створити складений контур diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index da89525314..361c30bdd6 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -2154,6 +2154,7 @@ digits Hindi Hindi Isolate Blending Tách biệt hòa trộn Isolate Group Tách biệt nhóm Isolate Selected Group Tách biệt nhóm đã chọn + Isolate Selected Path Tách biệt đường dẫn đã chọn Isolate Selected Object Tách biệt đối tượng đã chọn Isometric Bottom Đẳng góc dưới Isometric Left Đẳng góc trái diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5f612cb0d4..14ba565ffc 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4188,6 +4188,7 @@ imageTrace Outline 轮廓 to set spacing and orientation 可设置间距与方向 : : Isolate Selected Group 隔离选择的编组 + Isolate Selected Path 隔离选择的路径 Isolate Selected Object 隔离选择的对象 Release Clipping Mask 释放剪切蒙版 Make Compound Path 制作复合路径 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e0b5a13ee2..a3626c7863 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5504,6 +5504,7 @@ imageTrace Outline 輪廓 to set spacing and orientation 可設定間距與方向 : : Isolate Selected Group 隔離選取的群組 + Isolate Selected Path 隔離選取的路徑 Isolate Selected Object 隔離選取的物件 Release Clipping Mask 釋放剪裁遮色片 Make Compound Path 製作複合路徑 diff --git a/crates/ui-egui/src/menus/context.rs b/crates/ui-egui/src/menus/context.rs index 68b2a93574..187ce863e4 100644 --- a/crates/ui-egui/src/menus/context.rs +++ b/crates/ui-egui/src/menus/context.rs @@ -55,10 +55,19 @@ pub fn context_items(app: &VectorcraftApp) -> Vec { ]); } else { v.extend([c("Cut", "edit.cut"), c("Copy", "edit.copy"), c("Paste", "edit.paste"), Sep]); + // With one group or compound path selected the menu has Isolate Selected Group, and with + // one path selected (a member of a group or a compound path too) it has Isolate Selected + // Path, as the help page + // (https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=324) + // lists them. Neither shows for an object that `object.isolate` refuses. if let [one] = roots.as_slice() - && one.is_container() + && isolatable(app, &st.doc, one) { - v.push(c("Isolate Selected Group", "object.isolate")); + if one.is_container() { + v.push(c("Isolate Selected Group", "object.isolate")); + } else if matches!(one.kind, NodeKind::Path { .. }) { + v.push(c("Isolate Selected Path", "object.isolate")); + } } if several { v.push(c("Group", "object.group")); @@ -244,6 +253,18 @@ fn artboard_items(app: &VectorcraftApp) -> Vec { v } +/// Does `object.isolate` take `n`? It and every group and layer above it are shown and unlocked +/// (for a Shaper Group, its source group, which is the group isolated), it is not on a locked +/// artboard, it is not a guide path while Lock Guides is on, and while a symbol is edited it is on +/// the symbol's editing layer. A selection set by a command can still hold an object that fails +/// this. +fn isolatable(app: &VectorcraftApp, doc: &vectorcraft_doc::Document, n: &vectorcraft_doc::Node) -> bool { + let target = if n.extras().shaper.is_some() { n.children().and_then(|c| c.first()).map_or(n.id, |c| c.id) } else { n.id }; + doc.is_editable(target) + && !(app.session.guides_locked() && doc.node(target).is_some_and(|t| t.is_guide())) + && doc.symbol_edit.as_ref().is_none_or(|e| doc.ancestry(target).is_some_and(|a| a.contains(&e.layer))) +} + /// `items` without the commands that can't run now (Undo and Redo stay, greyed out), submenus /// left empty, and separators that no longer separate anything. fn prune(app: &VectorcraftApp, items: Vec) -> Vec { diff --git a/crates/ui-egui/src/menus/labels.rs b/crates/ui-egui/src/menus/labels.rs index b8829ac0a2..3fe80167bd 100644 --- a/crates/ui-egui/src/menus/labels.rs +++ b/crates/ui-egui/src/menus/labels.rs @@ -248,6 +248,7 @@ pub const CONTEXT_LABELS: &[&str] = &[ "Add to Dictionary", "No Suggestions", "Isolate Selected Group", + "Isolate Selected Path", "Exit Isolation Mode", "Lock Artboards", "Lock Selected", diff --git a/crates/ui-egui/src/tests/contextmenu.rs b/crates/ui-egui/src/tests/contextmenu.rs index b73bb08dfa..a8a517a03d 100644 --- a/crates/ui-egui/src/tests/contextmenu.rs +++ b/crates/ui-egui/src/tests/contextmenu.rs @@ -248,6 +248,109 @@ fn the_menu_follows_the_selection() { assert!(items.windows(2).all(|w| !matches!(w, [Item::Sep, Item::Sep]))); } +/// The labels of the context menu's isolation items. +fn isolate_labels(app: &VectorcraftApp) -> Vec<&'static str> { + labels(&menus::context_items(app)).into_iter().filter(|l| l.starts_with("Isolate Selected")).collect() +} + +/// One selected path has Isolate Selected Path, which isolates that path. +#[test] +fn single_path_context_item_enters_isolation() { + let mut app = app(); + let a = rect(&mut app, 0.0, 0.0); + app.run("select.set", json!({"ids": [a.0]})).unwrap(); + assert_eq!(isolate_labels(&app), ["Isolate Selected Path"]); + let entries = menus::context_entries(&app); + assert!(entries.iter().any(|e| e.command.as_deref() == Some("object.isolate") && e.enabled), "agents see the item"); + menus::invoke(&mut app, "object.isolate", json!({})); + assert_eq!(app.session.active().unwrap().isolation, Some(a), "the path is isolated"); + assert!(labels(&menus::context_items(&app)).contains(&"Exit Isolation Mode")); +} + +/// The isolation item names the kind of the one selected object: a group or a compound path is a +/// group, a path (a group's member too) is a path, and no object or two objects have neither. +#[test] +fn isolation_context_item_follows_selected_kind() { + let mut app = app(); + let (a, b) = (rect(&mut app, 0.0, 0.0), rect(&mut app, 50.0, 50.0)); + app.run("select.none", json!({})).unwrap(); + assert!(isolate_labels(&app).is_empty(), "nothing selected"); + app.run("select.set", json!({"ids": [a.0, b.0]})).unwrap(); + assert!(isolate_labels(&app).is_empty(), "two paths"); + app.run("object.compoundPath.make", json!({})).unwrap(); + assert_eq!(isolate_labels(&app), ["Isolate Selected Group"], "a compound path selected whole"); + let compound = app.session.active().unwrap().selection.objects.clone(); + app.run("select.set", json!({"ids": [a.0]})).unwrap(); + assert_eq!(app.session.active().unwrap().selection.objects, [a], "a compound path's member selected on its own"); + assert_eq!(isolate_labels(&app), ["Isolate Selected Path"], "a path in a compound path"); + app.run("select.set", json!({"ids": [compound[0].0]})).unwrap(); + app.run("object.compoundPath.release", json!({})).unwrap(); + app.run("select.set", json!({"ids": [a.0, b.0]})).unwrap(); + app.run("object.group", json!({})).unwrap(); + assert_eq!(isolate_labels(&app), ["Isolate Selected Group"], "a group"); + app.run("select.set", json!({"ids": [a.0]})).unwrap(); + assert_eq!(app.session.active().unwrap().selection.objects, [a], "a member selected on its own"); + assert_eq!(isolate_labels(&app), ["Isolate Selected Path"], "a path in a group"); + menus::invoke(&mut app, "object.isolate", json!({})); + assert_eq!(app.session.active().unwrap().isolation, Some(a), "the member is isolated"); +} + +/// Neither isolation item shows for an object `object.isolate` refuses, which a selection set by a +/// command can still hold: a hidden or locked object, a path in a locked group, and a guide while +/// guides are locked. +#[test] +fn isolation_context_item_skips_objects_that_cannot_be_isolated() { + let mut app = app(); + let (a, b) = (rect(&mut app, 0.0, 0.0), rect(&mut app, 50.0, 50.0)); + let set = |app: &mut VectorcraftApp, id: NodeId, f: fn(&mut vectorcraft_doc::Node)| { + let st = app.session.doc_mut().unwrap(); + f(std::sync::Arc::make_mut(&mut st.doc).node_mut(id).unwrap()); + st.selection.set([id]); + }; + set(&mut app, a, |n| n.locked = true); + assert!(isolate_labels(&app).is_empty(), "a locked path"); + set(&mut app, a, |n| { + n.locked = false; + n.visible = false; + }); + assert!(isolate_labels(&app).is_empty(), "a hidden path"); + set(&mut app, a, |n| n.visible = true); + assert_eq!(isolate_labels(&app), ["Isolate Selected Path"]); + app.run("select.set", json!({"ids": [a.0, b.0]})).unwrap(); + app.run("object.group", json!({})).unwrap(); + let g = app.session.active().unwrap().selection.objects[0]; + set(&mut app, g, |n| n.locked = true); + assert!(isolate_labels(&app).is_empty(), "a locked group"); + app.session.doc_mut().unwrap().selection.set([a]); + assert!(isolate_labels(&app).is_empty(), "a path in a locked group"); + set(&mut app, g, |n| n.locked = false); + app.run("object.ungroup", json!({})).unwrap(); + app.run("select.set", json!({"ids": [a.0]})).unwrap(); + app.run("view.guides.make", json!({})).unwrap(); + app.run("view.guides.lock", json!({})).unwrap(); + assert!(app.session.guides_locked()); + app.session.doc_mut().unwrap().selection.set([a]); + assert!(isolate_labels(&app).is_empty(), "a guide while guides are locked"); +} + +/// While a symbol is edited, a path in the symbol's art has Isolate Selected Path, and a path +/// outside it, which a selection set by a command can still hold, has no isolation item. +#[test] +fn isolation_context_item_skips_objects_outside_the_edited_symbol() { + let mut app = app(); + let outside = rect(&mut app, 0.0, 0.0); + rect(&mut app, 200.0, 0.0); + app.run("symbol.new", json!({"name": "Box"})).unwrap(); + app.run("symbol.edit", json!({"name": "Box"})).unwrap(); + assert!(app.session.active().unwrap().doc.symbol_edit.is_some(), "symbol editing mode"); + let inside = rect(&mut app, 100.0, 100.0); + app.session.doc_mut().unwrap().selection.set([inside]); + assert_eq!(isolate_labels(&app), ["Isolate Selected Path"], "a path in the symbol's art"); + app.session.doc_mut().unwrap().selection.set([outside]); + assert!(isolate_labels(&app).is_empty(), "a path outside the symbol's art"); + assert!(app.run("object.isolate", json!({"id": outside.0})).is_err(), "object.isolate refuses it"); +} + /// A closed path of 60 jagged anchors around (150, 150), filled so that a right-click inside it /// hits it, with nothing selected. fn jagged(app: &mut VectorcraftApp) -> NodeId { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..0782e7760d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1096,6 +1096,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - In the Transform panel, the Properties panel's Transform section and the Control bar, Alt+Enter (Option+Return) applies a value to a copy of the selection and selects the copy, in one undo step. With anchor points selected with Direct Selection it applies the value to them, as Enter does. Ctrl/Cmd+Enter in W or H applies the value and scales the selection proportionally with the link off. With the Artboard tool, it scales the active artboard proportionally. A percentage typed alone in W or H (`50%`) is that share of the size the field shows, and the link and Ctrl/Cmd+Enter keep the proportions as with a length (#2401). - The Control bar's underlined Transform link opens the Transform panel in a popover under it (reference point, X/Y/W/H, Rotate and Shear with their icons and angle presets, flips, shape properties, Scale Corners and Scale Strokes & Effects), as its Stroke link does the Stroke panel; X/Y/W/H also show inline while the bar has room. The reference point locator is nine squares, the outer eight joined around the box. As VectorCraft's own keyboard rule, the locator is one tab stop in the Control bar popover, the Transform panel, the Properties panel and the dialogs, the Arrange Tools dialogs included. While it has the focus it shows an outline, and ←, →, ↑ and ↓ move the reference point one square, stopping at the edges (`the_reference_point_grid_is_one_tab_stop`, `arrow_keys_move_the_reference_point`, `the_reference_point_locator_is_one_tab_stop_and_arrows_move_it`). - In isolation mode the Control bar has an Exit Isolation Mode button (`object.exitIsolation`), except while a pattern is edited. Outside isolation mode, with one group, compound path, path, image, mesh or placed file selected, it has an Isolate Selected Object button (`object.isolate`), which also isolates a path inside a group that Direct Selection selected. + - The canvas context menu has Isolate Selected Path (`object.isolate`) when the selection is one path, a path selected inside a group or a compound path included, as the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=324) lists it beside Isolate Selected Group. As VectorCraft's own rule, neither item shows for two or more objects, or for an object `object.isolate` refuses: a hidden or locked object, one in a hidden or locked group or layer, a guide while Lock Guides is on, and, while a symbol is edited, an object outside the symbol's art (`single_path_context_item_enters_isolation`, `isolation_context_item_follows_selected_kind`, `isolation_context_item_skips_objects_that_cannot_be_isolated`). - While an opacity mask is edited, Exit Isolation Mode (Esc, the isolation bar's back arrow, the Control bar's button, and the Layers panel menu's and canvas context menu's Exit Isolation Mode) leaves mask editing as Stop Editing Opacity Mask does, in one undo step: the mask keeps the edits, and the masked object is selected. While a pattern is edited, the Exit Isolation Mode item of the Layers panel menu and of the canvas context menu saves the pattern and leaves pattern editing, as Done does. - Numeric spinner arrows keep stepping while held with the mouse past the click timeout and stop on release (#6307; `a_held_spinner_arrow_repeats`). - Object › Vector Halftone keeps the selection box and hides selection marks on the temporary dots during Preview; turning Preview off or cancelling restores the original selection marks (#6369). From 8a47799f173730247e7459fa700f8c7395a106b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 05:09:57 -0800 Subject: [PATCH 20/31] 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 21/31] 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 75b02ea8df4f4bd7742d58278fe89068d08a2968 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 05:29:31 -0800 Subject: [PATCH 22/31] Symbols: the panel reads the current symbol without running symbol.list The Symbols panel and its panel menu asked for the current symbol on every frame by running symbol.list, which builds a row per symbol and walks the whole document once per symbol to count its instances. They now read it from the active document with cmd::current_symbol, the rule symbol.list itself uses for its `current`: the stored name while a symbol has it, else the first symbol. symbol.sortByName, symbol.place, symbol.options and text.insertInline use the same function, and symbol.list's reply is unchanged. An idle frame of the panel or its menu now runs no command, so on macOS the native menu is not brought up to date on every frame while the panel is open. In a document with 200 symbols and 50,000 objects the read takes 0.035 us instead of 48.5 ms in a release build (thread CPU time on Linux, median of 7 runs). The gain matters on large documents; on small ones it is too small to notice. --- crates/engine/src/cmd.rs | 4 + crates/engine/src/cmd/brushsym.rs | 3 + crates/engine/src/cmd/brushsym/symbols.rs | 23 ++-- crates/engine/src/cmd/inline.rs | 11 +- crates/engine/src/tests/brushsym.rs | 47 +++++++ crates/ui-egui/src/panels/symbols.rs | 143 +++++++++++++++++++++- docs/target-app-parity.md | 1 + 7 files changed, 206 insertions(+), 26 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index e2bc50cdc5..c4a86dd3a5 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -893,6 +893,10 @@ pub use buildcmds::live_paint_gaps; /// Control bar enable it when it changes one). pub use brushsym::reset_transformation_changes; +/// The Symbols panel's current symbol, as `symbol.list` answers it (the panel reads it on every +/// frame without running the command). +pub use brushsym::current_symbol; + /// The byte order of UTF-16 text without a byte-order mark, by Import Data Sets' rule (the Graph /// Data window reads files by it too). pub use variablecmds::utf16_order_without_mark; diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 1f9490f24e..c4f35dfc3f 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -27,6 +27,9 @@ use crate::EngineError; /// Whether Reset Transformation changes a symbol instance. pub use symbols::reset_transformation_changes; +/// The Symbols panel's current symbol, as `symbol.list` answers it. +pub use symbols::current_symbol; + mod brushes; mod dynamic; mod symbols; diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 9b718c61b4..cecd314858 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -162,7 +162,7 @@ pub(super) fn symbol_sort(s: &mut Session, _: &Value) -> Result { if d.symbols.is_sorted_by_key(key) { return ok(); } - let current = current_symbol(d).or_else(|| symbol_names(d).into_iter().next()); + let current = current_symbol(d); s.edit("Sort by Name", |d, _| { if let Some(name) = current { d.unknown.insert(CURRENT_SYMBOL.into(), json!(name)); @@ -173,12 +173,15 @@ pub(super) fn symbol_sort(s: &mut Session, _: &Value) -> Result { ok() } -fn symbol_names(d: &Document) -> Vec { - d.symbols.iter().map(|s| s.name.clone()).collect() -} - -fn current_symbol(d: &Document) -> Option { - d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str).filter(|n| d.symbols.iter().any(|s| s.name == *n)).map(str::to_string) +/// The Symbols panel's current symbol, as `symbol.list` answers it: the stored current symbol +/// while `d` has a symbol of that name, else the first symbol; `None` when `d` has no symbols. +pub fn current_symbol(d: &Document) -> Option { + d.unknown + .get(CURRENT_SYMBOL) + .and_then(Value::as_str) + .filter(|n| d.symbols.iter().any(|s| s.name == *n)) + .or_else(|| d.symbols.first().map(|s| s.name.as_str())) + .map(str::to_string) } pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result { @@ -200,7 +203,7 @@ pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result { }) }) .collect(); - Ok(json!({ "symbols": list, "current": current_symbol(d).or_else(|| symbol_names(d).into_iter().next()) })) + Ok(json!({ "symbols": list, "current": current_symbol(d) })) } /// Store `art` ([`normalize`]d, of natural size `size`) as symbol `name`, which becomes the @@ -398,9 +401,7 @@ fn resolve_symbol(d: &Document, p: &Value, cmd: &str) -> Result { match str_param(p, "name") { Some(n) if d.symbols.iter().any(|s| s.name == n) => Ok(n.to_string()), Some(n) => Err(bad(cmd, format!("no symbol named `{n}`"))), - None => { - current_symbol(d).or_else(|| symbol_names(d).into_iter().next()).ok_or_else(|| EngineError::Other("the document has no symbols".into())) - } + None => current_symbol(d).ok_or_else(|| EngineError::Other("the document has no symbols".into())), } } diff --git a/crates/engine/src/cmd/inline.rs b/crates/engine/src/cmd/inline.rs index db3e929952..d2df2ada51 100644 --- a/crates/engine/src/cmd/inline.rs +++ b/crates/engine/src/cmd/inline.rs @@ -6,6 +6,7 @@ use vectorcraft_doc::text::INLINE_MAX_SCALE; use vectorcraft_doc::{Document, InlineArt, NodeId, NodeKind, TextRun}; use vectorcraft_text::edit; +use super::brushsym::current_symbol; use super::typecmd::refresh_bounds; use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_doc, id_param, str_param}; @@ -97,13 +98,3 @@ fn insert_inline(s: &mut Session, p: &Value) -> Result { } Ok(json!({"id": id.0, "caret": caret})) } - -/// The Symbols panel's current symbol, else the first one. -fn current_symbol(d: &Document) -> Option { - d.unknown - .get("currentSymbol") - .and_then(Value::as_str) - .filter(|n| d.symbols.iter().any(|s| s.name == *n)) - .map(str::to_string) - .or_else(|| d.symbols.first().map(|s| s.name.clone())) -} diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 706bf2a508..77258b7eb7 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -2599,3 +2599,50 @@ fn symbol_sort_by_name_orders_the_symbols_in_one_undo_step() { s.execute("symbol.sortByName", &json!({})).unwrap(); assert_eq!(s.doc().unwrap().history.undo.len(), before); } + +/// `cmd::current_symbol` answers what `symbol.list` answers as `current`, and what `rule` (the +/// stored name while a symbol has it, else the first of all the names) answers: +/// with no symbols, with no stored name, with a stored name that is not first, after the current +/// symbol is deleted, with a stored name no symbol has and with a stored value that is not text. +#[test] +fn current_symbol_is_the_current_symbol_list_answers() { + fn rule(d: &Document) -> Option { + let names: Vec = d.symbols.iter().map(|s| s.name.clone()).collect(); + let stored = d.unknown.get("currentSymbol").and_then(Value::as_str).filter(|n| d.symbols.iter().any(|s| s.name == *n)).map(str::to_string); + stored.or_else(|| names.into_iter().next()) + } + fn check(s: &mut Session, want: Option<&str>, case: &str) { + let listed = s.execute("symbol.list", &json!({})).unwrap()["current"].clone(); + let d = &s.doc().unwrap().doc; + let helper = crate::cmd::current_symbol(d); + assert_eq!(helper.as_deref(), want, "{case}"); + assert_eq!(json!(helper), listed, "{case}: symbol.list"); + assert_eq!(helper, rule(d), "{case}: the rule"); + } + fn store(s: &mut Session, v: Value) { + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).unknown.insert("currentSymbol".into(), v); + } + let mut s = session(); + check(&mut s, None, "no symbols"); + store(&mut s, json!("Gone")); + check(&mut s, None, "no symbols and a stored name"); + for (i, name) in ["A", "B", "C"].into_iter().enumerate() { + rect(&mut s, 20.0 * i as f64, 0.0, 10.0, 10.0); + s.execute("symbol.new", &json!({"name": name})).unwrap(); + } + check(&mut s, Some("C"), "the newest symbol is current"); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).unknown.remove("currentSymbol"); + check(&mut s, Some("A"), "no stored name"); + s.execute("symbol.setCurrent", &json!({"name": "B"})).unwrap(); + check(&mut s, Some("B"), "a stored name that is not first"); + s.execute("symbol.delete", &json!({"name": "B"})).unwrap(); + check(&mut s, Some("A"), "the current symbol deleted"); + store(&mut s, json!("Renamed")); + check(&mut s, Some("A"), "a stored name no symbol has"); + store(&mut s, json!(3)); + check(&mut s, Some("A"), "a stored number"); + store(&mut s, json!(["C"])); + check(&mut s, Some("A"), "a stored list"); + store(&mut s, json!("C")); + check(&mut s, Some("C"), "a stored name that is last"); +} diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index 6e933d44cd..a8392cdf50 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -133,8 +133,10 @@ pub(crate) fn chip(ui: &Ui, doc: &Document, keys: &Thumbs, r: egui::Rect, name: } } -fn current(app: &mut VectorcraftApp) -> Option { - app.run("symbol.list", json!({})).ok().and_then(|v| v["current"].as_str().map(str::to_string)) +/// The active document's current symbol (`symbol.list`'s `current`), read without running a +/// command; `None` without a document or symbols. +fn current(app: &VectorcraftApp) -> Option { + app.session.active().and_then(|st| vectorcraft_engine::cmd::current_symbol(&st.doc)) } /// Does the selection hold (in it or in its groups) a symbol instance that `wanted` takes? @@ -1189,7 +1191,7 @@ mod tests { let tile = pos2(26.0, 26.0); frame(&ctx, &mut app, vec![]); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile), button(tile, true), button(tile, false)]); - assert_eq!((editing(&app), current(&mut app)), (None, Some("Leaf".into())), "a click makes it current"); + assert_eq!((editing(&app), current(&app)), (None, Some("Leaf".into())), "a click makes it current"); let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); frame(&ctx, &mut app, vec![]); @@ -1265,7 +1267,7 @@ mod tests { let row = rows[2].1; app.run("symbol.setCurrent", json!({"name": "ant"})).unwrap(); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(row), button(row, true), button(row, false)]); - assert_eq!((editing(&app), current(&mut app)), (None, Some("Cat".into())), "{view}"); + assert_eq!((editing(&app), current(&app)), (None, Some("Cat".into())), "{view}"); let ctx2 = egui::Context::default(); crate::theme::install_fonts(&ctx2); frame(&ctx2, &mut app, vec![]); @@ -1674,7 +1676,7 @@ mod tests { app.run("edit.clear", json!({"ids": [id_b]})).unwrap(); // Currently "B" is the current symbol - assert_eq!(current(&mut app), Some("B".to_string())); + assert_eq!(current(&app), Some("B".to_string())); let mut h = egui_kittest::Harness::builder().with_size(vec2(260.0, 400.0)).with_accessibility_check(false).build_ui_state( |ui, app: &mut VectorcraftApp| { @@ -1834,4 +1836,135 @@ mod tests { let (left, reserve) = room.expect("the row was drawn"); assert!(left >= reserve, "{left} pt left after the symbol controls, {reserve} pt reserved"); } + + /// The current symbol as `symbol.list` answers it, read by running the command. + fn listed_current(app: &mut VectorcraftApp) -> Option { + app.run("symbol.list", json!({})).ok().and_then(|v| v["current"].as_str().map(str::to_string)) + } + + fn store_current(app: &mut VectorcraftApp, v: Value) { + Arc::make_mut(&mut app.session.doc_mut().unwrap().doc).unknown.insert("currentSymbol".into(), v); + } + + /// The panel's current symbol is the one `symbol.list` answers: with no document, with no + /// symbols, with several symbols, with an instance of another symbol selected, and with a + /// stored name no symbol has. + #[test] + fn current_is_the_current_symbol_list_answers() { + fn check(app: &mut VectorcraftApp, want: Option<&str>, case: &str) { + let read = current(app); + assert_eq!(read.as_deref(), want, "{case}"); + assert_eq!(read, listed_current(app), "{case}: symbol.list"); + } + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + check(&mut app, None, "no document"); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + check(&mut app, None, "a document without symbols"); + for (name, x) in [("Leaf", 10), ("Dot", 80), ("Star", 150)] { + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 30, "height": 30})).unwrap(); + app.run("symbol.new", json!({"name": name})).unwrap(); + } + check(&mut app, Some("Star"), "several symbols, the newest current"); + app.run("symbol.setCurrent", json!({"name": "Leaf"})).unwrap(); + check(&mut app, Some("Leaf"), "the first symbol made current"); + let dot = instance_of(&app, "Dot").expect("a Dot instance"); + app.run("select.set", json!({"ids": [dot.0]})).unwrap(); + check(&mut app, Some("Leaf"), "an instance of Dot selected"); + app.run("symbol.setCurrent", json!({"name": "Dot"})).unwrap(); + check(&mut app, Some("Dot"), "a symbol that is not first"); + store_current(&mut app, json!("Gone")); + check(&mut app, Some("Leaf"), "a stored name no symbol has"); + store_current(&mut app, json!(7)); + check(&mut app, Some("Leaf"), "a stored value that is not a name"); + } + + /// Idle frames of the panel and of its open menu run no command (`symbol.list` included), so + /// they leave `run_count`, which the native menus watch, as it was. + #[test] + fn idle_frames_of_the_panel_and_its_menu_run_no_command() { + let mut app = leaf_and_dot(); + let ctx = egui::Context::default(); + frame(&ctx, &mut app, vec![]); + let commands = app.run_count; + frame(&ctx, &mut app, vec![]); + frame(&ctx, &mut app, vec![]); + assert_eq!(app.run_count, commands, "the panel"); + let menu_ctx = egui::Context::default(); + menu_frame(&menu_ctx, &mut app, vec![]); + menu_frame(&menu_ctx, &mut app, vec![]); + assert_eq!(app.run_count, commands, "the panel menu"); + assert_eq!(current(&app).as_deref(), Some("Dot")); + } + + /// CPU time of this thread in nanoseconds where the system reports it (Linux), else `None`. + fn thread_cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() + } + + /// Time reading the current symbol of a document with 200 symbols and 50,000 objects (5,000 of + /// them instances): by running `symbol.list` and by [`current`]. Per run, + /// `symbol.list` reads 20 times and `current` 200,000 times (so the thread's CPU clock, which + /// advances in steps of a few milliseconds, sees it); the two sides alternate, and the median + /// time per read of 7 runs is printed. + /// Run with `cargo test --release -p vectorcraft-ui-egui --lib current_symbol_read_timing -- --ignored --nocapture`. + #[test] + #[ignore = "manual timing probe; performance depends on machine load"] + fn current_symbol_read_timing() { + const SYMBOLS: usize = 200; + const OBJECTS: usize = 50_000; + const INSTANCES: usize = 5_000; + const LIST_READS: u32 = 20; + const READS: u32 = 200_000; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 2000, "height": 2000})).unwrap(); + for i in 0..SYMBOLS { + app.run("shape.rectangle", json!({"x": i % 40 * 40, "y": i / 40 * 40, "width": 30, "height": 30})).unwrap(); + app.run("symbol.new", json!({"name": format!("S{i}")})).unwrap(); + } + let rect = app.run("shape.rectangle", json!({"x": 0, "y": 400, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + let rect = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(rect)).cloned().unwrap(); + app.session + .edit("Fill", |d, _| { + let layer = d.layers[0].id; + for i in 0..OBJECTS - SYMBOLS - 1 { + let id = d.alloc_id(); + let node = if i < INSTANCES - SYMBOLS { + let at = vectorcraft_geom::Vec2::new((i % 100) as f64 * 20.0, 600.0 + (i / 100) as f64 * 20.0); + Node::new(id, NodeKind::SymbolInstance { symbol: format!("S{}", i % SYMBOLS), xf: vectorcraft_geom::Affine::translate(at) }) + } else { + let mut n = rect.clone(); + n.id = id; + n + }; + d.insert(Some(layer), usize::MAX, node)?; + } + Ok(()) + }) + .unwrap(); + app.run("symbol.setCurrent", json!({"name": "S7"})).unwrap(); + let mut nodes = 0; + app.session.active().unwrap().doc.walk(|_| nodes += 1); + assert_eq!(listed_current(&mut app), current(&app)); + let mut time = |reads: u32, f: &mut dyn FnMut(&mut VectorcraftApp) -> Option| { + let (cpu, wall) = (thread_cpu_ns(), std::time::Instant::now()); + for _ in 0..reads { + assert_eq!(f(&mut app).as_deref(), Some("S7")); + } + let ns = thread_cpu_ns().zip(cpu).map_or_else(|| wall.elapsed().as_nanos(), |(b, a)| b - a); + ns as f64 / f64::from(reads) / 1000.0 + }; + let (mut base, mut new) = (vec![], vec![]); + for _ in 0..7 { + base.push(time(LIST_READS, &mut listed_current)); + new.push(time(READS, &mut |app| current(app))); + } + let median = |v: &mut Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + let clock = if thread_cpu_ns().is_some() { "thread CPU time" } else { "wall-clock time" }; + eprintln!("{SYMBOLS} symbols, {nodes} nodes; {clock} per read, median of 7 runs"); + eprintln!("symbol.list ({LIST_READS} reads a run): {:>12.1} us {base:.1?}", median(&mut base)); + eprintln!("current ({READS} reads a run): {:>12.4} us {new:.4?}", median(&mut new)); + } } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..ceb5ea7d0d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1054,6 +1054,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Symbols panel context menu** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): right-clicking a symbol in thumbnail view or list view displays a context menu with Place Symbol Instance (passes view center or artboard center), Edit Symbol, Duplicate Symbol, Delete Symbol, Break Link to Symbol (enabled when canvas selection includes instances of this symbol), and Select All Instances. Right-clicking an unselected symbol selects it first (`symbol.setCurrent`). Tests: `panels::symbols::tests::right_click_context_menu_in_symbols_panel_runs_actions`. - **Symbols › Select All Unused** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), #4918): the Symbols panel menu's Select All Unused shows the symbols nothing places selected (`symbol.unused`): instances in the art (opacity masks included), graph designs, pattern tiles and brush art count, and so do instances in a used symbol's art. Delete Symbol, the button or the menu item, then asks "Delete the selected symbols?" once and deletes those still unused in one undo step (`symbol.delete {names}`); Alt-click on the button deletes them without asking, and a click on a symbol picks just it again. Tests: `tests::brushsym::symbol_unused_lists_the_symbols_nothing_places_and_delete_takes_several`, `panels::symbols::tests::select_all_unused_picks_the_unused_symbols_and_delete_deletes_them`, `dialogs::symbol_delete::tests::several_symbols_get_the_plural_question`. - **Symbols › Sort by Name and the list views** ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Sort by Name puts the symbols in alphabetical order (`symbol.sortByName`), and its Thumbnail View, Small List View and Large List View show them as thumbnails, in a compact list or in a list with larger thumbnails. VectorCraft's own rules: the sort ignores case and keeps names that differ only in case in their order; it changes the document's order, which `symbol.list` reports, as one undo step, keeps the current symbol and adds no undo step when the symbols are already in order; Thumbnail View is the default, Small List View has 18-point rows with 14-point thumbnails and Large List View 26-point rows with 22-point thumbnails, and a click or double-click on a symbol does the same in every view. `ui.panelView` sets the view of the Symbols panel, and of the Swatches and Graphic Styles panels, as their panel menus do. Tests: `tests::brushsym::symbol_sort_by_name_orders_the_symbols_in_one_undo_step`, `panels::symbols::tests::sort_by_name_and_the_small_and_large_list_views`, `panels::symbols::tests::panel_view_sets_the_view_of_each_panel`. + - **The Symbols panel reads its current symbol from the document:** the Symbols panel and its panel menu read the current symbol on each frame without running `symbol.list`, which counts every symbol's instances by walking the whole document. The current symbol they show and act on is the one `symbol.list` reports, and an idle frame of the panel or its menu runs no command, so on macOS the native menu is not brought up to date on every frame while the panel is open. In a document with 200 symbols and 50,000 objects, the read takes 0.035 µs instead of 48.5 ms in a release build (thread CPU time on Linux, median of 7 runs); in a small document the difference is too small to notice. Tests: `tests::brushsym::current_symbol_is_the_current_symbol_list_answers`, `panels::symbols::tests::current_is_the_current_symbol_list_answers`, `panels::symbols::tests::idle_frames_of_the_panel_and_its_menu_run_no_command`; the timing probe is `panels::symbols::tests::current_symbol_read_timing`. - **Expand of symbol instances:** Object › Expand turns selected symbol instances (without effects, not in perspective, in groups or placed documents too) into their art as Break Link to Symbol places it, one level deep, as one undo step; the Expand dialog's Fill and Stroke reach that art (`object.expand`, `crates/engine/src/tests/expand_symbols.rs`; estimated, score unchanged). - **Reset Transformation** ([Transform symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/transform-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Reset Transformation and the Control bar's Reset, shown while symbol instances are selected, give the selected instances their symbol's own scale again, without rotation or shear, as one undo step (`symbol.instance.resetTransform`); an instance in perspective is left as it is. VectorCraft's own rules: each instance keeps the center of its bounding box in place, reflection is removed too, and the menu item and the button are enabled only while a selected instance would change. Tests: `tests::brushsym::reset_transformation_restores_the_symbols_scale_and_keeps_the_center`, `reset_transformation_keeps_the_center_of_art_away_from_the_origin`, `reset_transformation_ignores_a_stored_size_that_is_not_positive`, `reset_transformation_leaves_unchanged_instances_and_refuses_bad_ids`, `panels::symbols::tests::reset_transformation_is_enabled_for_a_transformed_instance_and_resets_it`. - **Expand of dimensions:** Object › Expand, Expand Appearance, Create Outlines and Outline Stroke turn a dimension whose art they change into a plain group of that art, which stays as it is through later moves, scales and edits of what it measured; undo gives the live dimension back (`crates/engine/tests/it/dimensions.rs`; VectorCraft's own rule; estimated, score unchanged). From 69b4f3ae968ae074895f96d4563642874a0c004c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 05:34:43 -0800 Subject: [PATCH 23/31] 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 24/31] 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 756341ddc96c8d7538f10f88b4af8af6519bae46 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 05:41:04 -0800 Subject: [PATCH 25/31] Character panel: work out the selected stories once, not once per field With the Selection tool, every Character and Paragraph field read its value through selected_stories, which walked the selected objects and looked up each type object's story again. With the default panels open that was 24 builds of the same list per frame. selected_stories and selected_story_texts now keep the last list, with the document (a held Weak keeps its address from being reused), its revision and a copy of the selected objects. A change to any of them builds the list again. Type objects are still resolved from the current document on every read, so the panels show the same values. Tests compare the kept list with a fresh build after an edit, a reordered or replaced selection, a selection set without a new revision, a selected group and a switch to another document at the same revision; compare what both panels draw and their field values with and without the kept list; and count one build per frame. --- crates/ui-egui/src/panels/character.rs | 68 +++++++- crates/ui-egui/src/panels/character/tests.rs | 157 +++++++++++++++++++ docs/target-app-parity.md | 1 + 3 files changed, 221 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index 746a8fbdf4..e9c497a4ad 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -2,14 +2,17 @@ //! scale, baseline shift, character rotation, the anti-aliasing method and the All Caps, Small Caps, //! Superscript, Subscript, Underline and Strikethrough toggles and the Language menu. +use std::cell::RefCell; use std::collections::HashSet; -use std::sync::{Mutex, OnceLock}; +use std::rc::Rc; +use std::sync::{Arc, Mutex, OnceLock, Weak}; use egui::{Key, Ui, vec2}; use serde_json::{Value, json}; use vectorcraft_doc::setup::{LANGUAGES, char_language_name}; use vectorcraft_doc::text::TypeAntiAlias; use vectorcraft_doc::{CharStyle, NodeId, NodeKind}; +use vectorcraft_engine::DocState; use vectorcraft_tools::{Mods, ToolKey}; use super::{pstate, set_pstate}; @@ -589,7 +592,62 @@ pub(crate) fn text_story(app: &VectorcraftApp) -> Option> { /// in selected groups, each with every frame of its threaded story (locked and hidden frames /// included), each once, the frames of a story in thread order. pub(crate) fn selected_stories(app: &VectorcraftApp) -> Vec { - let Some(st) = app.session.active() else { return Vec::new() }; + app.session.active().map_or_else(Vec::new, |st| story_frames(st).to_vec()) +} + +/// The last list [`selected_stories`] worked out, with the document version (its address, which +/// the held `Weak` keeps from being reused, and its revision) and the selected objects it was +/// worked out for. The Character and Paragraph panels read the list once for each field they show. +struct StoryFrames { + doc: Weak, + revision: u64, + selection: Vec, + frames: Rc<[NodeId]>, +} + +thread_local! { + static STORY_FRAMES: RefCell> = const { RefCell::new(None) }; +} + +#[cfg(test)] +thread_local! { + /// How many times [`build_selected_stories`] ran on this thread. + static STORY_BUILDS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Whether [`story_frames`] builds the list on every read instead of keeping it. + static STORIES_UNKEPT: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// [`selected_stories`] of `st`: the kept list while `st`'s document, revision and selected +/// objects are the ones it was worked out for, else a new one, kept in its place. +fn story_frames(st: &DocState) -> Rc<[NodeId]> { + #[cfg(test)] + if STORIES_UNKEPT.get() { + return build_selected_stories(st).into(); + } + STORY_FRAMES.with_borrow_mut(|kept| { + if let Some(k) = kept.as_ref() + && k.revision == st.revision + && k.doc.strong_count() > 0 + && std::ptr::eq(k.doc.as_ptr(), Arc::as_ptr(&st.doc)) + && k.selection == st.selection.objects + { + return k.frames.clone(); + } + let frames: Rc<[NodeId]> = build_selected_stories(st).into(); + *kept = Some(StoryFrames { + doc: Arc::downgrade(&st.doc), + revision: st.revision, + selection: st.selection.objects.clone(), + frames: frames.clone(), + }); + frames + }) +} + +/// The list [`selected_stories`] describes, worked out from `st`'s selection. +fn build_selected_stories(st: &DocState) -> Vec { + #[cfg(test)] + STORY_BUILDS.set(STORY_BUILDS.get() + 1); let mut frames = Vec::new(); let mut taken = HashSet::new(); for selected in st.selection.objects.iter().filter_map(|id| st.doc.node(*id)) { @@ -609,9 +667,9 @@ pub(crate) fn selected_stories(app: &VectorcraftApp) -> Vec { /// The type objects of [`selected_stories`]. pub(crate) fn selected_story_texts(app: &VectorcraftApp) -> Vec<&vectorcraft_doc::TextObject> { let Some(st) = app.session.active() else { return Vec::new() }; - selected_stories(app) - .into_iter() - .filter_map(|id| match st.doc.node(id).map(|n| &n.kind) { + story_frames(st) + .iter() + .filter_map(|&id| match st.doc.node(id).map(|n| &n.kind) { Some(NodeKind::Text(t)) => Some(t.as_ref()), _ => None, }) diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index 1e3e6acec4..4b0e96679f 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -1971,3 +1971,160 @@ fn selected_stories_list_each_frame_once() { app.run("select.set", json!({"ids": []})).unwrap(); assert!(selected_stories(&app).is_empty()); } + +/// Check that the kept list of the selected stories, and the type objects it resolves to, are the +/// ones a fresh build works out. +fn assert_stories_are_fresh(app: &VectorcraftApp, what: &str) { + let st = app.session.active().unwrap(); + let fresh = build_selected_stories(st); + assert_eq!(selected_stories(app), fresh, "{what}"); + let texts = selected_story_texts(app); + let expected: Vec<_> = fresh + .iter() + .filter_map(|id| match &st.doc.node(*id)?.kind { + NodeKind::Text(t) => Some(t.as_ref()), + _ => None, + }) + .collect(); + assert_eq!(texts.len(), expected.len(), "{what}: type objects"); + assert!(texts.iter().zip(&expected).all(|(t, e)| std::ptr::eq(*t, *e)), "{what}: the current document's type objects, in order"); +} + +/// The kept list of the selected stories follows every change it is worked out from: an edit, a +/// new selection (in another order, or as long with other objects, also without a new revision), +/// a selected group and a switch to another document at the same revision. +#[test] +fn kept_selected_stories_follow_the_document_and_the_selection() { + let (mut app, [a, b, c], other) = story_selected_in_its_first_frame(); + assert_stories_are_fresh(&app, "a frame of a story"); + let builds = STORY_BUILDS.get(); + assert_eq!(selected_stories(&app), [a, b, c].map(NodeId).to_vec()); + assert_eq!(STORY_BUILDS.get(), builds, "a second read keeps the list"); + + app.run("text.setStyle", json!({"size": 9})).unwrap(); + assert_stories_are_fresh(&app, "after an edit"); + app.run("select.set", json!({"ids": [other, a]})).unwrap(); + assert_stories_are_fresh(&app, "two stories"); + app.run("select.set", json!({"ids": [a, other]})).unwrap(); + assert_stories_are_fresh(&app, "the same objects in another order"); + app.run("select.set", json!({"ids": [other, b]})).unwrap(); + assert_stories_are_fresh(&app, "as many other objects"); + app.session.doc_mut().unwrap().selection.objects = vec![NodeId(other)]; + assert_stories_are_fresh(&app, "a new selection at the same revision"); + assert_eq!(selected_stories(&app), vec![NodeId(other)]); + + app.run("select.set", json!({"ids": [other, a]})).unwrap(); + let group = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [group]})).unwrap(); + assert_stories_are_fresh(&app, "a selected group"); + + let revision = app.session.active().unwrap().revision; + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let only = app.run("text.create", json!({"x": 20, "y": 50, "text": "Only", "size": 12})).unwrap()["id"].as_u64().unwrap(); + let st = app.session.doc_mut().unwrap(); + st.selection.objects = vec![NodeId(group)]; + st.revision = revision; + assert_stories_are_fresh(&app, "another document with the first one's selection and revision"); + assert_ne!(selected_stories(&app), [a, b, c, other].map(NodeId).to_vec()); + app.run("select.set", json!({"ids": [only]})).unwrap(); + assert_stories_are_fresh(&app, "the other document's own type"); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_stories_are_fresh(&app, "back in the first document"); + + app.run("select.set", json!({"ids": []})).unwrap(); + assert!(selected_stories(&app).is_empty()); + assert!(selected_story_texts(&app).is_empty()); +} + +/// What the Character and Paragraph panels draw, and the values of their fields, with the list of +/// the selected stories kept and with it built for every read. +fn panels_kept_and_unkept(app: &mut VectorcraftApp) -> [(Vec, String); 2] { + let read = |app: &mut VectorcraftApp, unkept: bool| { + STORIES_UNKEPT.set(unkept); + let ctx = egui::Context::default(); + let mut texts = vec![]; + for _ in 0..3 { + texts = super::super::tests_appearance::frame_events(&ctx, app, vec![], |app, ui| { + show(app, ui); + crate::panels::paragraph::show(app, ui); + }); + } + // A rect's position can be NaN, which `Rect`'s `==` refuses to compare. + let texts: Vec = texts.iter().map(|(text, rect)| format!("{text} {rect:?}")).collect(); + let fields = format!( + "{:?} {:?}", + [ + shared_effective(app, |s| s.size), + shared_effective(app, |s| s.h_scale), + shared_effective(app, |s| s.v_scale), + shared_effective(app, |s| s.baseline_shift), + shared_leading(app), + shared(app, |s| s.tracking), + ], + ( + shared(app, |s| (s.font_family.clone(), s.font_style.clone())), + shared(app, |s| (s.all_caps, s.underline, s.strikethrough, s.position)), + selected_fonts(app), + any_style(app, |s| s.underline), + selected_stories(app), + selected_story_texts(app).len(), + text_style(app).map(|(c, p)| (c.size, p.left_indent)), + ) + ); + STORIES_UNKEPT.set(false); + (texts, fields) + }; + [read(app, true), read(app, false)] +} + +/// The panels show the same thing whether the list of the selected stories is kept or worked out +/// for each field: with nothing selected, one story, several stories with mixed values and a +/// Type tool selection inside one story. +#[test] +fn panels_show_the_same_with_the_kept_selected_stories() { + let (mut app, [a, b, c], other) = story_selected_in_its_first_frame(); + let same = |app: &mut VectorcraftApp, what: &str| { + let [unkept, kept] = panels_kept_and_unkept(app); + assert_eq!(unkept.1, kept.1, "{what}: field values"); + assert_eq!(unkept.0, kept.0, "{what}: what the panels draw"); + unkept.1 + }; + app.run("select.set", json!({"ids": []})).unwrap(); + same(&mut app, "nothing selected"); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let one = same(&mut app, "one story"); + app.run("text.setStyle", json!({"ids": [c], "size": 20, "tracking": 50})).unwrap(); + app.run("text.setFormat", json!({"ids": [b], "underline": true, "hScale": 120})).unwrap(); + app.run("select.set", json!({"ids": [other, a]})).unwrap(); + let mixed = same(&mut app, "several stories with mixed values"); + assert_ne!(one, mixed); + app.session.select_tool("type", Default::default()).unwrap(); + app.session.set_tool_option("textSelection", &json!({"editing": a, "anchor": 4, "caret": 15})); + assert_eq!(text_editing(&app), Some((NodeId(a), 4, 15))); + same(&mut app, "a Type tool selection inside one story"); +} + +/// One frame of the Character and Paragraph panels works out the selected stories once, though +/// many of their fields read them; a change to the document works them out again. +#[test] +fn panels_work_out_the_selected_stories_once_per_frame() { + let (mut app, [a, ..], other) = story_selected_in_its_first_frame(); + app.run("select.set", json!({"ids": [other, a]})).unwrap(); + let ctx = egui::Context::default(); + let frame = |app: &mut VectorcraftApp| { + let builds = STORY_BUILDS.get(); + super::super::tests_appearance::frame_events(&ctx, app, vec![], |app, ui| { + show(app, ui); + crate::panels::paragraph::show(app, ui); + }); + STORY_BUILDS.get() - builds + }; + frame(&mut app); + app.run("text.setStyle", json!({"size": 9})).unwrap(); + assert_eq!(frame(&mut app), 1, "one build after an edit"); + assert_eq!(frame(&mut app), 0, "nothing changed"); + STORIES_UNKEPT.set(true); + let reads = frame(&mut app); + STORIES_UNKEPT.set(false); + assert!(reads > 1, "the fields read the list {reads} times"); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..901b368b2c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1113,6 +1113,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - With the whole story of threaded text selected by Select All, the Character, Paragraph, OpenType, Tabs and Text Styles panels, the Justification dialog and the font menu change the frames that are in the edited frame's thread at the time of the change, locked and hidden frames included. A frame that has left the thread is not changed, and a frame added to the thread is (VectorCraft's own behavior; `panels::character::tests::story_changes_follow_the_edited_frames_thread_after_the_first_saved_frame_leaves`, `story_changes_leave_out_a_frame_that_left_and_take_in_a_frame_that_joined`, `story_changes_stay_in_the_edited_frame_once_its_thread_is_removed`, `story_changes_take_in_locked_and_hidden_frames`). - With the Selection tool, a Character or Paragraph panel change to a selected frame of threaded text changes every frame of its story, locked and hidden frames included, as one undo step. The anti-aliasing method, Variable Font axes, the Tabs panel's tab stops and both panels' Reset Panel change the whole story too, and the panels show a value only when every frame of the story has it. A story selected through several of its frames or through a group is changed once, and other type keeps its formatting (VectorCraft's own behavior; `panels::character::tests::selection_tool_changes_reach_every_frame_of_the_story`, `selection_tool_fields_read_every_frame_of_the_story`, `selected_stories_list_each_frame_once`, `panels::paragraph::tests::selection_tool_paragraph_changes_reach_every_frame_of_the_story`, `panels::tabs::tests::selection_tool_tab_stops_reach_every_frame_of_the_story`). - With the Selection tool, the Justification dialog, the OpenType panel, a Character or Paragraph Styles row and Type › Bullets and Numbering › Convert to Text also change every frame of a selected story, locked and hidden frames included, as one undo step. The Justification dialog acts on the story's frames as they were when it opened. When the frames differ, the OpenType panel's Figure menu shows Mixed, its checkboxes show a dash (a click turns the feature on everywhere), and the style panels highlight no row; a row shows "+" when any frame overrides its style (VectorCraft's own behavior; `dialogs::justification::tests::selection_tool_justification_reaches_every_frame_of_the_story`, `panels::opentype::tests::selection_tool_features_reach_every_frame_of_the_story`, `panels::text_styles::tests::selection_tool_styles_reach_every_frame_of_the_story`, `panels::paragraph::tests::selection_tool_convert_to_text_takes_every_frame_of_the_story`). + - With the Selection tool, the Character and Paragraph panels work out the list of selected stories once, not once for each of the 24 fields they show by default, and reuse it until the document, its revision or the selected objects change. The panels show the same values. With 200 threads of 10 frames and 2,000 point type objects selected, one frame of both panels takes 21.7 ms of CPU time in a release build instead of 81.7 ms (`panels::character::tests::kept_selected_stories_follow_the_document_and_the_selection`, `panels_show_the_same_with_the_kept_selected_stories` and `panels_work_out_the_selected_stories_once_per_frame`). - Switching from a Type tool to the Eyedropper keeps a whole story selected by Select All: a pick applies to the text of every frame as one undo step, and switching back restores the story selection (VectorCraft's own behavior; `textedit::switching_to_the_eyedropper_keeps_the_whole_story_selected`). - While the Type tool edits text, a character typed with AltGr is typed and runs no command. Firefox on Windows reports AltGr as Ctrl and Alt held, so in the web build AltGr+L (ł on a Polish layout) does not also open Layer Options for a new layer, and AltGr+Q (@ on a German layout) does not also run Reset Tracking and Kerning. A Ctrl+Alt chord that types no character runs its command. - On a layout without Latin letters, a one-key shortcut goes by the position of the key that typed the character, in the web build too, where the character arrives before its key press: on a Russian layout the P key (`з`) chooses the Pen, and two keys pressed in one frame each run their own shortcut. From 70fdab8445a0a172107bf38f1d9903a3b16786d1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 05:50:00 -0800 Subject: [PATCH 26/31] 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, ,