diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d7f5b4e77b..ddb84d64b2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -64,6 +64,9 @@ jobs: vectorcraft vectorcraft-web vectorcraft-cli vectorcraft-mcp xtask (rest) (always) + # The warm build runs as one `cache warm /6` leg per shard, in parallel (each builds what + # its shard builds), and `cache warm` puts their files into the one entry it saves. + warm-split: true # The dependency cache also keeps the compiled workspace crates and test executables, so a # pull request's shards rebuild only the crates its changes reach. Each main run's `cache # warm` leg saves a rolling entry of its own, every leg restores the newest one, and @@ -82,14 +85,17 @@ jobs: # the old entries when the `cache warm` leg starts saving (scripts/ci-clear-rolling-cache.py). # When the leg fails or is canceled, before its save or during it, this job fails too, so "Re-run # failed jobs" runs it again beside the re-run leg. The leg starts after `gate / select legs` and a - # free runner: the script fails when the leg has not started within 120 minutes, and then waits - # up to 160 minutes from the leg's start. This job's timeout is longer than both together, so the - # script reports a leg that starts late with its own error before the job times out. + # free runner, and with `warm-split` after every `cache warm /6` leg. The script suspends its + # start deadline while any split leg is queued or running, then allows 180 minutes from the last + # split completion for the saving leg to start. Without split legs, it allows 180 minutes from + # the script's start. A failed split leg fails this job too. The script then waits up to 160 + # minutes from the saving leg's start. GitHub's 360-minute job limit can end this job before the + # script's deadlines expire when split builds or runner waits take too long. cold-cache-clear: name: cold cache clear if: github.event_name == 'schedule' runs-on: ubuntu-24.04 - timeout-minutes: 290 + timeout-minutes: 360 permissions: actions: write steps: diff --git a/assets/icons/dc-free-distort.svg b/assets/icons/dc-free-distort.svg index 9013cf97ae..3a6ea4451d 100644 --- a/assets/icons/dc-free-distort.svg +++ b/assets/icons/dc-free-distort.svg @@ -1,4 +1,4 @@ - + diff --git a/crates/effects/src/addons/halftone.rs b/crates/effects/src/addons/halftone.rs index 9b5771e7bd..371f664781 100644 --- a/crates/effects/src/addons/halftone.rs +++ b/crates/effects/src/addons/halftone.rs @@ -19,7 +19,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::color::{BlendMode, Color, Paint}; use vectorcraft_doc::{Appearance, Document, Node, NodeId}; use vectorcraft_geom::hit::fill_contains; -use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, shapes}; +use vectorcraft_geom::{Affine, BezPath, CubicBez, FillRule, PathData, Point, Rect, shapes}; use vectorcraft_pathops::{self as po, BoolOp}; use crate::catalog::{EffectInfo, Lengths}; @@ -43,7 +43,7 @@ pub(crate) fn catalog() -> Vec { id: HALFTONE, label: "Vector Halftone…", menu: &["Effect", "Color Effects"], - params: "{shape: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\" (circle), frequency: lines per inch 1..300 (20), angle: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode: \"mono\"|\"cmyk\" (mono), color: mono dot colour (\"#000000\"), fromArt: bool (false; mono: each dot takes the art's colour under it), invert: bool (false; dots for light tones), clip: bool (true; the dots clipped to the art's outline)} draws the object as vector halftone dots sized by its tone, as object.vectorHalftone makes them (CMYK screens multiply); the object is sampled as drawn with its other effects; at most 100000 cells per screen, past that the object draws as it is", + params: "{shape: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\"|\"euclidean\"|\"elliptical\" (circle; euclidean: round dots that meet corner to corner at 50%, then round holes; elliptical: long dots that join into chains at 40% and on all sides at 60%, then long holes), frequency: lines per inch 1..300 (20), angle: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode: \"mono\"|\"cmyk\" (mono), color: mono dot colour (\"#000000\"), fromArt: bool (false; mono: each dot takes the art's colour under it), invert: bool (false; dots for light tones), clip: bool (true; the dots clipped to the art's outline)} draws the object as vector halftone dots sized by its tone, as object.vectorHalftone makes them (CMYK screens multiply); the object is sampled as drawn with its other effects; at most 100000 cells per screen, past that the object draws as it is", defaults: json!({"shape": "circle", "frequency": 20.0, "angle": 45.0, "mode": "mono", "color": "#000000", "fromArt": false, "invert": false, "clip": true}), raster: false, lengths: Lengths::default(), @@ -63,6 +63,12 @@ pub enum DotShape { Square, Diamond, Line, + /// Round dots that grow into squares meeting corner to corner at 50% (a checkerboard), then + /// round holes, as the Euclidean spot function draws them. + Euclidean, + /// Elongated dots that join along their long side at 40% into chains, along their short side + /// at 60%, then elongated holes. + Elliptical, } impl DotShape { @@ -73,6 +79,8 @@ impl DotShape { "square" => DotShape::Square, "diamond" => DotShape::Diamond, "line" | "lines" => DotShape::Line, + "euclidean" => DotShape::Euclidean, + "elliptical" => DotShape::Elliptical, _ => return None, }) } @@ -94,10 +102,227 @@ impl DotShape { DotShape::Diamond => square(s * t.sqrt()).transformed(Affine::rotate(std::f64::consts::FRAC_PI_4)), // Cells along a row join into a line as thick as the tone. DotShape::Line => shapes::rectangle(Rect::from_center_size(Point::ZERO, (s * 1.001, s * t))), + DotShape::Euclidean => PathData::from_bezpath(&spot(t, s / 2.0, SpotKind::Euclidean)), + DotShape::Elliptical => PathData::from_bezpath(&spot(t, s / 2.0, SpotKind::Elliptical)), } } } +/// The Elliptical dot's height over its width: a dot as wide as its cell covers 40% of it +/// (π × ratio / 4 = 0.4 of a quadrant). +const ELLIPTICAL_RATIO: f64 = 1.6 / std::f64::consts::PI; + +/// The Elliptical dot's middle-tone cut in a quadrant of half side 1, the line +/// `ELLIPTICAL_CUT.0 × x + y = ELLIPTICAL_CUT.1`. It meets the side x = 1 at y = 0.25 and the y +/// axis at 0.75 and runs through the quadrant's center, so the dot it cuts at 50% is its own +/// complement: the dark bridges across the x side from 40%, and the y side stays light until 60%. +const ELLIPTICAL_CUT: (f64, f64) = (0.5, 0.75); + +/// Steps of the table of dot sizes per tone ([`dot_sizes`]) over tones 0..0.5. +const SIZE_STEPS: usize = 512; + +static EUCLIDEAN: OnceLock> = OnceLock::new(); +static ELLIPTICAL: OnceLock> = OnceLock::new(); + +/// The two spot-function dots. +#[derive(Clone, Copy)] +enum SpotKind { + Euclidean, + Elliptical, +} + +impl SpotKind { + /// The first quadrant of the dot of width `a` in a quadrant of half side 1. + fn quadrant(self, a: f64) -> Vec { + match self { + SpotKind::Euclidean => quadrant(a, a, 1.0), + SpotKind::Elliptical => elliptical_quadrant(a), + } + } + + /// The width at which the dot covers half the cell. + fn max_size(self) -> f64 { + match self { + SpotKind::Euclidean => 1.0, + SpotKind::Elliptical => ELLIPTICAL_CUT.1 / ELLIPTICAL_RATIO, + } + } + + fn table(self) -> &'static OnceLock> { + match self { + SpotKind::Euclidean => &EUCLIDEAN, + SpotKind::Elliptical => &ELLIPTICAL, + } + } +} + +/// For tones `k / SIZE_STEPS × 0.5`, the width `a` of the dot of `kind` that covers that tone of the +/// cell [-1, 1]². +fn dot_sizes(kind: SpotKind) -> Vec { + (0..=SIZE_STEPS) + .map(|k| { + // A quadrant of the cell has area 1. + let target = k as f64 / SIZE_STEPS as f64 * 0.5; + let (mut lo, mut hi) = (0.0, kind.max_size()); + for _ in 0..50 { + let mid = (lo + hi) / 2.0; + if curves_area(&kind.quadrant(mid)) < target { lo = mid } else { hi = mid } + } + (lo + hi) / 2.0 + }) + .collect() +} + +/// The area between the origin and `curves`, which run from the x axis to the y axis. +fn curves_area(curves: &[CubicBez]) -> f64 { + use vectorcraft_geom::kurbo::ParamCurveArea; + curves.iter().map(|c| c.signed_area()).sum() +} + +/// Cubic curves along the ellipse with semi-axes `a`, `b` from angle `t0` to `t1`. +fn ellipse_arc(out: &mut Vec, a: f64, b: f64, t0: f64, t1: f64) { + if t1 <= t0 { + return; + } + let at = |th: f64| Point::new(a * th.cos(), b * th.sin()); + let n = ((t1 - t0) / std::f64::consts::FRAC_PI_4).ceil().max(1.0); + let d = (t1 - t0) / n; + let k = 4.0 / 3.0 * (d / 4.0).tan(); + for i in 0..n as usize { + let (u0, u1) = (t0 + d * i as f64, t0 + d * (i as f64 + 1.0)); + let (p0, p3) = (at(u0), at(u1)); + let c1 = p0 + k * vectorcraft_geom::Vec2::new(-a * u0.sin(), b * u0.cos()); + let c2 = p3 - k * vectorcraft_geom::Vec2::new(-a * u1.sin(), b * u1.cos()); + out.push(CubicBez::new(p0, c1, c2, p3)); + } +} + +/// The straight segment from `p` to `q` as a cubic curve. +fn segment(p: Point, q: Point) -> CubicBez { + CubicBez::new(p, p.lerp(q, 1.0 / 3.0), p.lerp(q, 2.0 / 3.0), q) +} + +/// The first quadrant of the Elliptical dot of width `a` (height `ELLIPTICAL_RATIO × a`) in a +/// quadrant of half side 1, from the x axis to the y axis. Up to width 1 (40%) it is the whole +/// ellipse. Wider, the ellipse is clipped to the side x = 1, which makes a bridge to the next dot +/// along x, and to the cut line [`ELLIPTICAL_CUT`], which keeps it off the y side. +fn elliptical_quadrant(a: f64) -> Vec { + use std::f64::consts::FRAC_PI_2; + let b = a * ELLIPTICAL_RATIO; + let mut out = vec![]; + if a <= 1.0 { + ellipse_arc(&mut out, a, b, 0.0, FRAC_PI_2); + return out; + } + let at = |th: f64| Point::new(a * th.cos(), b * th.sin()); + let (m, c) = ELLIPTICAL_CUT; + // The ellipse crosses the side x = 1 at angle t0. + let t0 = (1.0 / a).acos(); + // Between angles ts and te the ellipse lies beyond the cut line. + let r = (m * a).hypot(b); + let (ts, te) = if r > c { + let (phi, alpha) = (b.atan2(m * a), (c / r).acos()); + (phi - alpha, phi + alpha) + } else { + (FRAC_PI_2, FRAC_PI_2) + }; + let end = if te < FRAC_PI_2 { at(te) } else { Point::new(0.0, c) }; + out.push(segment(Point::new(1.0, 0.0), if t0 < ts || t0 >= te { at(t0) } else { Point::new(1.0, c - m) })); + if t0 >= te { + ellipse_arc(&mut out, a, b, t0, FRAC_PI_2); + return out; + } + if t0 < ts { + ellipse_arc(&mut out, a, b, t0, ts.min(FRAC_PI_2)); + if ts >= FRAC_PI_2 { + return out; + } + } + let from = out.last().map_or(Point::new(1.0, 0.0), |q| q.p3); + out.push(segment(from, end)); + ellipse_arc(&mut out, a, b, te, FRAC_PI_2); + out +} + +/// The first quadrant of the ellipse with semi-axes `a`, `b` clipped to the diamond side x + y ≤ +/// `h`, from its point on the x axis to its point on the y axis, as cubic curves. +fn quadrant(a: f64, b: f64, h: f64) -> Vec { + use std::f64::consts::FRAC_PI_2; + let at = |th: f64| Point::new(a * th.cos(), b * th.sin()); + let mut out = vec![]; + let r = a.hypot(b); + if r <= h { + ellipse_arc(&mut out, a, b, 0.0, FRAC_PI_2); + return out; + } + let (phi, alpha) = (b.atan2(a), (h / r).acos()); + let (ts, te) = (phi - alpha, phi + alpha); + let start = if ts > 0.0 { + ellipse_arc(&mut out, a, b, 0.0, ts); + at(ts) + } else { + Point::new(h, 0.0) + }; + let end = if te < FRAC_PI_2 { at(te) } else { Point::new(0.0, h) }; + out.push(segment(start, end)); + ellipse_arc(&mut out, a, b, te, FRAC_PI_2); + out +} + +/// `curves` reversed, each curve run backwards. +fn reversed(curves: &[CubicBez]) -> Vec { + curves.iter().rev().map(|c| CubicBez::new(c.p3, c.p2, c.p1, c.p0)).collect() +} + +/// `curves` with each point mapped by `f`. +fn mapped(curves: &[CubicBez], f: impl Fn(Point) -> Point) -> Vec { + curves.iter().map(|c| CubicBez::new(f(c.p0), f(c.p1), f(c.p2), f(c.p3))).collect() +} + +/// The quadrant of the `kind` spot for tone `u` (0..0.5) in a cell of half side `h`, its size from +/// the kind's table ([`dot_sizes`]). +fn spot_quadrant(u: f64, h: f64, kind: SpotKind) -> Vec { + let sizes = kind.table().get_or_init(|| dot_sizes(kind)); + let x = (u / 0.5).clamp(0.0, 1.0) * SIZE_STEPS as f64; + let i = (x.floor() as usize).min(SIZE_STEPS - 1); + let (lo, hi) = (sizes.get(i).copied().unwrap_or(0.0), sizes.get(i + 1).copied().unwrap_or(0.0)); + let a = lo + (hi - lo) * (x - i as f64); + mapped(&kind.quadrant(a), |p| Point::new(p.x * h, p.y * h)) +} + +/// A spot-function dot for tone `t` (0..1) in a cell of half side `h` centered on the origin: up to +/// half tone, the `kind` dot with the tone's area (Euclidean: a circle clipped to the cell's +/// diamond; Elliptical: an ellipse clipped to the cell's sides and its middle-tone cut); past half, +/// the cell with the dot of the opposite tone cut out at each corner, so the dark joins up and the +/// light becomes holes. +fn spot(t: f64, h: f64, kind: SpotKind) -> BezPath { + let mut bp = BezPath::new(); + let mut add = |curves: Vec, first: bool| { + for (k, c) in curves.iter().enumerate() { + if k == 0 { + if first { bp.move_to(c.p0) } else { bp.line_to(c.p0) } + } + bp.curve_to(c.p1, c.p2, c.p3); + } + }; + if t <= 0.5 { + let q1 = spot_quadrant(t, h, kind); + add(q1.clone(), true); + add(reversed(&mapped(&q1, |p| Point::new(-p.x, p.y))), false); + add(mapped(&q1, |p| Point::new(-p.x, -p.y)), false); + add(reversed(&mapped(&q1, |p| Point::new(p.x, -p.y))), false); + } else { + // Round the corners counterclockwise, each one's hole the dot of the opposite tone. + let q1 = spot_quadrant(1.0 - t.min(1.0), h, kind); + add(reversed(&mapped(&q1, |p| Point::new(h - p.x, h - p.y))), true); + add(mapped(&q1, |p| Point::new(p.x - h, h - p.y)), false); + add(reversed(&mapped(&q1, |p| Point::new(p.x - h, p.y - h))), false); + add(mapped(&q1, |p| Point::new(h - p.x, p.y - h)), false); + } + bp.close_path(); + bp +} + /// One screen: its ink and angle, and how to read its tone from a sampled pixel. struct Screen { paint: Color, @@ -399,6 +624,7 @@ pub fn halftone_art(d: &Document, n: &Node) -> Option { mod tests { use super::*; use vectorcraft_doc::Effect; + use vectorcraft_geom::Shape; /// A black square's samples: `side` points of black from (10, 10), white around it. fn black_square(side: f64, h: &Halftone) -> (Samples, Rect) { @@ -464,6 +690,73 @@ mod tests { assert_eq!(cmyk.layers(&one, Rect::new(2.0, 2.0, 18.0, 18.0), None).0.len(), 2); } + /// Is `p` (in cells of side 1) inside the dot `shape` draws for tone `t`? + fn covers(shape: DotShape, t: f64, p: (f64, f64)) -> bool { + fill_contains(&shape.path(t, 1.0).to_bezpath(), FillRule::NonZero, Point::new(p.0, p.1)) + } + + #[test] + fn spot_dots_cover_the_tone() { + for shape in [DotShape::Euclidean, DotShape::Elliptical] { + for k in 1..100 { + let t = f64::from(k) / 100.0; + let area = shape.path(t, 2.0).to_bezpath().area().abs() / 4.0; + assert!((area - t).abs() < 2e-3, "{shape:?} at {t}: {area}"); + let b = shape.path(t, 2.0).control_bounds().unwrap(); + assert!(b.x0 >= -1.0 - 1e-9 && b.x1 <= 1.0 + 1e-9 && b.y0 >= -1.0 - 1e-9 && b.y1 <= 1.0 + 1e-9, "{shape:?} at {t}: {b:?}"); + } + } + assert_eq!((DotShape::parse("Euclidean"), DotShape::parse("elliptical")), (Some(DotShape::Euclidean), Some(DotShape::Elliptical))); + } + + #[test] + fn euclidean_dots_meet_corner_to_corner_at_half() { + let s = DotShape::Euclidean; + // Round dots apart from their neighbors below half. + assert!(!covers(s, 0.45, (0.49, 0.0)) && !covers(s, 0.45, (0.0, 0.49)) && covers(s, 0.45, (0.3, 0.0))); + // At half the dot is the diamond reaching the middle of each side: a checkerboard. + for p in [(0.49, 0.0), (-0.49, 0.0), (0.0, 0.49), (0.0, -0.49)] { + assert!(covers(s, 0.5, p), "{p:?}"); + } + assert!(!covers(s, 0.5, (0.26, 0.26)) && covers(s, 0.5, (0.24, 0.24))); + // Past half the light becomes round holes at the corners. + assert!(covers(s, 0.55, (0.0, 0.499)) && covers(s, 0.55, (0.499, 0.0)) && !covers(s, 0.55, (0.49, 0.49))); + assert!(covers(s, 0.99, (0.3, 0.3))); + } + + #[test] + fn elliptical_dots_join_along_their_length_then_their_width() { + let s = DotShape::Elliptical; + // Below 40% the dots stand apart. + assert!(!covers(s, 0.38, (0.495, 0.0)) && !covers(s, 0.38, (0.0, 0.45))); + // From 40% they reach their neighbors along x, making chains, but not along y. + assert!(covers(s, 0.42, (0.495, 0.0)) && !covers(s, 0.42, (0.0, 0.45))); + // The chains are bridges as tall as the tone allows across the shared side, not single + // points: off the axis on the side x = 0.5, and on the cell's other side by symmetry. + assert!(covers(s, 0.46, (0.499, 0.03)) && covers(s, 0.46, (-0.499, -0.03)) && !covers(s, 0.46, (0.499, 0.2))); + assert!(covers(s, 0.5, (0.499, 0.12)) && !covers(s, 0.5, (0.499, 0.13)) && !covers(s, 0.5, (0.0, 0.49))); + // Up to 60% the light still runs along the top edge between the corner holes. + assert!(!covers(s, 0.55, (0.02, 0.499)) && covers(s, 0.55, (0.0, 0.3))); + // Past 60% the dark joins across the top edge too, leaving elongated holes. + assert!(covers(s, 0.65, (0.02, 0.499)) && covers(s, 0.65, (0.495, 0.0)) && !covers(s, 0.65, (0.49, 0.49))); + // The holes are longer along x than along y. + assert!(!covers(s, 0.8, (0.3, 0.49)) && covers(s, 0.8, (0.49, 0.3)), "ratio {ELLIPTICAL_RATIO}"); + // Today's Ellipse stays as it was: an ellipse 1.69 times as wide as tall. + let b = DotShape::Ellipse.path(0.3, 1.0).control_bounds().unwrap(); + assert!((b.width() / b.height() - 1.69).abs() < 1e-6, "{b:?}"); + } + + #[test] + fn spot_shapes_make_dots_through_the_screen() { + for shape in [DotShape::Euclidean, DotShape::Elliptical] { + let h = Halftone::of(&effect(json!({"frequency": 18, "shape": format!("{shape:?}")}))).unwrap(); + assert_eq!(h.shape, shape); + let (s, b) = black_square(60.0, &h); + let (layers, dots) = h.layers(&s, b, None); + assert!(layers.len() == 1 && (150..=320).contains(&dots), "{shape:?}: {dots}"); + } + } + #[test] fn the_caps_refuse_too_many_cells() { let h = Halftone::of(&effect(json!({"frequency": 300}))).unwrap(); diff --git a/crates/engine/src/cmd/halftone.rs b/crates/engine/src/cmd/halftone.rs index b54e92932c..9677f23ad6 100644 --- a/crates/engine/src/cmd/halftone.rs +++ b/crates/engine/src/cmd/halftone.rs @@ -19,7 +19,7 @@ pub fn specs() -> Vec { "Vector Halftone…", ["Object"], None, - "{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\" (circle), frequency?: lines per inch 1–300 (20), angle?: deg clockwise (45; 0: level rows of dots; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"; #rrggbbaa and #rgba are refused), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", + "{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\"|\"euclidean\"|\"elliptical\" (circle; euclidean: round dots that meet corner to corner at 50%, then round holes; elliptical: long dots that join into chains at 40% and on all sides at 60%, then long holes), frequency?: lines per inch 1–300 (20), angle?: deg clockwise (45; 0: level rows of dots; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"; #rrggbbaa and #rgba are refused), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", has_selection, halftone )] @@ -28,7 +28,9 @@ pub fn specs() -> Vec { fn halftone(s: &mut Session, p: &Value) -> Result { const C: &str = "object.vectorHalftone"; let shape = match text_param(p, "shape", C)? { - Some(v) => DotShape::parse(v).ok_or_else(|| bad(C, format!("unknown shape `{v}` (circle|ellipse|square|diamond|line)")))?, + Some(v) => { + DotShape::parse(v).ok_or_else(|| bad(C, format!("unknown shape `{v}` (circle|ellipse|square|diamond|line|euclidean|elliptical)")))? + } None => DotShape::Circle, }; let frequency = number_or(p, "frequency", 20.0, C)?; diff --git a/crates/engine/tests/it/affinity_features.rs b/crates/engine/tests/it/affinity_features.rs index 98fdbe6b23..a5bc28f24b 100644 --- a/crates/engine/tests/it/affinity_features.rs +++ b/crates/engine/tests/it/affinity_features.rs @@ -744,20 +744,41 @@ fn objects_beyond_the_document_range_are_left_out() { assert!(loaded.warnings.iter().any(|w| w.contains("beyond the document range")), "{:?}", loaded.warnings); } +/// A magenta rectangle with a Recolor adjustment (`RcRA`) attached, at `lightness`. +fn recolored(visible: bool, lightness: f64) -> F { + let mut node = rectangle(10, (0.0, 0.0), (50.0, 50.0)); + let recolor = F::Def( + 20, + vec![tag(b"RcRA")], + vec![ + (tag(b"Visi"), F::Bool(visible)), + (tag(b"AdjP"), F::Obj(tag(b"RecP"), vec![(tag(b"RecH"), F::F64(0.0)), (tag(b"RecS"), F::F64(1.0)), (tag(b"RecL"), F::F64(lightness))])), + ], + ); + if let F::Def(_, _, fields) = &mut node { + fields.push((tag(b"AdCh"), F::Shared(vec![recolor]))); + } + node +} + +fn first_fill(n: &Node) -> Paint { + let Some(AppearanceItem::Fill(fill)) = n.appearance.items.first() else { panic!("no fill: {:?}", n.appearance) }; + fill.paint.clone() +} + #[test] -fn test_af_g_symbol_fill_is_white() { - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../test.af"); - let Ok(bytes) = std::fs::read(&path) else { - return; - }; - let loaded = vectorcraft_engine::cmd::fileio::load("test.af", &bytes).unwrap(); - assert!(!loaded.preview_only, "{:?}", loaded.warnings); - let d = &loaded.doc; - // The visible "g41" group holds the "g" symbol (path43). - let g41 = all(d).into_iter().find(|n| n.visible && n.name.as_deref() == Some("g41")).expect("visible g41 group must be present"); - let path43 = g41.children().and_then(|c| c.iter().find(|n| n.name.as_deref() == Some("path43"))).expect("path43 inside g41 must be present"); - let Some(AppearanceItem::Fill(fill)) = path43.appearance.items.first() else { - panic!("path43 has no fill: {:?}", path43.appearance); - }; - assert_eq!(fill.paint, Paint::solid(Color::rgb(1.0, 1.0, 1.0)), "The 'g' symbol must have a white fill in test.af, got {:?}", fill.paint); +fn attached_recolor_adjustments_recolor_the_shape() { + // Lightness 1 recolors to white. + let loaded = open("recolor.af", &canvas_with(vec![recolored(true, 1.0)], None)); + assert!(!loaded.warnings.iter().any(|w| w.contains("attached to other layers")), "{:?}", loaded.warnings); + let rect = named(&loaded.doc, "Magenta box"); + assert!(rect.appearance.effects.is_empty()); + assert_eq!(first_fill(rect), Paint::solid(Color::rgb(1.0, 1.0, 1.0))); + // Lightness 0.5 at hue 0 and full saturation is pure red. + let d = open("red.af", &canvas_with(vec![recolored(true, 0.5)], None)).doc; + let [r, g, b, a] = pixel(&d, 25, 25); + assert!(r > 250 && g < 5 && b < 5 && a == 255, "{:?}", [r, g, b, a]); + // A hidden adjustment leaves the shape as it is. + let d = open("hidden.af", &canvas_with(vec![recolored(false, 1.0)], None)).doc; + assert_eq!(first_fill(named(&d, "Magenta box")), Paint::solid(Color::cmyk(0.0, 1.0, 0.0, 0.0))); } diff --git a/crates/pathops/README.md b/crates/pathops/README.md index 2397045a84..f41873333c 100644 --- a/crates/pathops/README.md +++ b/crates/pathops/README.md @@ -59,7 +59,7 @@ pub fn interior_point(path: &PathData) -> Option; Unlike `regions`, which splits the filled areas of closed shapes, `live_paint` treats every path as an edge, open paths included. Three crossing lines enclose a triangle, a line across a rectangle splits it in two, and an area enclosed by paths becomes a face even when nothing fills it. Each face lists the inputs whose fill covers it; the list is empty for an area that is only enclosed by paths. Each edge is a piece of a path, split wherever another path meets it, and keeps the key of the front-most input it lies on. -`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. +`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. When the paths cross each other so often that the sweep cuts them into more than `SHAPE_BUILDER_MAX_MAP_EDGES` pieces, it skips the full map and returns only the regions of the filled areas, which are capped on their own: a filled shape apart from open paths that cross too often still has its region. ```rust pub struct Adjacency { pub faces: Vec, pub edges: Vec, pub slivers: Vec, pub outlines: Vec } diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index d02e5a8a93..61d03ecbc1 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -33,8 +33,9 @@ pub use pathfinder::{ FaceMerger, PathfinderOp, Region, Shape, merge_regions, pathfinder, pathfinder_with, region_at, regions, regions_with, regions_within, }; pub use planar::{ - 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, + Adjacency, BuilderArrangement, MapEdge, MapFace, MapOutline, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_MAP_EDGES, 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 thickness::{MAX_DOCUMENT_THICKNESS_WORK, MAX_THICKNESS_PIECES, ThicknessBudget, thinner_than, thinner_than_within}; pub use trap::{TRAP_HEIGHT_WIDTH_RANGE, TRAP_MAX_WIDTH, TRAP_MIN_WIDTH, trap_band}; diff --git a/crates/pathops/src/pathfinder.rs b/crates/pathops/src/pathfinder.rs index 102d7e7138..3caddb4bc0 100644 --- a/crates/pathops/src/pathfinder.rs +++ b/crates/pathops/src/pathfinder.rs @@ -561,6 +561,16 @@ pub fn regions_with(shapes: &[Shape], precision: f64) -> Vec { arrangement(shapes, precision).map(|a| regions_of(&a)).unwrap_or_default() } +/// [`regions_with`], or `None` when the sweep cuts the shapes into more than `max_edges` pieces +/// (the faces are then not built). +pub(crate) fn regions_capped(shapes: &[Shape], precision: f64, max_edges: usize) -> Option> { + let Some(a) = arrangement(shapes, precision) else { return Some(Vec::new()) }; + if a.top.segment_indices().nth(max_edges).is_some() { + return None; + } + Some(regions_of(&a)) +} + /// [`regions`] when there are at most `limit` of them; `None` when there are more, found as soon /// as the face past `limit` is built (the faces after it are not built). pub fn regions_within(shapes: &[Shape], limit: usize) -> Option> { diff --git a/crates/pathops/src/planar.rs b/crates/pathops/src/planar.rs index f702f993ed..ca473dd839 100644 --- a/crates/pathops/src/planar.rs +++ b/crates/pathops/src/planar.rs @@ -41,8 +41,8 @@ pub use live_paint::{find_gaps, live_paint, live_paint_with_gaps}; pub use map::interior_point; pub(crate) use map::{Map, Rest, map}; pub use shape_builder::{ - BuilderArrangement, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_SEGMENTS, cut_out, encloses_area, has_open_path, run_around, shape_builder, - shape_builder_with_gap, + BuilderArrangement, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_MAP_EDGES, SHAPE_BUILDER_MAX_SEGMENTS, cut_out, encloses_area, has_open_path, + run_around, shape_builder, shape_builder_with_gap, }; pub(crate) use shape_builder::{builder, gap_inputs}; diff --git a/crates/pathops/src/planar/map.rs b/crates/pathops/src/planar/map.rs index f2c4b200d3..051a341e1a 100644 --- a/crates/pathops/src/planar/map.rs +++ b/crates/pathops/src/planar/map.rs @@ -42,6 +42,11 @@ 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. pub(super) fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option { + map_within(shapes, cover, precision, usize::MAX) +} + +/// [`map_with`], or `None` when the sweep cuts the paths into more than `max_edges` pieces. +pub(super) fn map_within(shapes: &[Shape], cover: bool, precision: f64, max_edges: usize) -> Option { let mut inputs: Vec<(BezPath, usize)> = Vec::new(); for (i, s) in shapes.iter().enumerate() { let mut bp = BezPath::new(); @@ -69,7 +74,7 @@ pub(super) fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option< return None; } let tidy = Tidy::keeping(precision, inputs.iter().map(|p| &p.0)); - let (points, edges) = sweep_graph(&inputs, eps, precision)?; + let (points, edges) = sweep_graph(&inputs, eps, precision, max_edges)?; let nv = points.len(); // Half-edges leaving each vertex, sorted by direction; walking a face, the next half-edge is @@ -188,11 +193,17 @@ pub(super) fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option< Some(Map { edges, around, slot_of, faces, face_index, slivers, holes, face_holes, tidy, anchors, snap }) } -fn sweep_graph(inputs: &[(BezPath, usize)], eps: f64, precision: f64) -> Option<(Vec, Vec)> { +fn sweep_graph(inputs: &[(BezPath, usize)], eps: f64, precision: f64, max_edges: usize) -> Option<(Vec, Vec)> { // The sweep can panic on rare near-degenerate input; that must never take the app down. let sweep = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| Topology::::from_paths(inputs.iter().map(|(p, i)| (p, *i)), eps))); let top = sweep.ok()?.ok()?; + // What is built from here on takes time and memory in proportion to the pieces the sweep cut + // the paths into, and paths that cross many times are cut into far more pieces than they have + // segments. + if top.segment_indices().nth(max_edges).is_some() { + return None; + } // The planar graph: vertices are the sweep's points, edges its segments. Points closer than // the sweep's tolerance are one vertex (it can put a corner that lies on another path's edge // a rounding error away from where it cuts that edge). @@ -426,8 +437,9 @@ impl Map { /// Faces and edges of `shapes`, and the pieces of the open paths (those with no closed subpath) /// that lie under another path in front of them, whose edges are that path's: under a closed /// path's outline, or along an open path in front. +/// `None` when the sweep cuts the paths into more than [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces. pub(super) fn build(shapes: &[Shape], precision: f64) -> Option<(Vec, Vec, Vec)> { - let m = map_with(shapes, false, precision)?; + let m = map_within(shapes, false, precision, SHAPE_BUILDER_MAX_MAP_EDGES)?; let Map { edges, around, faces, holes, face_holes, tidy, anchors, snap, .. } = &m; let snap = *snap; let fills: Vec = shapes.iter().map(Fill::new).collect(); diff --git a/crates/pathops/src/planar/shape_builder.rs b/crates/pathops/src/planar/shape_builder.rs index fcfb6cea95..4ddd10495a 100644 --- a/crates/pathops/src/planar/shape_builder.rs +++ b/crates/pathops/src/planar/shape_builder.rs @@ -9,6 +9,16 @@ use super::*; /// can take on art far past what a drawing holds. pub const SHAPE_BUILDER_MAX_SEGMENTS: usize = 65_536; +/// Most pieces the sweep may cut the Shape Builder's paths into, where they cross each other and +/// where an open path is traced there and back: twice [`SHAPE_BUILDER_MAX_SEGMENTS`], what open +/// paths that cross nothing make at that cap. Paths that cross many times make far more pieces +/// than they have segments (400 circles stacked nearly on top of each other, 1,600 segments, make +/// about 320,000), and the regions and edges built from them took minutes and gigabytes of memory. +/// Past this the Shape Builder skips the full map and keeps only the regions of the filled areas, +/// which are capped on their own: when the open paths alone cross too often, a filled shape apart +/// from them still has its region. +pub const SHAPE_BUILDER_MAX_MAP_EDGES: usize = 2 * SHAPE_BUILDER_MAX_SEGMENTS; + /// The Shape Builder's arrangement: see [`shape_builder`]. #[derive(Clone, Debug, Default, PartialEq)] pub struct BuilderArrangement { @@ -40,7 +50,10 @@ pub fn has_open_path(shapes: &[Shape]) -> bool { /// nothing fills, and each path with no closed subpath comes back cut wherever another path meets /// it, as pieces keyed by its index in `shapes`. Outlines are cut the same way. With more than /// [`SHAPE_BUILDER_MAX_SEGMENTS`] segments or a map that can't be built, only the filled areas -/// count and there are no pieces. +/// count and there are no pieces. The same happens when the sweep cuts the paths into more than +/// [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces; the filled areas are then capped on their own. They +/// then have no regions when they alone are cut into more pieces than that, and a filled area +/// thinner than the precision is dropped as a sliver, as in [`regions`](crate::regions). pub fn shape_builder(shapes: &[Shape], edges: bool) -> BuilderArrangement { shape_builder_with_gap(shapes, edges, 0.0) } @@ -97,7 +110,7 @@ pub(crate) fn builder(shapes: &[Shape], edges: bool, gap: f64, precision: f64) - faces } else { // The filled areas from their arrangement, whose faces merge exactly, then the gaps. - let mut regions = crate::pathfinder::regions_with(shapes, precision); + let mut regions = crate::pathfinder::regions_capped(shapes, precision, SHAPE_BUILDER_MAX_MAP_EDGES).unwrap_or_default(); regions.extend(faces.into_iter().filter(|f| f.sources.is_empty())); regions }; @@ -112,14 +125,16 @@ pub(crate) fn builder(shapes: &[Shape], edges: bool, gap: f64, precision: f64) - /// The regions of the shapes' filled areas. A shape that fills nothing (open paths that enclose no /// area, such as cutting lines) is left out, so a flood of them cannot push the arrangement past its /// size budget and take the filled shapes down with it; the regions keep the original indices. +/// There are none when the sweep cuts the filled shapes into more than [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces. fn filled_regions(shapes: &[Shape], precision: f64) -> Vec { let fills = |s: &Shape| s.path.subpaths.iter().any(|sp| sp.closed || encloses_area(sp)); let keep: Vec = (0..shapes.len()).filter(|&i| shapes.get(i).is_some_and(fills)).collect(); if keep.len() == shapes.len() { - return crate::pathfinder::regions_with(shapes, precision); + return crate::pathfinder::regions_capped(shapes, precision, SHAPE_BUILDER_MAX_MAP_EDGES).unwrap_or_default(); } let kept: Vec = keep.iter().filter_map(|&i| shapes.get(i).cloned()).collect(); - crate::pathfinder::regions_with(&kept, precision) + crate::pathfinder::regions_capped(&kept, precision, SHAPE_BUILDER_MAX_MAP_EDGES) + .unwrap_or_default() .into_iter() .map(|mut r| { r.sources = r.sources.iter().filter_map(|&s| keep.get(s).copied()).collect(); diff --git a/crates/pathops/src/planar/tests.rs b/crates/pathops/src/planar/tests.rs index ad888448a7..130d381bfa 100644 --- a/crates/pathops/src/planar/tests.rs +++ b/crates/pathops/src/planar/tests.rs @@ -603,6 +603,49 @@ fn shape_builder_offers_the_gaps_closed_shapes_enclose() { assert!(shape_builder(&s, false).regions.iter().all(|r| !r.sources.is_empty())); } +/// `n` horizontal and `n` vertical lines across one square, every one crossing every other. +fn line_grid(n: usize) -> Vec { + let at = |k: usize| 10.0 + k as f64 * 980.0 / n as f64; + let across = (0..n).map(|k| line((0.0, at(k)), (1000.0, at(k)), k as u64)); + let down = (0..n).map(|k| line((at(k), 0.0), (at(k), 1000.0), (n + k) as u64)); + across.chain(down).collect() +} + +/// `n` horizontal and `n` vertical bars across one square, every one crossing every other. +fn bar_grid(n: usize) -> Vec { + let at = |k: usize| 10.0 + k as f64 * 980.0 / n as f64; + let across = (0..n).map(|k| rect(0.0, at(k), 1000.0, at(k) + 1.0, k as u64)); + let down = (0..n).map(|k| rect(at(k), 0.0, at(k) + 1.0, 1000.0, (n + k) as u64)); + across.chain(down).collect() +} + +#[test] +fn a_map_past_its_edge_cap_is_not_built() { + // 20 lines each way: each line is cut into 21 pieces, 840 in all. + let s = line_grid(20); + assert!(map::map_within(&s, false, DEFAULT_PRECISION, 1000).is_some()); + assert!(map::map_within(&s, false, DEFAULT_PRECISION, 500).is_none()); + let bars = bar_grid(20); + assert!(crate::pathfinder::regions_capped(&bars, DEFAULT_PRECISION, 100_000).is_some_and(|r| r.len() > 400)); + assert!(crate::pathfinder::regions_capped(&bars, DEFAULT_PRECISION, 1000).is_none()); +} + +#[test] +fn shape_builder_builds_no_regions_past_its_edge_cap() { + // 300 lines each way cross 90,000 times with 600 segments: the sweep cuts them into about + // 180,000 pieces, past the cap, and nothing is built from them. + let s = line_grid(300); + let started = work_done(); + let BuilderArrangement { regions, lines, edges, lines_under } = shape_builder(&s, true); + assert!(regions.is_empty() && lines.is_empty() && edges.is_empty() && lines_under.is_empty(), "{} regions", regions.len()); + assert_eq!(work_done() - started, 0, "no face or edge was looked up"); + // Bars, closed paths only, each edge crossing 300 others: their filled areas are not built + // either. + assert!(shape_builder(&bar_grid(150), true).regions.is_empty()); + // Under the cap, the same grid is built. + assert_eq!(shape_builder(&line_grid(20), false).regions.len(), 19 * 19); +} + #[test] fn shape_builder_stays_quick_up_to_its_cap() { // A wavy ring of nearly the most segments the map takes, crossed by a few lines. diff --git a/crates/pdf/src/streams.rs b/crates/pdf/src/streams.rs index e29d828f48..7314e930ae 100644 --- a/crates/pdf/src/streams.rs +++ b/crates/pdf/src/streams.rs @@ -1034,6 +1034,19 @@ mod tests { assert!(unread.is_empty(), "{unread:#?}"); } + #[test] + fn a_hex_string_broken_by_a_non_hex_byte_hides_no_stream_after_it() { + // A `<` followed by hex digits and then a byte that is neither a hex digit nor white space + // is no hex string: the scan goes on from the next byte instead of skipping to a `>`. + let bad = b"<< /Type /XRef /DecodeParms 9 0 R >> stream\nx\nendstream"; + for lead in [&b"<4G "[..], b"<41 4z ", b"<\x00 "] { + let pdf = [lead, &bad[..]].concat(); + assert!(unsafe_file_streams(&pdf), "{}", String::from_utf8_lossy(&pdf)); + } + // A hex string that ends is skipped, and the stream after it is still read. + assert!(unsafe_file_streams(&[&b"<41 42> "[..], &bad[..]].concat())); + } + #[test] fn a_run_of_lt_in_an_image_a_string_or_a_comment_opens() { // #3924 review: every `<<` in a run of `<` (an image's flat area of grey 60) was read as a diff --git a/crates/pdf/src/tests/file_fonts.rs b/crates/pdf/src/tests/file_fonts.rs index d0d1b949ab..b27dac4f0d 100644 --- a/crates/pdf/src/tests/file_fonts.rs +++ b/crates/pdf/src/tests/file_fonts.rs @@ -10,7 +10,7 @@ use kurbo::{Point, Rect, Shape}; use vectorcraft_doc::{Document, FILE_FONT_MIME, TextObject}; use vectorcraft_text::{FontDb, FontMatch}; -use crate::tests::live_text::{SOURCE_SERIF, outlines, texts, uninstalled_serif}; +use crate::tests::live_text::{SOURCE_SERIF, outlines, renamed, texts, uninstalled_serif}; use crate::*; /// Lines of (x, y from the top, size, text): kerned pairs, a long line, two sizes. @@ -274,3 +274,29 @@ fn two_glyphs_for_one_character_both_survive_import() { }; close(&glyph_ink(db, &imported), "imported"); } + +/// The license flags (OS/2 `fsType`) of the font a PDF carries go with the font the document keeps: +/// a restricted font (0x0002) still draws its type, and a PDF saved from the document draws that +/// type as outlines with the license warning instead of embedding the font again. +#[test] +fn a_restricted_font_the_file_carries_is_not_embedded_again() { + let mut font = renamed(SOURCE_SERIF, &[("SourceSerif4", "SourceSerif7"), ("Source Serif 4", "Source Serif 7")]); + let tables = usize::from(u16::from_be_bytes([font[4], font[5]])); + let os2 = (0..tables).map(|i| 12 + 16 * i).find(|r| &font[*r..*r + 4] == b"OS/2").unwrap(); + let at = u32::from_be_bytes(font[os2 + 8..os2 + 12].try_into().unwrap()) as usize; + font[at + 8..at + 10].copy_from_slice(&0x0002u16.to_be_bytes()); + + let carried = import(&page_pdf(font)); + let t = texts(&carried.document); + assert!(t.iter().any(|t| t.file_fonts.is_some()), "the file's font draws its type"); + + let saved = export_with_report(&carried.document, &PdfOptions::default()).unwrap(); + assert!(saved.warnings.iter().any(|w| w.contains("Source Serif 7") && w.contains("doesn't allow embedding")), "{:?}", saved.warnings); + let back = import(&saved.bytes); + assert!( + texts(&back.document).is_empty(), + "no type in the saved file: {:?}", + texts(&back.document).iter().map(TextObject::plain_text).collect::>() + ); + assert!(!back.document.images.values().any(|b| b.mime == FILE_FONT_MIME), "no font in the saved file"); +} diff --git a/crates/pdf/src/tests/live_text.rs b/crates/pdf/src/tests/live_text.rs index 90341ca28b..f6a2e8229b 100644 --- a/crates/pdf/src/tests/live_text.rs +++ b/crates/pdf/src/tests/live_text.rs @@ -271,7 +271,7 @@ fn invisible_text_is_type_whatever_its_glyphs_look_like() { } /// `font` with each of `names` (`from`, `to`, the same length) replaced, in ASCII and UTF-16. -fn renamed(font: &[u8], names: &[(&str, &str)]) -> Vec { +pub(crate) fn renamed(font: &[u8], names: &[(&str, &str)]) -> Vec { let mut bytes = font.to_vec(); let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::>(); for &(from, to) in names { diff --git a/crates/render/src/stroke.rs b/crates/render/src/stroke.rs index cd5cacac97..93fe88a1ed 100644 --- a/crates/render/src/stroke.rs +++ b/crates/render/src/stroke.rs @@ -19,7 +19,7 @@ pub(crate) fn outline(line: &BezPath, st: &StrokeLayer, width: f64, tol: f64) -> } // Closed endpoint rounding must not consume a substantial part of a subpixel band. let fine = (tol / 8.0).min(width / 32.0).max(1e-4); - if let Some(band) = thin_line(line, st, width).and_then(|lines| thin_band(&lines, st, width, fine)) { + if let Some(band) = thin_line(line, st, width).and_then(|lines| thin_band(&lines, &corners(line), st, width, fine)) { return band; } let outline = effects::stroke::line_outline(line, st, width, fine); @@ -49,21 +49,65 @@ fn thin_line(line: &BezPath, st: &StrokeLayer, width: f64) -> Option { lines.elements().iter().all(|el| !matches!(el, PathEl::QuadTo(..) | PathEl::CurveTo(..))).then_some(lines) } +/// The points where `line` has a corner: where two of its segments meet with tangents that are not +/// in line ([`SMOOTH`]), or where a segment has no direction there. One list for each subpath, in +/// order, each sorted by [`point_order`]. [`draw_sub`] leaves these points where they are, so the +/// lines a curve is drawn with have each corner at the same point, and draws one subpath for each. +fn corners(line: &BezPath) -> Vec> { + let tangents = |seg: PathSeg| { + let c = match seg { + PathSeg::Line(l) => CubicBez::new(l.p0, l.p0, l.p1, l.p1), + other => cubic(other)?, + }; + Some((start_tangent(&c)?, end_tangent(&c)?)) + }; + let mut out = Vec::new(); + // A span of `f64::INFINITY` gives every segment no steps: only the segments are wanted. + for sub in subpaths(line.elements(), f64::INFINITY, 1.0).unwrap_or_default() { + let mut here = Vec::new(); + let n = sub.segs.len(); + let first = if sub.closed { 0 } else { 1 }; + for i in first..n { + let before = if i == 0 { n - 1 } else { i - 1 }; + let (Some((a, _)), Some((b, _))) = (sub.segs.get(before), sub.segs.get(i)) else { continue }; + let smooth = match (tangents(*a).map(|t| t.1), tangents(*b).map(|t| t.0)) { + (Some(u), Some(v)) => u.dot(v) > 0.0 && u.cross(v).abs() <= SMOOTH * u.hypot() * v.hypot(), + _ => false, + }; + if !smooth { + here.push(b.start()); + } + } + here.sort_by(point_order); + out.push(here); + } + out +} + +/// Points in order of `x`, then `y` ([`corners`]). +fn point_order(a: &Point, b: &Point) -> std::cmp::Ordering { + a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y)) +} + /// The outline of stroke `st` at `width` along `lines`, a path of lines only ([`thin_line`]), to fill /// with the non-zero rule. Each side of each line is offset by half the width. Where two lines meet -/// at a small angle ([`THIN_SMOOTH`]) both sides go to where the offsets cross; elsewhere the -/// stroke's join is drawn, and an open subpath ends in the stroke's caps, with round parts drawn as +/// at a small angle ([`THIN_SMOOTH`]) both sides go to where the offsets cross. Elsewhere the +/// stroke's join is drawn at the corners of the same subpath of the path (`corners`, one list for +/// each subpath of `lines`, [`corners`]) and a round join where the lines a +/// curve is drawn with meet. An open subpath ends in the stroke's caps, with round parts drawn as /// lines within `fine` of their arcs. `None` when a subpath has fewer than two distinct points or a /// point that isn't finite, or is closed and no wider or taller than the stroke: those take /// [`effects::stroke::line_outline`]. -fn thin_band(lines: &BezPath, st: &StrokeLayer, width: f64, fine: f64) -> Option { +fn thin_band(lines: &BezPath, corners: &[Vec], st: &StrokeLayer, width: f64, fine: f64) -> Option { let h = width / 2.0; // The angle between two points of an arc of radius `h` drawn as lines within `fine` of it. let step = 2.0 * (1.0 - (fine / h).min(1.0)).acos().max(1e-3); let mut out = BezPath::new(); let mut pts: Vec = Vec::new(); let mut closed = false; - let flush = |pts: &mut Vec, closed: bool, out: &mut BezPath| -> Option<()> { + // The subpath being read; `None` before the first move. + let mut sub: Option = None; + let flush = |pts: &mut Vec, closed: bool, sub: Option, out: &mut BezPath| -> Option<()> { if pts.is_empty() { return Some(()); } @@ -80,14 +124,15 @@ fn thin_band(lines: &BezPath, st: &StrokeLayer, width: f64, fine: f64) -> Option return None; } } - band_sub(out, pts, closed, st, h, step); + band_sub(out, pts, corners.get(sub?)?, closed, st, h, step); pts.clear(); Some(()) }; for el in lines.elements() { match *el { PathEl::MoveTo(p) => { - flush(&mut pts, closed, &mut out)?; + flush(&mut pts, closed, sub, &mut out)?; + sub = Some(sub.map_or(0, |s| s + 1)); closed = false; pts.push(p); } @@ -100,7 +145,7 @@ fn thin_band(lines: &BezPath, st: &StrokeLayer, width: f64, fine: f64) -> Option PathEl::QuadTo(..) | PathEl::CurveTo(..) => return None, } } - flush(&mut pts, closed, &mut out)?; + flush(&mut pts, closed, sub, &mut out)?; Some(out) } @@ -108,8 +153,9 @@ fn thin_band(lines: &BezPath, st: &StrokeLayer, width: f64, fine: f64) -> Option /// repeating the first when `closed`) to `out`: for an open subpath one contour, its left side, /// the end cap, its right side backward and the start cap; for a closed one its left side and its /// right side backward, as two contours. `h` is half the width and `step` the angle between the -/// points of a round join or cap. -fn band_sub(out: &mut BezPath, pts: &[Point], closed: bool, st: &StrokeLayer, h: f64, step: f64) { +/// points of a round join or cap. A sharp turn takes the stroke's join at one of this subpath's +/// `corners` (sorted by [`point_order`]) and a round join elsewhere. +fn band_sub(out: &mut BezPath, pts: &[Point], corners: &[Point], closed: bool, st: &StrokeLayer, h: f64, step: f64) { use vectorcraft_doc::{LineCap, LineJoin}; let n = pts.len(); let chords = if closed { n } else { n - 1 }; @@ -143,7 +189,10 @@ fn band_sub(out: &mut BezPath, pts: &[Point], closed: bool, st: &StrokeLayer, h: inner.push(p); inner.push(p - nb * sign); outer.push(p + na * sign); - match st.join { + // Only the path's corners take the stroke's join; where the lines of a curve turn sharply + // the stroke along the curve is round. + let kind = if corners.binary_search_by(|c| point_order(c, &p)).is_ok() { st.join } else { LineJoin::Round }; + match kind { LineJoin::Miter if 2.0 < (1.0 + dot) * st.miter_limit.powi(2) => outer.push(p + miter * sign), LineJoin::Round => arc(outer, p, na * sign, cross.atan2(dot)), LineJoin::Miter | LineJoin::Bevel => {} diff --git a/crates/render/src/tests/thincoverage.rs b/crates/render/src/tests/thincoverage.rs index 4017448fd9..ab31619111 100644 --- a/crates/render/src/tests/thincoverage.rs +++ b/crates/render/src/tests/thincoverage.rs @@ -133,6 +133,148 @@ fn thin_strokes_drawn_as_lines_keep_both_turns_of_a_curve() { assert!(bounds.x1 <= turn + past && bounds.x0 >= -turn - past, "the outline spans {bounds:?}"); } +/// A path with a bend at (10, 0) and then six smooth anchors `gap` apart, each with handles +/// `handle` and 1.7 times `handle` long, scaled by `zoom`, and its points flattened within 0.001. +fn close_smooth_anchors(gap: f64, handle: f64, zoom: f64) -> (BezPath, Vec) { + let path = close_smooth_path(gap, handle, zoom); + let mut line = Vec::new(); + vectorcraft_geom::flatten(path.iter(), 1e-3, |el| { + if let kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) = el { + line.push(p); + } + }); + (path, line) +} + +/// How far `q` is from the nearest point of `path`. +fn from_curve(path: &BezPath, q: kurbo::Point) -> f64 { + use kurbo::ParamCurveNearest; + path.segments().map(|s| s.nearest(q, 1e-9).distance_sq.sqrt()).fold(f64::INFINITY, f64::min) +} + +/// The path of [`close_smooth_anchors`]. +fn close_smooth_path(gap: f64, handle: f64, zoom: f64) -> BezPath { + use vectorcraft_geom::path::{Anchor, AnchorKind, PathData, SubPath}; + let dir = kurbo::Vec2::new(0.8, 0.6); + let mut anchors = vec![ + Anchor::corner(kurbo::Point::new(0.0, 0.0)), + Anchor::with_handles(kurbo::Point::new(10.0, 0.0), kurbo::Point::new(10.0, 0.0), kurbo::Point::new(10.0, 5.0)), + ]; + let mut x = 10.0; + for i in 0..6 { + x += gap; + let p = kurbo::Point::new(x, 1.0 + if i % 2 == 0 { 0.3 } else { -0.2 } * gap); + anchors.push(Anchor { p, h_in: p - dir * handle, h_out: p + dir * handle * 1.7, kind: AnchorKind::Smooth }); + } + anchors.push(Anchor::smooth(kurbo::Point::new(x + 20.0, 0.0), kurbo::Point::new(x + 25.0, -4.0))); + kurbo::Affine::scale(zoom) * PathData::single(SubPath::new(anchors, false)).to_bezpath() +} + +/// A thin stroke along smooth anchors that sit close together after a bend follows the curve: its +/// outline has no point farther than a stroke's width from the curve, and covers the curve. The +/// lines such a curve is drawn with are short beside the stroke and turn sharply, so offsetting +/// them drew the stroke's miter joins as spikes. +#[test] +fn thin_strokes_follow_smooth_anchors_close_together() { + for gap in [0.1, 1.0] { + let (path, line) = close_smooth_anchors(gap, 1.0, 1.0); + for w in [0.6, 0.9] { + let st = StrokeLayer::new(Paint::solid(Color::BLACK), w); + let o = raster_stroke_outline(&path, &st, w, 0.25); + for el in o.elements() { + if let kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) = *el { + let d = from_curve(&path, p); + assert!(d <= w, "gap {gap}, width {w}: outline point {p:?} is {d} from the curve"); + } + } + for p in line.iter().step_by(7) { + assert!(o.winding(*p) != 0, "gap {gap}, width {w}: the curve at {p:?} is not covered"); + } + } + } +} + +/// A thin stroke's outline stays within the stroke's width of its curve where the lines the curve is +/// drawn with turn sharply, as near a cusp: they meet with a round join, not the stroke's miter. +/// 200 cubic curves, each about 100 device pixels across. +#[test] +fn thin_strokes_meet_round_where_a_curves_lines_turn_sharply() { + let mut seed: u64 = 7; + let mut r = |lo: f64, hi: f64| { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + lo + (hi - lo) * ((seed >> 11) as f64 / (1u64 << 53) as f64) + }; + let w = 0.5; + let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), w); + st.join = LineJoin::Miter; + st.miter_limit = 10.0; + for _ in 0..200 { + let (x, y) = (r(20.0, 980.0), r(20.0, 980.0)); + let mut q = [kurbo::Point::ZERO; 3]; + for p in &mut q { + *p = kurbo::Point::new((x + r(-30.0, 30.0)) * 1.71, (y + r(-30.0, 30.0)) * 1.71); + } + let mut path = BezPath::new(); + path.move_to((x * 1.71, y * 1.71)); + path.curve_to(q[0], q[1], q[2]); + let o = raster_stroke_outline(&path, &st, w, 0.25); + for el in o.elements() { + if let kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) = *el { + let d = from_curve(&path, p); + assert!(d <= w, "outline point {p:?} is {d} from the curve {path:?}"); + } + } + } +} + +/// A thin stroke along smooth anchors close together, with handles long beside the gaps between +/// them, covers what the curve's own outline covers: at every point of a grid more than 0.25 pixels +/// nearer or farther than half the stroke's width from the curve, both outlines agree. The miter +/// joins drawn where the curve's lines turned sharply covered points well outside the stroke. +#[test] +fn thin_strokes_along_long_handles_cover_the_curve_outline() { + let tol = 0.25; + for (gap, w) in [(1.0, 0.6), (1.0, 0.9), (0.1, 0.6)] { + let path = close_smooth_path(gap, 10.0, 4.0); + let st = StrokeLayer::new(Paint::solid(Color::BLACK), w); + let o = raster_stroke_outline(&path, &st, w, tol); + let fine = (tol / 8.0).min(w / 32.0); + let mut want = BezPath::new(); + vectorcraft_geom::flatten(crate::effects::stroke::line_outline(&path, &st, w, fine).iter(), fine, |el| want.push(el)); + let bb = want.bounding_box().inflate(w, w); + for i in 0..90 { + for j in 0..90 { + let q = kurbo::Point::new(bb.x0 + bb.width() * f64::from(i) / 90.0, bb.y0 + bb.height() * f64::from(j) / 90.0); + let d = from_curve(&path, q); + if (d - w / 2.0).abs() > 0.25 { + assert_eq!(o.winding(q) != 0, want.winding(q) != 0, "gap {gap}, width {w}: at {q:?}, {d} from the curve"); + } + } + } + } +} + +/// A corner of one subpath does not change the join where the lines of another subpath's curve +/// meet at the same point: the first subpath's outline is the same with or without the second. +#[test] +fn thin_strokes_take_corners_from_their_own_subpath() { + let w = 0.5; + let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), w); + st.join = LineJoin::Miter; + st.miter_limit = 10.0; + let mut alone = BezPath::new(); + alone.move_to((-1.0, 0.0)); + alone.line_to((0.0, 0.0)); + alone.curve_to((0.000001, 0.0), (-1.0, 0.5), (-2.0, 1.0)); + let mut both = alone.clone(); + both.move_to((-10.0, -10.0)); + both.line_to((0.0, 0.0)); + both.line_to((-10.0, 10.0)); + let one = raster_stroke_outline(&alone, &st, w, 0.25); + let two = raster_stroke_outline(&both, &st, w, 0.25); + assert_eq!(two.elements().get(..one.elements().len()), Some(one.elements()), "the second subpath changed the first one's outline"); +} + /// Independently integrate coverage in radial/angle bins of an original notched ring. Checking /// only the outline geometry misses raster flattening that cancels its two nearby contours. #[test] diff --git a/crates/ui-egui/src/addons/shapes.rs b/crates/ui-egui/src/addons/shapes.rs index e5fde5725e..65fed545ca 100644 --- a/crates/ui-egui/src/addons/shapes.rs +++ b/crates/ui-egui/src/addons/shapes.rs @@ -709,7 +709,7 @@ mod cancel_tests { #[cfg(test)] mod tests { use craft::behavior::IconId; - use craft::ui::primitives::{has_icon, register_app_icons}; + use craft::ui::primitives::has_icon; use super::icon_for_shape; @@ -717,7 +717,7 @@ mod tests { /// would show the placeholder instead of the toolbar's icon. #[test] fn every_shape_button_shows_its_tools_icon() { - register_app_icons(&crate::icons::APP_ICONS); + crate::icons::register(); for id in ["box3d", "rectangle", "ellipse", "polygon", "star", "spiral"] { let tool = vectorcraft_tools::tool_info(id).unwrap_or_else(|| panic!("{id} is a tool")); assert_eq!(icon_for_shape(id), crate::icons::tool_icon(tool.icon), "{id}"); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 0fda79c6d1..b660816876 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -67,7 +67,7 @@ impl VectorcraftApp { /// once, gives Data Recovery the host's store and makes a view for each open document. pub fn new(mut session: Session, mut services: Services) -> Self { // Every entry point (desktop, web, tests) makes the app before its first pass. - craft::ui::primitives::register_app_icons(&super::icons::APP_ICONS); + super::icons::register(); craft::ui::primitives::register_app_icons(&super::cursors::CURSOR_ICONS); // The font menus and the first file opened need the installed fonts: catalog them now. vectorcraft_text::FontDb::global().scan_in_background(); diff --git a/crates/ui-egui/src/canvas/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index 2e33ef9cf8..8b2b35db16 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -463,7 +463,14 @@ impl CanvasTool for SessionTool<'_> { if claim(&mut app, EngineKey::Left) { claims = claims.nudges(); } - if claim(&mut app, EngineKey::AltTap) { + // A lone Alt while the canvas has the keys is the tools' modifier let go without a click: the canvas takes it, + // so it does not give the menu bar the keys and the next tool letter still chooses its tool. F10 and Alt with + // a letter still reach the bar, and a lone Alt in a field or the bar keeps the framework's rule. + let canvas_has_keys = app + .ui_ctx + .as_ref() + .is_some_and(|ctx| !ctx.egui_wants_keyboard_input() && !craft::ui::menu::bar::is_focused(ctx) && !craft::ui::menu::bar::is_open(ctx)); + if canvas_has_keys || claim(&mut app, EngineKey::AltTap) { claims = claims.alt_tap(); } claims diff --git a/crates/ui-egui/src/cursors/tests.rs b/crates/ui-egui/src/cursors/tests.rs index 183bda8b47..2f6821f8a9 100644 --- a/crates/ui-egui/src/cursors/tests.rs +++ b/crates/ui-egui/src/cursors/tests.rs @@ -17,7 +17,7 @@ fn every_tool_cursors_hotspot_is_on_its_glyph() { use craft::ui::primitives::{painted_image, register_app_icons}; use craft::ui::runtime::env::Env; use craft::ui::style::rgba_color; - register_app_icons(&crate::icons::APP_ICONS); + crate::icons::register(); register_app_icons(&CURSOR_ICONS); let mut missed = Vec::new(); crate::testing::ui_context() diff --git a/crates/ui-egui/src/dialogs/halftone.rs b/crates/ui-egui/src/dialogs/halftone.rs index 98a8515c16..ebc54223f6 100644 --- a/crates/ui-egui/src/dialogs/halftone.rs +++ b/crates/ui-egui/src/dialogs/halftone.rs @@ -47,7 +47,15 @@ pub(super) fn options>(list: &[(I, &str)]) -> Vec<(String, Label)> /// Vector Halftone adds Keep Original. The Color row depends on two values, so the rows are built /// from `fields`. pub(crate) fn screen_params(live: bool, fields: &DialogFields) -> Vec { - let shapes = [("circle", "Circle"), ("ellipse", "Ellipse"), ("square", "Square"), ("diamond", "Diamond"), ("line", "Line")]; + let shapes = [ + ("circle", "Circle"), + ("ellipse", "Ellipse"), + ("square", "Square"), + ("diamond", "Diamond"), + ("line", "Line"), + ("euclidean", "Euclidean"), + ("elliptical", "Elliptical"), + ]; let mut rows = vec![ Param::new("shape", tl!("Shape"), ParamKind::choice(options(&shapes), Some("circle".into()))), Param::new("frequency", tl!("Frequency"), ParamKind::range(1.0, 150.0, 20.0, SliderScale::Linear)).unit(UnitKind::LinesPerInch), diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs index 96719fa0c9..eb2a544af8 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -4,31 +4,8 @@ /// The Selection and Direct Selection arrows' fill, painted black or white under their outline. pub const DC_ARROW_FILL: &[u8] = include_bytes!("../../../assets/icons/dc-arrow-fill.svg"); +/// VectorCraft's own `dc-*` icons, drawn with 1.5-unit strokes in a 24-unit view box. pub static ICONS: &[(&str, &[u8])] = &[ - ("align-center-horizontal", include_bytes!("../../../assets/icons/align-center-horizontal.svg")), - ("align-center-vertical", include_bytes!("../../../assets/icons/align-center-vertical.svg")), - ("align-end-horizontal", include_bytes!("../../../assets/icons/align-end-horizontal.svg")), - ("align-end-vertical", include_bytes!("../../../assets/icons/align-end-vertical.svg")), - ("align-horizontal-justify-center", include_bytes!("../../../assets/icons/align-horizontal-justify-center.svg")), - ("align-horizontal-justify-end", include_bytes!("../../../assets/icons/align-horizontal-justify-end.svg")), - ("align-horizontal-justify-start", include_bytes!("../../../assets/icons/align-horizontal-justify-start.svg")), - ("align-start-horizontal", include_bytes!("../../../assets/icons/align-start-horizontal.svg")), - ("align-start-vertical", include_bytes!("../../../assets/icons/align-start-vertical.svg")), - ("align-vertical-justify-center", include_bytes!("../../../assets/icons/align-vertical-justify-center.svg")), - ("align-vertical-justify-end", include_bytes!("../../../assets/icons/align-vertical-justify-end.svg")), - ("align-vertical-justify-start", include_bytes!("../../../assets/icons/align-vertical-justify-start.svg")), - ("arrow-left-right", include_bytes!("../../../assets/icons/arrow-left-right.svg")), - ("arrow-up-down", include_bytes!("../../../assets/icons/arrow-up-down.svg")), - ("chart-column", include_bytes!("../../../assets/icons/chart-column.svg")), - ("chevron-down", include_bytes!("../../../assets/icons/chevron-down.svg")), - ("chevron-left", include_bytes!("../../../assets/icons/chevron-left.svg")), - ("chevron-right", include_bytes!("../../../assets/icons/chevron-right.svg")), - ("chevrons-left", include_bytes!("../../../assets/icons/chevrons-left.svg")), - ("chevrons-right", include_bytes!("../../../assets/icons/chevrons-right.svg")), - // PLAN: circle-off.svg is plugins-w11's file; the row waits for it. - ("circle-off", include_bytes!("../../../assets/icons/circle-off.svg")), - ("clipboard-paste", include_bytes!("../../../assets/icons/clipboard-paste.svg")), - ("combine", include_bytes!("../../../assets/icons/combine.svg")), ("dc-actions", include_bytes!("../../../assets/icons/dc-actions.svg")), ("dc-al-bottom", include_bytes!("../../../assets/icons/dc-al-bottom.svg")), ("dc-al-center", include_bytes!("../../../assets/icons/dc-al-center.svg")), @@ -244,6 +221,34 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-wrinkle", include_bytes!("../../../assets/icons/dc-wrinkle.svg")), ("dc-zoom-large", include_bytes!("../../../assets/icons/dc-zoom-large.svg")), ("dc-zoom-small", include_bytes!("../../../assets/icons/dc-zoom-small.svg")), +]; + +/// Lucide icons the built-in catalog lacks, drawn with Lucide's 2-unit strokes in a 24-unit view box. +pub static LUCIDE_ICONS: &[(&str, &[u8])] = &[ + ("align-center-horizontal", include_bytes!("../../../assets/icons/align-center-horizontal.svg")), + ("align-center-vertical", include_bytes!("../../../assets/icons/align-center-vertical.svg")), + ("align-end-horizontal", include_bytes!("../../../assets/icons/align-end-horizontal.svg")), + ("align-end-vertical", include_bytes!("../../../assets/icons/align-end-vertical.svg")), + ("align-horizontal-justify-center", include_bytes!("../../../assets/icons/align-horizontal-justify-center.svg")), + ("align-horizontal-justify-end", include_bytes!("../../../assets/icons/align-horizontal-justify-end.svg")), + ("align-horizontal-justify-start", include_bytes!("../../../assets/icons/align-horizontal-justify-start.svg")), + ("align-start-horizontal", include_bytes!("../../../assets/icons/align-start-horizontal.svg")), + ("align-start-vertical", include_bytes!("../../../assets/icons/align-start-vertical.svg")), + ("align-vertical-justify-center", include_bytes!("../../../assets/icons/align-vertical-justify-center.svg")), + ("align-vertical-justify-end", include_bytes!("../../../assets/icons/align-vertical-justify-end.svg")), + ("align-vertical-justify-start", include_bytes!("../../../assets/icons/align-vertical-justify-start.svg")), + ("arrow-left-right", include_bytes!("../../../assets/icons/arrow-left-right.svg")), + ("arrow-up-down", include_bytes!("../../../assets/icons/arrow-up-down.svg")), + ("chart-column", include_bytes!("../../../assets/icons/chart-column.svg")), + ("chevron-down", include_bytes!("../../../assets/icons/chevron-down.svg")), + ("chevron-left", include_bytes!("../../../assets/icons/chevron-left.svg")), + ("chevron-right", include_bytes!("../../../assets/icons/chevron-right.svg")), + ("chevrons-left", include_bytes!("../../../assets/icons/chevrons-left.svg")), + ("chevrons-right", include_bytes!("../../../assets/icons/chevrons-right.svg")), + // PLAN: circle-off.svg is plugins-w11's file; the row waits for it. + ("circle-off", include_bytes!("../../../assets/icons/circle-off.svg")), + ("clipboard-paste", include_bytes!("../../../assets/icons/clipboard-paste.svg")), + ("combine", include_bytes!("../../../assets/icons/combine.svg")), ("ellipsis", include_bytes!("../../../assets/icons/ellipsis.svg")), ("eye-off", include_bytes!("../../../assets/icons/eye-off.svg")), ("file-plus", include_bytes!("../../../assets/icons/file-plus.svg")), diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index 30b6edfb49..a544de7e90 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -2,14 +2,24 @@ use craft::ui::primitives::{AppIcons, icon_names}; -use crate::icon_data::{DC_ARROW_FILL, ICONS}; +use crate::icon_data::{DC_ARROW_FILL, ICONS, LUCIDE_ICONS}; /// The fills of the Selection and Direct Selection arrows: black and white whatever the theme, as users /// know them, under an outline in the theme's colour. const FILLS: &[(&str, &[u8], [u8; 4])] = &[("dc-selection", DC_ARROW_FILL, [0, 0, 0, 255]), ("dc-direct", DC_ARROW_FILL, [255, 255, 255, 255])]; -/// The app's icons, for `register_app_icons`. -pub static APP_ICONS: AppIcons = AppIcons::new("vectorcraft", Some(1.6), ICONS).with_fills(FILLS); +/// The app's own icons, for `register_app_icons`. The stroke width is the documents' own, so the framework redraws +/// their strokes at the width it draws the catalog's. +pub static APP_ICONS: AppIcons = AppIcons::new("vectorcraft", Some(1.5), ICONS).with_fills(FILLS); + +/// The Lucide icons the catalog lacks, with Lucide's own stroke width. +pub static LUCIDE_APP_ICONS: AppIcons = AppIcons::new("vectorcraft-lucide", Some(2.0), LUCIDE_ICONS); + +/// Registers both of the app's icon sets beside the framework's catalog. +pub fn register() { + craft::ui::primitives::register_app_icons(&APP_ICONS); + craft::ui::primitives::register_app_icons(&LUCIDE_APP_ICONS); +} /// Map tool-catalogue icon names to the names of icons that resolve. pub fn tool_icon(name: &str) -> &'static str { @@ -114,23 +124,63 @@ pub fn tool_icon(name: &str) -> &'static str { "tool-print-tiling" => "dc-print-tiling", "tool-zoom" => "zoom_in", // A name that is already an icon maps to itself, as the `'static` name of the set that has it. - other => icon_names().iter().copied().chain(APP_ICONS.icons.iter().map(|(n, _)| *n)).find(|n| *n == other).unwrap_or("rect_dashed"), + other => icon_names() + .iter() + .copied() + .chain(APP_ICONS.icons.iter().chain(LUCIDE_APP_ICONS.icons).map(|(n, _)| *n)) + .find(|n| *n == other) + .unwrap_or("rect_dashed"), } } #[cfg(test)] mod tests { - use craft::ui::primitives::{has_icon, register_app_icons}; + use craft::ui::primitives::has_icon; // PLAN: assumed the `craft` facade is a dependency of vectorcraft-ui-egui (Cargo.toml is not in this set's files; craft-ui does not re-export IconId) use craft::behavior::IconId; use super::*; fn resolves(name: &'static str) -> bool { - register_app_icons(&APP_ICONS); + register(); has_icon(&IconId::new(name)) } + /// The SVG document of the app icon `name`, from either set. + fn app_svg(name: &str) -> String { + let (_, bytes) = ICONS.iter().chain(LUCIDE_ICONS).find(|(n, _)| *n == name).unwrap_or_else(|| panic!("{name} isn't an app icon")); + String::from_utf8_lossy(bytes).into_owned() + } + + /// The `stroke-width` the document's root `` element sets, the width of every stroke that sets none of its + /// own; `None` for a document drawn with fills. + fn root_stroke_width(svg: &str) -> Option { + let root = svg.split("').next()?; + Some(root.split("stroke-width=\"").nth(1)?.split('"').next()?.parse().unwrap_or(f32::NAN)) + } + + // Regression test: the tool rail's icons drew uneven outlines. The app set declared a 1.6-unit stroke while its own icons drew 1.5 and + // its Lucide copies drew 2, so the framework drew them 6% thinner and 25% heavier than the catalog's icons. + /// The framework scales every stroke in a set by the drawn width over the set's declared width, so an icon's + /// outline matches the catalog's only when its root stroke width equals its set's declared width. Details with + /// a width of their own keep their ratio to the outline. + #[test] + fn every_app_icon_draws_its_outline_at_the_catalog_width() { + let mut off = Vec::new(); + for set in [&APP_ICONS, &LUCIDE_APP_ICONS] { + let declared = set.stroke_width.unwrap_or_else(|| panic!("{} declares its stroke width", set.name)); + for (name, bytes) in set.icons { + let Some(width) = root_stroke_width(&String::from_utf8_lossy(bytes)) else { continue }; + // The outline's drawn width relative to the catalog's. + let relative = width / declared; + if !(0.99..=1.01).contains(&relative) { + off.push(format!("{name} in {}: {width} draws at {relative:.3} of the catalog width", set.name)); + } + } + } + assert!(off.is_empty(), "app icons whose outlines do not draw at the catalog width: {off:#?}"); + } + /// The ways a source line writes an icon id as a literal; a `const` that holds one is read by `const_icon`. const FORMS: [&str; 3] = ["IconId::new(\"", "icon(\"", "icon = \""]; @@ -153,7 +203,7 @@ mod tests { /// app's set. Other ids built in match arms and tuple tables are not scanned. #[test] fn every_icon_id_literal_and_panel_icon_resolves() { - register_app_icons(&APP_ICONS); + register(); let resolves = |id: &str| has_icon(&IconId::from(std::borrow::Cow::Owned(id.to_owned()))); let (mut seen, mut unknown) = (0, Vec::new()); let mut stack = vec![std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src")]; @@ -212,10 +262,7 @@ mod tests { // as opaque as the line, so the line vanished where it crossed the bar. #[test] fn the_cap_icons_mark_the_path_end_in_one_place_over_a_lighter_stroke() { - let svg = |name: &str| { - let (_, bytes) = crate::icon_data::ICONS.iter().find(|(n, _)| *n == name).unwrap_or_else(|| panic!("{name} isn't an icon")); - String::from_utf8_lossy(bytes).into_owned() - }; + let svg = app_svg; // The end-of-path line is the icon's last shape, a vertical line `M{x} …V…`. let end_line = |icon: &str| -> String { let last = icon.rsplit(">(); let pen = shapes(&svg("tool-pen")); @@ -331,7 +373,7 @@ mod tests { assert!(resolves(name), "{} maps to {name}, which no icon set has", tool.icon); } let catalog = icon_names(); - for (name, _) in APP_ICONS.icons { + for (name, _) in APP_ICONS.icons.iter().chain(LUCIDE_APP_ICONS.icons) { assert!(!catalog.contains(name), "{name} is in the catalog: the app's copy is refused"); } } diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index 6155d4f6e7..ef54366ba5 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -341,7 +341,7 @@ fn rows_list_by_depth_and_ruler_guide_nodes_get_no_object_row() { /// guide kind's ruler, and both glyphs are in the app's icon set. #[test] fn horizontal_and_vertical_guide_rows_show_their_own_drawn_glyphs() { - use craft::ui::primitives::{has_icon, register_app_icons}; + use craft::ui::primitives::has_icon; let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); @@ -355,7 +355,7 @@ fn horizontal_and_vertical_guide_rows_show_their_own_drawn_glyphs() { }; let (across, down) = (icon_of(false), icon_of(true)); assert_ne!(across, down, "the two kinds of guide rows look alike"); - register_app_icons(&crate::icons::APP_ICONS); + crate::icons::register(); for icon in [&across, &down] { assert!(has_icon(icon), "{icon:?} is in no icon set, so the row draws nothing"); } diff --git a/crates/ui-egui/src/tests/cut.rs b/crates/ui-egui/src/tests/cut.rs index 4732a6347b..995f87564a 100644 --- a/crates/ui-egui/src/tests/cut.rs +++ b/crates/ui-egui/src/tests/cut.rs @@ -11,7 +11,7 @@ fn the_cut_tools_have_their_own_icons_and_toolbar_slot() { let info = vectorcraft_tools::tool_info(tool).unwrap(); assert_eq!(icons::tool_icon(info.icon), icon); // The app registers its icons at start; a test run alone in its process must too. - craft::ui::primitives::register_app_icons(&icons::APP_ICONS); + icons::register(); assert!(craft::ui::primitives::has_icon(&IconId::new(icon)), "{icon}"); assert!(crate::toolbar::BASIC.iter().flat_map(|(_, slots)| slots.iter()).any(|s| s.contains(&tool) && s.contains(&"knife"))); } diff --git a/crates/ui-egui/tests/menu_access_keys.rs b/crates/ui-egui/tests/menu_access_keys.rs index c837734c99..f2a04cd75a 100644 --- a/crates/ui-egui/tests/menu_access_keys.rs +++ b/crates/ui-egui/tests/menu_access_keys.rs @@ -164,10 +164,22 @@ fn menu_access_custom_shortcut_typing_tool_altgr_and_cancel_ownership() { assert_eq!(s.app.session.tool_id(), "pen", "after the dismissal the letter selects its tool"); s.app.select_tool("selection"); - // While the bar holds the keys after a lone Alt, the letter does not reach the tool either. + // A lone Alt over the canvas is a tool modifier let go: the bar does not take the keys, and the next tool + // letters choose their tools instead of opening View or Window. s.bare_alt(); s.settle(); - assert!(is_focused(&s.ctx), "a lone Alt gives the bar the keys"); + assert!(!is_focused(&s.ctx) && !is_open(&s.ctx), "a lone Alt over the canvas leaves the bar alone"); + s.letter(Key::V, "v", Modifiers::NONE); + assert!(!is_open(&s.ctx), "V after a lone Alt opens no menu"); + s.letter(Key::P, "p", Modifiers::NONE); + assert_eq!(s.app.session.tool_id(), "pen", "P after a lone Alt chooses the Pen"); + s.app.select_tool("selection"); + + // While the bar holds the keys after F10, the letter does not reach the tool. + s.frame(vec![key(Key::F10, true, Modifiers::NONE)]); + s.frame(vec![key(Key::F10, false, Modifiers::NONE)]); + s.settle(); + assert!(is_focused(&s.ctx), "F10 gives the bar the keys"); s.letter(Key::P, "p", Modifiers::NONE); assert_eq!(s.app.session.tool_id(), "selection", "a focused bar takes the letter"); s.click(outside); diff --git a/docs/mcp.md b/docs/mcp.md index f1fa488694..83755a1937 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -15592,7 +15592,7 @@ effects keep their colours. ## Vector halftone `object.vectorHalftone` turns the selection into vector dots, lines or shapes sized by its -tone (mono, or CMYK screens multiplied over each other), clipped to the art's outline by default. An image in the +tone (the `shape` values are those of the live effect below, Euclidean and Elliptical dots included; mono, or CMYK screens multiplied over each other), clipped to the art's outline by default. An image in the art that can't be decoded is sampled as blank (no dots, or full dots with `invert`), and the result carries the `warning` that Flatten Transparency gives: @@ -17623,7 +17623,7 @@ Object › Vector Halftone without Keep Original, and the Appearance panel reope | Parameter | Values (default) | Does | |---|---|---| -| `shape` | `circle`, `ellipse`, `square`, `diamond`, `line` (`circle`) | The dot shape; lines join along a row | +| `shape` | `circle`, `ellipse`, `square`, `diamond`, `line`, `euclidean`, `elliptical` (`circle`) | The dot shape; lines join along a row; `euclidean` dots are round, meet corner to corner at 50% and turn into round holes past it; `elliptical` dots are long, join into chains along their length at 40% and on every side at 60%, then turn into long holes | | `frequency` | lines per inch 1…300 (20) | Cells per inch of the screen | | `angle` | degrees (45) | The screen angle; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it | | `mode` | `mono`, `cmyk` (`mono`) | One screen following lightness, or four ink screens following the art's ink amounts, multiplied over each other | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index db42c0d72c..8e956a2c75 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1460,6 +1460,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - With a sublayer isolated, Exit Isolation Mode (the Layers panel menu item, the isolation bar's back arrow, the Control bar button and `object.exitIsolation`) goes back one layer at a time, isolating the parent layer, and leaves isolation mode from the top-level layer, as the [help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html) and an archived [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=213) describe. As VectorCraft's own rules, Esc and the top-level layer's crumb leave isolation mode from a sublayer at any depth (`object.exitIsolation {all: true}`), a sublayer's crumb isolates that sublayer, a hidden or locked parent layer is not isolated, and a step up records no undo step (`exit_isolation_goes_up_one_layer_from_a_sublayer`, `isolation_bar_back_button_steps_up_through_sublayers`, `escape_leaves_an_isolated_sublayer_in_one_step`). - 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). + - Vector Halftone (Object › Vector Halftone and the live effect) has Euclidean and Elliptical dot shapes: Euclidean dots meet corner to corner at 50% and become round holes past it; Elliptical dots join into chains at 40% and on every side at 60%, then become long holes. Each dot covers its cell's tone. - Tab shows and hides the panels (in the Type tool it types a tab) without moving the keyboard focus onto a field, so the next shortcut or letter still works; in dialogs and panel fields it moves between fields, one press each — a numeric field's scrub label is not a tab stop of its own, and the Transform panel's, Properties panel's and Control bar's W/H link comes after the fields it sits between (`one_tab_moves_from_a_field_to_the_next`). A field's up/down spinner, the chevron that opens its presets (Stroke Weight, font size, Rotate, Export for Screens' scale) and the Transparency row's opacity slider chevron are not tab stops either. Alt+↓ with no other modifier in a field with presets opens them with the keyboard focus on the chosen one, instead of stepping the field down; Enter picks the focused preset without pressing a dialog's OK, and after a pick or Escape the field has the keyboard focus again (`tab_goes_from_field_to_field_past_the_spinner_and_the_preset_chevron`, `tab_goes_from_the_opacity_field_past_its_slider_chevron`, `alt_down_opens_a_fields_presets_for_the_keyboard`, `escape_closes_a_fields_presets_and_returns_to_the_field`). - Shift+Tab (`window.panels`) shows and hides the dock and the floating panels and leaves the toolbar and the Control bar as they are; hiding the panels with Tab or Shift+Tab also closes a panel popped out of the icon column. - The second Tab (`window.dock`) shows again only the bars the first Tab hid, after a restart too: a Control bar that was off stays off, a toolbar hidden with Window › Tools stays hidden, and panels shown with Shift+Tab in between stay shown. diff --git a/scripts/ci-clear-rolling-cache-tests.py b/scripts/ci-clear-rolling-cache-tests.py index 250fd92b1c..5684762f4e 100644 --- a/scripts/ci-clear-rolling-cache-tests.py +++ b/scripts/ci-clear-rolling-cache-tests.py @@ -36,6 +36,11 @@ def earlier(conclusion): return [{"name": WARM, "conclusion": conclusion}, {"name": "cold cache clear", "conclusion": "failure"}] +def split_job(shard, status, completed_at=None): + return {"name": f"gate / cache warm {shard}/5 (ubuntu-24.04)", "status": status, + "conclusion": "success" if status == "completed" else None, "completed_at": completed_at} + + class SaveStep(unittest.TestCase): def test_the_leg_is_saving_once_its_save_step_starts(self): self.assertFalse(clear.saving(warm_job("in_progress", steps=[("Setup", "completed", "success"), ("Gate", "in_progress", None)]))) @@ -99,6 +104,34 @@ class Deadline(unittest.TestCase): self.assertFalse(clear.started_late(warm_job("queued"), self.began)) self.assertFalse(clear.started_late(None, self.began)) + def test_split_progress_suspends_the_start_deadline(self): + for status in ("queued", "in_progress"): + with self.subTest(status=status): + jobs = [split_job(1, "completed", "2026-11-28T06:00:00Z"), split_job(2, status)] + ready = clear.start_wait_began(jobs, self.began) + self.assertIsNone(ready) + now = self.began + timedelta(seconds=clear.START_SECONDS + 60) + self.assertFalse(clear.start_overdue(None, now, ready)) + self.assertFalse(clear.started_late(warm_job("in_progress", started_at=now.isoformat()), ready)) + + def test_the_last_split_completion_starts_the_wait(self): + jobs = [split_job(1, "completed", "2026-11-28T08:00:00Z"), + split_job(2, "completed", "2026-11-28T07:00:00Z")] + ready = clear.start_wait_began(jobs, self.began) + self.assertEqual(ready, clear.parse_time("2026-11-28T08:00:00Z")) + self.assertFalse(clear.start_overdue(None, ready + timedelta(seconds=clear.START_SECONDS), ready)) + self.assertTrue(clear.start_overdue(None, ready + timedelta(seconds=clear.START_SECONDS + 1), ready)) + self.assertFalse(clear.started_late(warm_job("in_progress", started_at="2026-11-28T08:01:00Z"), ready)) + late = warm_job("in_progress", started_at=(ready + timedelta(seconds=clear.START_SECONDS + 1)).isoformat()) + self.assertTrue(clear.started_late(late, ready)) + + def test_without_split_legs_the_script_start_starts_the_wait(self): + self.assertEqual(clear.start_wait_began([], self.began), self.began) + self.assertEqual(clear.start_wait_began(ME + [warm_job("queued")], self.began), self.began) + + def test_a_split_completion_without_a_timestamp_does_not_start_the_wait(self): + self.assertIsNone(clear.start_wait_began([split_job(1, "completed")], self.began)) + class Workflow(unittest.TestCase): ci = (Path(__file__).resolve().parent.parent / ".github" / "workflows" / "ci.yml").read_text() @@ -116,10 +149,17 @@ class Workflow(unittest.TestCase): self.fail(f"no timeout-minutes under {job}") def test_the_job_outlasts_the_start_wait_and_the_save_wait(self): - # Five minutes are left for the steps before the script and for the deletion. + # Without split legs, five minutes remain for setup and deletion. spare = self.timeout_minutes("cold-cache-clear") * 60 - clear.START_SECONDS - clear.GIVE_UP_SECONDS self.assertGreaterEqual(spare, 5 * 60) + def test_the_job_allows_both_warm_builds_within_the_hosted_job_limit(self): + # Runner waits and the full start allowance may exceed the 360-minute job limit. + timeout = self.timeout_minutes("cold-cache-clear") + spare = timeout * 60 - self.timeout_minutes("gate") * 60 - clear.GIVE_UP_SECONDS + self.assertGreaterEqual(spare, 5 * 60) + self.assertEqual(timeout, 360) + def test_the_save_wait_outlasts_the_gate(self): self.assertGreater(clear.GIVE_UP_SECONDS, self.timeout_minutes("gate") * 60) @@ -156,6 +196,9 @@ class Jobs(unittest.TestCase): self.assertTrue(clear.legs_stopped([done("gate / select legs", "success"), done("gate / build (ubuntu-24.04)", "cancelled")])) self.assertFalse(clear.legs_stopped([done("gate / select legs", "success"), done("gate / build (${{ matrix.os }})", "skipped")])) self.assertFalse(clear.legs_stopped([done("gate / test 1/5 (ubuntu-24.04)", "failure")])) + # With warm-split, the saving `cache warm ()` leg also needs every `cache warm /` leg. + self.assertTrue(clear.legs_stopped([done("gate / cache warm 2/5 (ubuntu-24.04)", "failure")])) + self.assertFalse(clear.legs_stopped([done("gate / cache warm 2/5 (ubuntu-24.04)", "success")])) class Caches(unittest.TestCase): @@ -192,6 +235,60 @@ class Clock(datetime): return datetime(2026, 11, 28, 4, 0, tzinfo=timezone.utc) +class BeforeSaving(unittest.TestCase): + def run_main(self, polls): + began = Clock.now() + current = began + remaining = iter(polls) + + class PollClock(datetime): + @classmethod + def now(cls, tz=None): + return current + + def gh(url): + nonlocal current + if "/jobs?" in url: + minutes, jobs = next(remaining) + current = began + timedelta(minutes=minutes) + return {"jobs": ME + jobs} + if "/caches?" in url: + return {"actions_caches": []} + return {"run_started_at": began.isoformat()} + + env = {"GITHUB_REPOSITORY": "storytold/vectorcraft", "GITHUB_RUN_ID": "1", "GITHUB_RUN_ATTEMPT": "1"} + with mock.patch.object(clear, "gh", gh), mock.patch.object(clear.time, "sleep"), \ + mock.patch.object(clear, "datetime", PollClock), mock.patch.dict(os.environ, env), \ + mock.patch.object(clear.subprocess, "run") as delete, contextlib.redirect_stdout(io.StringIO()): + status = clear.main() + delete.assert_not_called() + return status + + def test_queued_and_running_split_legs_can_outlast_the_original_start_deadline(self): + done = split_job(1, "completed", "2026-11-28T07:40:00Z") + saved = warm_job("completed", "success", [("Post Setup", "completed", "success")], + started_at="2026-11-28T07:50:00Z") + self.assertFalse(self.run_main([ + (181, [split_job(1, "queued")]), + (201, [split_job(1, "in_progress"), warm_job("queued")]), + (220, [done, warm_job("queued")]), + (230, [done, saved]), + ])) + + def test_a_saving_leg_that_never_starts_expires_after_the_last_split_completion(self): + done = split_job(1, "completed", "2026-11-28T07:40:00Z") + self.assertEqual(self.run_main([ + (220, [done, warm_job("queued")]), + (401, [done, warm_job("queued")]), + ]), 1) + + def test_a_late_start_after_split_completion_is_rejected_even_if_already_saving(self): + done = split_job(1, "completed", "2026-11-28T07:40:00Z") + late = warm_job("in_progress", steps=[("Post Setup", "in_progress", None)], + started_at="2026-11-28T10:40:01Z") + self.assertEqual(self.run_main([(401, [done, late])]), 1) + + class AfterDeletion(unittest.TestCase): SAVING = [("Gate", "completed", "success"), ("Post Setup", "in_progress", None)] @@ -230,9 +327,17 @@ class AfterDeletion(unittest.TestCase): canceled = warm_job("completed", "cancelled", [("Gate", "completed", "success"), ("Post Setup", "completed", "cancelled")]) self.assertEqual(self.run_main(canceled), 1) + def test_a_saving_leg_skipped_after_a_failed_split_warm_leg_fails_this_job(self): + skipped = warm_job("completed", conclusion="skipped") + failed = {"name": "gate / cache warm 2/5 (ubuntu-24.04)", "status": "completed", "conclusion": "failure"} + env = {"GITHUB_REPOSITORY": "storytold/vectorcraft", "GITHUB_RUN_ID": "1", "GITHUB_RUN_ATTEMPT": "1"} + with mock.patch.object(clear, "gh", lambda url: {"jobs": ME + [failed, skipped]}), mock.patch.object(clear.time, "sleep"), \ + mock.patch.object(clear, "datetime", Clock), mock.patch.dict(os.environ, env), contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(clear.main(), 1) + def test_a_leg_that_starts_late_and_saves_deletes_nothing(self): - # Clock.now() is 04:00, so the leg starts 120 minutes 5 seconds after the script. - late = warm_job("in_progress", steps=self.SAVING, started_at="2026-11-28T06:00:05Z") + # Clock.now() is 04:00, so the leg starts 180 minutes 5 seconds after the script. + late = warm_job("in_progress", steps=self.SAVING, started_at="2026-11-28T07:00:05Z") deleted = [] def run(args, **kwargs): diff --git a/scripts/ci-clear-rolling-cache.py b/scripts/ci-clear-rolling-cache.py index e285fef70b..6a9f3cdc88 100644 --- a/scripts/ci-clear-rolling-cache.py +++ b/scripts/ci-clear-rolling-cache.py @@ -16,8 +16,10 @@ save step started saves nothing: its old entries stay, and this exits 1, so "Re- runs it again beside the re-run leg. A save step that is canceled or fails after the old entries were deleted leaves no rolling entry, so the next run starts cold, and this exits 1 too. A failure in a later post step does not count once the save step has succeeded. This also exits 1 when the -leg has not started START_SECONDS after this script started, and when the leg has not reached its -save, or its save has not finished, GIVE_UP_SECONDS after the leg started. An absent warm leg is treated as finished only +leg has not started START_SECONDS after the last split warm leg completed (or after this script +started when there are no split legs). The start deadline does not expire while a split leg is +queued or running. This exits 1 when the leg has not reached its save, or its save has not finished, +GIVE_UP_SECONDS after the leg started. An absent warm leg is treated as finished only when the most recent earlier attempt that lists it reports success and the current attempt still lists no `gate / select legs` job RERUN_GRACE_SECONDS after this script started: "Re-run all jobs" lists that job from its start, and "Re-run failed jobs" after a successful leg does not. @@ -34,9 +36,11 @@ import time REF = 'refs/heads/main' WARM_JOB = re.compile(r'^gate / cache warm \(') +SPLIT_WARM_JOB = re.compile(r'^gate / cache warm \d+/\d+ \(') # The jobs the gate's legs need (craft-common-actions .github/workflows/gate.yml): when one of -# them fails or is canceled, the legs are skipped and no warm leg is listed. -NEEDED_JOBS = re.compile(r'^gate / (select legs$|build \()') +# them fails or is canceled, the legs are skipped and no warm leg is listed. With `warm-split` the +# saving leg also needs every `cache warm /` leg. +NEEDED_JOBS = re.compile(r'^gate / (select legs$|build \(|cache warm \d+/\d+ \()') # The gate's first job. "Re-run all jobs" lists it; "Re-run failed jobs" lists it only when it # failed, and then no warm leg succeeded before. SELECT_JOB = 'gate / select legs' @@ -52,12 +56,11 @@ PAGE_SIZE = 100 # Longer than the gate's `timeout-minutes` in ci.yml and timed from the leg's own start, so a cold # leg that starts late and runs to its limit still reaches its save before this gives up. GIVE_UP_SECONDS = 160 * 60 -# How long the leg may take to start, timed from this script's start: the leg waits for -# `gate / select legs` and then for a runner, which took 44 minutes on a push to main on -# 2026-11-28. The `cold-cache-clear` job's `timeout-minutes` in ci.yml is longer than -# START_SECONDS and GIVE_UP_SECONDS together, so this exits with its own error before the job -# times out. -START_SECONDS = 120 * 60 +# How long the saving leg may take to start after the last split warm leg completed, or after +# this script started when there are no split legs. Queued or running split legs suspend this +# deadline. The `cold-cache-clear` job's 360-minute timeout in ci.yml can end the wait before +# this deadline or GIVE_UP_SECONDS expires when split builds or runner waits take too long. +START_SECONDS = 180 * 60 STOPPED = ('failure', 'cancelled', 'timed_out') # Steps with continue-on-error in craft-common-actions .github/workflows/gate.yml. TOLERATED_FAILURES = ('Trim the cache entry to this build',) @@ -103,16 +106,25 @@ def started_at(job): return parse_time(started) if started else None +def start_wait_began(jobs, began): + """The last split warm completion, the script's start without splits, or None while waiting.""" + splits = [j for j in jobs if SPLIT_WARM_JOB.match(j['name'])] + if not splits: + return began + if any(j['status'] != 'completed' or not j.get('completed_at') for j in splits): + return None + return max(parse_time(j['completed_at']) for j in splits) + + def start_overdue(job, now, began): - """True once START_SECONDS have passed since `began` (this script's start) and the warm leg - has not started.""" - return started_at(job) is None and (now - began).total_seconds() > START_SECONDS + """True once START_SECONDS have passed since the start wait began and the leg has not started.""" + return began is not None and started_at(job) is None and (now - began).total_seconds() > START_SECONDS def started_late(job, began): - """True when the warm leg started more than START_SECONDS after `began` (this script's start).""" + """True when the warm leg started more than START_SECONDS after the start wait began.""" started = started_at(job) - return started is not None and (started - began).total_seconds() > START_SECONDS + return began is not None and started is not None and (started - began).total_seconds() > START_SECONDS def gave_up(job, now): @@ -180,7 +192,8 @@ def main(): while True: jobs = gh(jobs_url) or {} job = warm_job(jobs.get('jobs', [])) - if started_late(job, began): + ready = start_wait_began(jobs.get('jobs', []), began) + if started_late(job, ready): print(f'::error::the cache warm leg did not start within {START_SECONDS // 60} minutes; nothing deleted') return 1 if job and saving(job): @@ -199,13 +212,14 @@ def main(): print('::error::the gate stopped before its cache warm leg started; nothing deleted') return 1 if job and job['status'] == 'completed': - if job.get('conclusion') in STOPPED: + # A saving leg skipped because a leg it needs failed (a `cache warm /` leg). + if job.get('conclusion') in STOPPED or job.get('conclusion') == 'skipped' and legs_stopped(jobs.get('jobs', [])): print(f'::error::{NO_SAVE}') return 1 print('the cache warm leg finished without a save step; nothing deleted') return now = datetime.now(timezone.utc) - if start_overdue(job, now, began): + if start_overdue(job, now, ready): print(f'::error::the cache warm leg did not start within {START_SECONDS // 60} minutes; nothing deleted') return 1 if gave_up(job, now): diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 3ada901300..8eea32c1f3 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -49,6 +49,7 @@ commands: ci shard shard $GATE_SHARD of $GATE_SHARDS of ci (xtask/src/shards.rs): a test shard runs the tests and doctests of its crates, the last shard the other steps ci warm build what every shard builds, without running it (fills the gate's cache); with + GATE_SHARD of GATE_SHARDS set, only what that shard builds; with CRAFT_CACHE_UNITS set, appends Cargo's JSON messages for each build to that file shards list the crates each shard tests; fails when a member is in no shard or in two, or builds with other features in its shard than in the whole workspace @@ -417,18 +418,26 @@ fn cmd_ci_shard() -> Result<(), String> { /// features over the packages each command selects). The test builds select the same crates and /// targets as the test shards' runs, so the cache also holds the test executables the shards run. /// +/// With `GATE_SHARD` and `GATE_SHARDS` set (the gate's split warm legs), it builds only what that +/// shard builds: a test shard's tests, or the checks shard's builds. A split's later parts build +/// nothing in either case, since part 1 builds the same tests. +/// /// In a leg that saves the cache, every build records its units in `CRAFT_CACHE_UNITS` /// (xtask/src/cache_units.rs), xtask's own build included. fn cmd_ci_warm() -> Result<(), String> { + let var = |key: &str| match std::env::var(key) { + Ok(value) => Ok(Some(value)), + Err(std::env::VarError::NotPresent) => Ok(None), + Err(std::env::VarError::NotUnicode(_)) => Err(format!("ci warm: {key} is not valid Unicode")), + }; + let (shard, count) = (var("GATE_SHARD")?, var("GATE_SHARDS")?); + let only = shards::warm_only(shard.as_deref(), count.as_deref())?; cache_units::record_xtask()?; let checked = shards::run()?; + let (tests, checks) = shards::warm_plan(&checked, only); let mut steps: Vec = Vec::new(); - for shard in checked { - // A split's later parts build the same tests as its first. - if let shards::Shard::Tests(runs, part) = shard { - if part.is_some_and(|p| !p.is_first()) { - continue; - } + for i in tests { + if let shards::Shard::Tests(runs, _) = checked[i].clone() { for r in runs { steps.push(( "build tests", @@ -440,6 +449,14 @@ fn cmd_ci_warm() -> Result<(), String> { } } } + if checks { + push_warm_checks(&mut steps); + } + run_steps(&steps) +} + +/// The builds of the checks shard that [`cmd_ci_warm`] runs. +fn push_warm_checks(steps: &mut Vec) { steps.push(( "clippy", Box::new(|| { @@ -463,7 +480,6 @@ fn cmd_ci_warm() -> Result<(), String> { }), )); steps.push(("wasm", Box::new(cmd_wasm))); - run_steps(&steps) } /// The command `ci warm` builds the tests of one run of a test shard with, and its description. diff --git a/xtask/src/shards.rs b/xtask/src/shards.rs index 072e55f280..009256ccd4 100644 --- a/xtask/src/shards.rs +++ b/xtask/src/shards.rs @@ -467,10 +467,107 @@ pub fn run() -> Result, String> { Ok(shards) } +/// The shard `cargo xtask ci warm` builds alone, as an index into [`GROUPS`], from the gate's +/// `GATE_SHARD` and `GATE_SHARDS`: `None` (every shard) when neither is set. Setting only one, +/// a value that is not a number, a count other than the number of shards, or a shard out of range +/// is an error. +pub fn warm_only(shard: Option<&str>, count: Option<&str>) -> Result, String> { + let (shard, count) = match (shard, count) { + (None, None) => return Ok(None), + (Some(shard), Some(count)) => (shard, count), + _ => return Err("ci warm: GATE_SHARD and GATE_SHARDS are set together or not at all".into()), + }; + let number = + |key: &str, value: &str| -> Result { value.trim().parse().map_err(|_| format!("ci warm: {key} is `{value}`, not a number")) }; + let (shard, count) = (number("GATE_SHARD", shard)?, number("GATE_SHARDS", count)?); + if count != GROUPS.len() { + return Err(format!( + "ci warm: GATE_SHARDS is {count}, and xtask/src/shards.rs has {} shards (test-shards in .github/workflows/ci.yml)", + GROUPS.len() + )); + } + if !(1..=count).contains(&shard) { + return Err(format!("ci warm: GATE_SHARD is {shard}, not 1 to {count}")); + } + Ok(Some(shard - 1)) +} + +/// What `cargo xtask ci warm` builds of `shards`: the indices of the test shards whose tests it +/// builds, and whether it runs the checks shard's builds. With `only` (from [`warm_only`]) it +/// builds that shard alone, and without it every shard. A split's later parts build nothing: they +/// build the same tests as part 1, whose leg puts them in the cache. +pub fn warm_plan(shards: &[Shard], only: Option) -> (Vec, bool) { + let mut tests = Vec::new(); + let mut checks = false; + for (i, shard) in shards.iter().enumerate() { + if only.is_some_and(|k| k != i) { + continue; + } + match shard { + Shard::Checks => checks = true, + Shard::Tests(_, part) if part.is_some_and(|p| !p.is_first()) => {} + Shard::Tests(..) => tests.push(i), + } + } + (tests, checks) +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn warm_builds_every_shard_unless_the_gate_names_one() { + let n = GROUPS.len().to_string(); + assert_eq!(warm_only(None, None), Ok(None)); + assert_eq!(warm_only(Some("1"), Some(&n)), Ok(Some(0))); + assert_eq!(warm_only(Some(&n), Some(&n)), Ok(Some(GROUPS.len() - 1))); + for (shard, count) in [(Some("1"), None), (None, Some(n.as_str())), (Some("0"), Some(n.as_str())), (Some("x"), Some(n.as_str()))] { + assert!(warm_only(shard, count).is_err(), "{shard:?} of {count:?}"); + } + let past = (GROUPS.len() + 1).to_string(); + assert!(warm_only(Some(&past), Some(&n)).is_err()); + assert!(warm_only(Some("1"), Some(&past)).is_err()); + } + + #[test] + fn warm_builds_each_shard_of_the_plan() { + let ws = [m("a"), m("b")]; + let shards = assign(&[Group::Part(&SPLIT, 1), Group::Part(&SPLIT, 2), Group::Rest, Group::Checks], &ws).unwrap(); + assert_eq!(warm_plan(&shards, None), (vec![0, 2], true)); + assert_eq!(warm_plan(&shards, Some(0)), (vec![0], false)); + assert_eq!(warm_plan(&shards, Some(1)), (vec![], false)); + assert_eq!(warm_plan(&shards, Some(2)), (vec![2], false)); + assert_eq!(warm_plan(&shards, Some(3)), (vec![], true)); + // The real plan: every leg the gate names builds its own shard (a split's later part + // builds nothing), and the legs together, like a full warm, build every crate's tests + // once and the checks. + let real = assign(GROUPS, &members(&crate::metadata().unwrap()).unwrap()).unwrap(); + let mut owned: Vec<&str> = real.iter().flat_map(owners).map(|(name, _)| name).collect(); + owned.sort_unstable(); + let (mut legs, mut leg_checks) = (Vec::new(), 0); + for i in 0..GROUPS.len() { + let n = GROUPS.len().to_string(); + let only = warm_only(Some(&(i + 1).to_string()), Some(&n)).unwrap(); + let (tests, checks) = warm_plan(&real, only); + let want = match &real[i] { + Shard::Checks => (vec![], true), + Shard::Tests(_, Some(p)) if !p.is_first() => (vec![], false), + Shard::Tests(..) => (vec![i], false), + }; + assert_eq!((tests.clone(), checks), want, "shard {}", i + 1); + legs.extend(tests); + leg_checks += usize::from(checks); + } + let (tests, checks) = warm_plan(&real, None); + assert!(checks); + assert_eq!(leg_checks, 1); + assert_eq!(tests, legs); + let mut built: Vec<&str> = tests.iter().flat_map(|&i| crates(&real[i])).collect(); + built.sort_unstable(); + assert_eq!(built, owned); + } + fn m(name: &str) -> Member { Member { name: name.into(), id: format!("path+file:///w/{name}#0.1.0"), version: "0.1.0".into(), doctests: true } }