diff --git a/README.md b/README.md index 158a4ca2c8..8e51d4930e 100644 --- a/README.md +++ b/README.md @@ -257,7 +257,7 @@ All 57 approximated Photoshop-style raster filters are available. The Effect Gal **What's missing:** - reliable exchange of .ai files (layer structure in real files; the editing copy a save writes keeps live effects only on paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports (see [docs/file-format-parity.md](docs/file-format-parity.md)), leaves out other objects' effects other than geometry effects, and writes live objects as their art); - an interaction-fidelity pass covering every tool's modifiers and small behaviours; -- 3D and Materials beyond the initial live Revolve (Extrude & Bevel, Inflate, Rotate, materials); +- the rest of 3D and Materials (base and Adobe Substance materials, shadows from lights after the first, ray-traced rendering, Turntable; see [docs/three-d.md](docs/three-d.md)); - CJK composition for vertical type (vertical type itself has initial support, with a Japanese interface); - scripting, and the rest of Variables (image and graph kinds, dataset import); - generative AI features. @@ -287,7 +287,9 @@ signed and published. Every bundled asset is listed with its licence in [`ASSETS |---|---|---| | x64 (64-bit Intel/AMD) | `vectorcraft--windows-x64.msi` | `vectorcraft--windows-x64-portable.zip` | | arm64 (Snapdragon and other ARM PCs) | `vectorcraft--windows-arm64.msi` | `vectorcraft--windows-arm64-portable.zip` | -| x86 (32-bit) | `vectorcraft--windows-x86.msi` | `vectorcraft--windows-x86-portable.zip` | + +For 32-bit Windows, [VectorCraft v0.22.0](https://github.com/storytold/vectorcraft/releases/tag/v0.22.0) +was the last release with both an x86 MSI and portable ZIP. Installers and executables are code-signed. @@ -306,13 +308,18 @@ Installers and executables are code-signed. | Flatpak | `vectorcraft--linux-x86_64.flatpak` | `vectorcraft--linux-aarch64.flatpak` | Sandboxed; `flatpak install --user ` | | Debian/Ubuntu | `vectorcraft--linux-x86_64.deb` | `vectorcraft--linux-aarch64.deb` | | | Fedora/RHEL/openSUSE | `vectorcraft--linux-x86_64.rpm` | `vectorcraft--linux-aarch64.rpm` | | +| Arch Linux | `vectorcraft--linux-x86_64.pkg.tar.zst` | `vectorcraft--linux-aarch64.pkg.tar.zst` | | | Tarball | `vectorcraft--linux-x86_64.tar.gz` | `vectorcraft--linux-aarch64.tar.gz` | Unpack anywhere | +RISC-V (riscv64) packages are `vectorcraft--linux-riscv64.deb`, +`vectorcraft--linux-riscv64.rpm`, and `vectorcraft--linux-riscv64.tar.gz`. + ### FreeBSD | Build | File | |---|---| | x86_64 | `vectorcraft--freebsd-x86_64.tar.gz` | +| aarch64 (ARM64) | `vectorcraft--freebsd-aarch64.tar.gz` | ### Web (WebAssembly) diff --git a/assets/icons/dc-al-bottom.svg b/assets/icons/dc-al-bottom.svg index 73ca1c4b02..45b61c2338 100644 --- a/assets/icons/dc-al-bottom.svg +++ b/assets/icons/dc-al-bottom.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-al-center.svg b/assets/icons/dc-al-center.svg index 2e8e9e978f..9b1d61bd3f 100644 --- a/assets/icons/dc-al-center.svg +++ b/assets/icons/dc-al-center.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-al-hcenter.svg b/assets/icons/dc-al-hcenter.svg index ae7c705f0a..f5561a859e 100644 --- a/assets/icons/dc-al-hcenter.svg +++ b/assets/icons/dc-al-hcenter.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-al-left.svg b/assets/icons/dc-al-left.svg index e8088d1386..0d0c93d70f 100644 --- a/assets/icons/dc-al-left.svg +++ b/assets/icons/dc-al-left.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-al-right.svg b/assets/icons/dc-al-right.svg index 6f5407ccf0..c3b38820a8 100644 --- a/assets/icons/dc-al-right.svg +++ b/assets/icons/dc-al-right.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-al-top.svg b/assets/icons/dc-al-top.svg index 9a32bc30cf..1ba453a482 100644 --- a/assets/icons/dc-al-top.svg +++ b/assets/icons/dc-al-top.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-al-vcenter.svg b/assets/icons/dc-al-vcenter.svg index 29e42fb45c..cc900e5bc1 100644 --- a/assets/icons/dc-al-vcenter.svg +++ b/assets/icons/dc-al-vcenter.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-alignto-artboard.svg b/assets/icons/dc-alignto-artboard.svg index a04ffb9970..9e539b8050 100644 --- a/assets/icons/dc-alignto-artboard.svg +++ b/assets/icons/dc-alignto-artboard.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-alignto-key.svg b/assets/icons/dc-alignto-key.svg index 5dd9f88b88..ee6c886f3a 100644 --- a/assets/icons/dc-alignto-key.svg +++ b/assets/icons/dc-alignto-key.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-alignto-selection.svg b/assets/icons/dc-alignto-selection.svg index d145c91c0f..22767bb02d 100644 --- a/assets/icons/dc-alignto-selection.svg +++ b/assets/icons/dc-alignto-selection.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-dist-bottom.svg b/assets/icons/dc-dist-bottom.svg index 06f9e16c0a..cdd41fbbc5 100644 --- a/assets/icons/dc-dist-bottom.svg +++ b/assets/icons/dc-dist-bottom.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-dist-hcenter.svg b/assets/icons/dc-dist-hcenter.svg index 30cabd1ad7..83ebc04416 100644 --- a/assets/icons/dc-dist-hcenter.svg +++ b/assets/icons/dc-dist-hcenter.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-dist-hspace.svg b/assets/icons/dc-dist-hspace.svg index bc7a749459..b26492efc5 100644 --- a/assets/icons/dc-dist-hspace.svg +++ b/assets/icons/dc-dist-hspace.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-dist-left.svg b/assets/icons/dc-dist-left.svg index efc53ab8e6..2b381ea7a9 100644 --- a/assets/icons/dc-dist-left.svg +++ b/assets/icons/dc-dist-left.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-dist-right.svg b/assets/icons/dc-dist-right.svg index 1dc5566767..9461ef385e 100644 --- a/assets/icons/dc-dist-right.svg +++ b/assets/icons/dc-dist-right.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-dist-top.svg b/assets/icons/dc-dist-top.svg index f0560524ed..8e070c2028 100644 --- a/assets/icons/dc-dist-top.svg +++ b/assets/icons/dc-dist-top.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-dist-vcenter.svg b/assets/icons/dc-dist-vcenter.svg index 4b0b5e76a1..bb5266c039 100644 --- a/assets/icons/dc-dist-vcenter.svg +++ b/assets/icons/dc-dist-vcenter.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-dist-vspace.svg b/assets/icons/dc-dist-vspace.svg index 8a2429cb98..0adda19d8a 100644 --- a/assets/icons/dc-dist-vspace.svg +++ b/assets/icons/dc-dist-vspace.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-pf-crop.svg b/assets/icons/dc-pf-crop.svg index 70f9dfc9a2..ba8af6315e 100644 --- a/assets/icons/dc-pf-crop.svg +++ b/assets/icons/dc-pf-crop.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-pf-divide.svg b/assets/icons/dc-pf-divide.svg index 9c4299adff..e1719c8226 100644 --- a/assets/icons/dc-pf-divide.svg +++ b/assets/icons/dc-pf-divide.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-pf-exclude.svg b/assets/icons/dc-pf-exclude.svg index c535d82d9c..8e6a236f0a 100644 --- a/assets/icons/dc-pf-exclude.svg +++ b/assets/icons/dc-pf-exclude.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-pf-intersect.svg b/assets/icons/dc-pf-intersect.svg index fec68213c1..f186706ad9 100644 --- a/assets/icons/dc-pf-intersect.svg +++ b/assets/icons/dc-pf-intersect.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-pf-merge.svg b/assets/icons/dc-pf-merge.svg index bbf2641547..adf641c87f 100644 --- a/assets/icons/dc-pf-merge.svg +++ b/assets/icons/dc-pf-merge.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-pf-minus-back.svg b/assets/icons/dc-pf-minus-back.svg index 487a240cab..8c47aed2e1 100644 --- a/assets/icons/dc-pf-minus-back.svg +++ b/assets/icons/dc-pf-minus-back.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-pf-minus-front.svg b/assets/icons/dc-pf-minus-front.svg index 6d077acca6..2363e726b9 100644 --- a/assets/icons/dc-pf-minus-front.svg +++ b/assets/icons/dc-pf-minus-front.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-pf-outline.svg b/assets/icons/dc-pf-outline.svg index cd0b691f5b..9fc55c5022 100644 --- a/assets/icons/dc-pf-outline.svg +++ b/assets/icons/dc-pf-outline.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-pf-trim.svg b/assets/icons/dc-pf-trim.svg index 8b448fc44c..714e6cdaef 100644 --- a/assets/icons/dc-pf-trim.svg +++ b/assets/icons/dc-pf-trim.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-pf-unite.svg b/assets/icons/dc-pf-unite.svg index a3eefb76a1..89a5dbdc87 100644 --- a/assets/icons/dc-pf-unite.svg +++ b/assets/icons/dc-pf-unite.svg @@ -1 +1 @@ - + diff --git a/crates/cad/src/hpgl/write.rs b/crates/cad/src/hpgl/write.rs index 4e08fb3f5e..d951e92681 100644 --- a/crates/cad/src/hpgl/write.rs +++ b/crates/cad/src/hpgl/write.rs @@ -304,7 +304,7 @@ pub fn export_regions(doc: &Document, opts: &HpglOptions, regions: &[Rect]) -> R warn(&mut warnings, PAST_CLASSIC_RANGE); } let bytes = match opts.version { - Version::Hpgl => plain(&by_pen), + Version::Hpgl => craft_plotter::hpgl::write::write_hpgl(&by_pen), Version::Hpgl2 => encoded(&by_pen, &pens), }; out.push(HpglOutput { bytes, pens: pens.clone(), warnings, setting_notes }); @@ -511,27 +511,6 @@ fn inner_first(left: Vec<(usize, Vec<(i64, i64)>)>, outer: &[Vec], waitin paths.extend(held.into_iter().flatten()); } -/// HP-GL: `IN;`, each pen's paths as `PU` and `PD`, `PU;SP0;`. -fn plain(by_pen: &[Vec>]) -> Vec { - let mut s = String::from("IN;"); - for (i, paths) in by_pen.iter().enumerate().filter(|(_, p)| !p.is_empty()) { - s.push_str(&format!("PU;SP{};", i + 1)); - for path in paths { - let Some(((x, y), rest)) = path.split_first() else { continue }; - s.push_str(&format!("PU{x},{y};PD")); - for (k, (x, y)) in rest.iter().enumerate() { - if k > 0 { - s.push(','); - } - s.push_str(&format!("{x},{y}")); - } - s.push(';'); - } - } - s.push_str("PU;SP0;"); - s.into_bytes() -} - /// HP-GL/2: `IN;`, the palette, each pen's paths as one `PE`, `PU;SP0;`. fn encoded(by_pen: &[Vec>], pens: &[[u8; 3]]) -> Vec { let pens: Vec<_> = pens.iter().enumerate().map(|(index, &rgb)| craft_plotter::hpgl::write::Pen { number: index + 1, rgb }).collect(); diff --git a/crates/cad/src/hpgl/write/tests.rs b/crates/cad/src/hpgl/write/tests.rs index f04b331696..b371c832db 100644 --- a/crates/cad/src/hpgl/write/tests.rs +++ b/crates/cad/src/hpgl/write/tests.rs @@ -112,6 +112,21 @@ fn each_new_color_is_the_next_pen_and_pens_draw_in_turn() { assert!(!text(&table).contains("SP2"), "{}", text(&table)); } +#[test] +fn classic_hpgl_preserves_explicit_pen_gaps_and_path_order() { + let d = doc_with(|d| { + vec![ + stroked(d, line((130.0, 70.0), (140.0, 80.0)), Color::rgb8(0, 0, 255)), + stroked(d, line((10.0, 20.0), (20.0, 40.0)), Color::rgb8(255, 0, 0)), + stroked(d, line((80.0, 60.0), (90.0, 70.0)), Color::rgb8(0, 0, 255)), + ] + }); + let out = + plot(&d, &HpglOptions { version: Version::Hpgl, origin: Origin::Center, pens: vec![[255, 0, 0], [0, 255, 0], [0, 0, 255]], ..opts(&d) }); + // The empty green pen must leave the two blue paths on pen three. + assert_eq!(out.bytes, b"IN;PU;SP1;PU-1270,423;PD-1129,141;PU;SP3;PU423,-282;PD564,-423;PU-282,-141;PD-141,-282;PU;SP0;"); +} + #[test] fn a_filled_path_is_its_closed_outline_and_a_stroke_its_line() { let d = doc_with(|d| { diff --git a/crates/doc/src/appearance/profile.rs b/crates/doc/src/appearance/profile.rs index e6f69e6670..4b0b59ce54 100644 --- a/crates/doc/src/appearance/profile.rs +++ b/crates/doc/src/appearance/profile.rs @@ -32,10 +32,9 @@ impl WidthProfile { /// weighted harmonic mean of the secants either side (Fritsch–Carlson). That is C1 continuous /// and monotone between points, so it never overshoots them, a point eases into its neighbours /// instead of making a corner, and moving one reshapes the curve as far as its neighbours' - /// neighbours (their slopes depend on it). The ends of a run use the one-sided PCHIP slope - /// from its first two secants, or the secant when it has only two points, so a two-point - /// profile stays a straight taper and the lens is a parabola. Two points at one `t` are still - /// a step: each run either side ends independently at it. + /// neighbours (their slopes depend on it). The ends of a run take the span's own slope, so a + /// two-point profile stays a straight taper. Two points at one `t` are still a step: each run + /// either side ends independently at it. pub fn at_points(p: &[(f64, f64, f64)], t: f64) -> (f64, f64) { if p.is_empty() { return (1.0, 1.0); @@ -263,27 +262,12 @@ impl AngleProfile { /// How close two width points' positions are to make a step ([`WidthProfile::around`]). const STEP: f64 = 1e-7; -/// The one-sided three-point PCHIP slope at the start of a run, from the first two secants. -/// A sign change caps the slope, and a slope that turns back on the first secant is flattened. -/// Runs of only two points use their secant instead (see [`tangent`]). -fn end_slope(h0: f64, h1: f64, d0: f64, d1: f64) -> f64 { - let m = ((2.0 * h0 + h1) * d0 - h0 * d1) / (h0 + h1); - if !m.is_finite() || m * d0 <= 0.0 { - return 0.0; - } - if d0 * d1 < 0.0 { - return if d0 > 0.0 { m.min(3.0 * d0) } else { m.max(3.0 * d0) }; - } - m -} - /// The slope of one side (`v` reads it from a point) of width profile `p` at its point `j`, in /// width per unit of position: Fritsch–Carlson's choice for a monotone cubic curve. It is 0 where /// the point is wider or narrower than both neighbours, and the weighted harmonic mean of the /// slopes of the spans on either side elsewhere (never more than three times either, so no span -/// overshoots its points). The ends of a run take the one-sided three-point PCHIP slope, or their -/// secant when the run has only two points; a step ends the run on each side, so the points either -/// side of it do not see across it. +/// overshoots its points). The ends of a run take their secant; a step ends the run on each +/// side, so the points either side of it do not see across it. fn tangent(p: &[(f64, f64, f64)], j: usize, v: fn(&(f64, f64, f64)) -> f64) -> f64 { let Some(q) = p.get(j) else { return 0.0 }; let before = j.checked_sub(1).and_then(|k| p.get(k)).filter(|a| q.0 - a.0 > STEP); @@ -298,18 +282,8 @@ fn tangent(p: &[(f64, f64, f64)], j: usize, v: fn(&(f64, f64, f64)) -> f64) -> f let (h0, h1) = (q.0 - a.0, b.0 - q.0); 3.0 * (h0 + h1) / ((2.0 * h1 + h0) / d0 + (h1 + 2.0 * h0) / d1) } - // The end of a run: its previous two points set a one-sided three-point slope, or its - // secant when the run has only two points (the point before `a` is on the other side of a - // step, or does not exist). - (Some(a), None) => { - let Some(prev) = j.checked_sub(2).and_then(|k| p.get(k)).filter(|z| a.0 - z.0 > STEP) else { return slope(a, q) }; - end_slope(q.0 - a.0, a.0 - prev.0, slope(a, q), slope(prev, a)) - } - // The start of a run, symmetrically. - (None, Some(b)) => { - let Some(next) = p.get(j + 2).filter(|z| z.0 - b.0 > STEP) else { return slope(q, b) }; - end_slope(b.0 - q.0, next.0 - b.0, slope(q, b), slope(b, next)) - } + (Some(a), None) => slope(a, q), + (None, Some(b)) => slope(q, b), (None, None) => 0.0, } } @@ -464,12 +438,12 @@ mod tests { #[test] fn widths_run_smoothly_through_width_points() { // A swell in the middle: flat at its widest, and a quarter of the way along above the - // straight ramp from 1 to 3 (2) because the end eases out of the first point. + // straight ramp from 1 to 3 (2). let swell = WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.5, 3.0, 2.0), (1.0, 1.0, 1.0)] }; let (before, after) = slopes(&swell, 0.5); assert!(before.abs() < 1e-4 && after.abs() < 1e-4, "{before} {after}"); let (l, r) = swell.at(0.25); - assert!((l - 2.5).abs() < 1e-12 && (r - 1.75).abs() < 1e-12, "{l} {r}"); + assert!((l - 2.25).abs() < 1e-12 && (r - 1.625).abs() < 1e-12, "{l} {r}"); // Rising on both sides of a point: the slope is the same either side of it. let rise = WidthProfile { points: vec![(0.0, 0.0, 0.0), (0.3, 1.0, 1.0), (1.0, 4.0, 4.0)] }; let (before, after) = slopes(&rise, 0.3); diff --git a/crates/doc/src/appearance/tests.rs b/crates/doc/src/appearance/tests.rs index ab0ba559f0..c91348d57f 100644 --- a/crates/doc/src/appearance/tests.rs +++ b/crates/doc/src/appearance/tests.rs @@ -221,9 +221,9 @@ fn strokes_without_pressure_round_trip_unchanged() { fn profile_interp() { let p = WidthProfile::lens(); assert_eq!(p.at(0.5), (1.0, 1.0)); - // The lens is a parabola between its ends, so a quarter of the way along is 0.75: above the - // 0.5 a straight taper would give. - assert_eq!(p.at(0.25), (0.75, 0.75)); + // Half way up the lens the width curves above the straight ramp (0.5), flattening into its + // widest point. + assert_eq!(p.at(0.25), (0.625, 0.625)); assert_eq!(p.at(2.0), (0.0, 0.0)); } @@ -259,13 +259,13 @@ fn profile_two_point_runs_are_linear() { } } -/// The lens's one-sided end slopes make it a parabola: at a quarter of the way it is 0.75, -/// above the 0.5 a straight line between its points would give. +/// The lens swells above a straight line between its points: a quarter of the way along it is +/// 0.625, easing flat into its widest point rather than rising at a constant rate. #[test] fn profile_lens_is_convex() { let p = WidthProfile::lens(); - assert!((p.at(0.25).0 - 0.75).abs() < 1e-12); - assert!((p.at(0.75).0 - 0.75).abs() < 1e-12); + assert!((p.at(0.25).0 - 0.625).abs() < 1e-12); + assert!((p.at(0.75).0 - 0.625).abs() < 1e-12); for k in 1..25 { let t = k as f64 / 100.0; assert!(p.at(t).0 > 2.0 * t, "{} at {t}", p.at(t).0); diff --git a/crates/doc/src/selection.rs b/crates/doc/src/selection.rs index d2488b8b5f..f0b8a5609f 100644 --- a/crates/doc/src/selection.rs +++ b/crates/doc/src/selection.rs @@ -23,8 +23,9 @@ pub struct Selection { /// `objects` with no entry here is fully selected; `segments` distinguishes segment picks. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub anchors: BTreeMap>, - /// Explicitly selected segments. Their endpoints in `anchors` move with them, but are not - /// selected anchor points: Delete cuts connections and their anchor squares stay hollow. + /// Explicitly selected segments. Their endpoints in `anchors` move with them (the arrow keys + /// bend a curved one instead), but are not selected anchor points: Delete cuts connections and + /// their anchor squares stay hollow. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub segments: BTreeMap>, /// Key object for Align, one object of a selection of two or more. [`Selection::prune`] clears diff --git a/crates/effects/src/stroke/tests.rs b/crates/effects/src/stroke/tests.rs index 1c79fd4805..aa4ea8dc9f 100644 --- a/crates/effects/src/stroke/tests.rs +++ b/crates/effects/src/stroke/tests.rs @@ -232,14 +232,16 @@ fn line_outline_uses_the_profile_dashes_or_a_plain_stroke() { let plain = line_outline(&l, &stroke(10.0, |_| {}), 10.0, 1e-3); assert!(near(plain.area().abs(), 1000.0, 1e-6)); let lens = line_outline(&l, &stroke(10.0, |s| s.profile = Some(WidthProfile::lens())), 10.0, 1e-3); - // The lens is a parabola between its ends: 2/3 of the full-width band. - assert!(near(lens.area().abs(), 2000.0 / 3.0, 0.1)); - // Each dash takes its widths from where it sits along the lens (0 → 1 → 0). + // The lens swells on a cubic, flat at the middle: 7/12 of the full-width band (#5714). + assert!(near(lens.area().abs(), 1000.0 * 7.0 / 12.0, 0.05)); + // Each dash takes its widths from where it sits along the lens (0 → 1 → 0). Half of the lens + // rises as w(u) = u + u² − u³ (u from 0 to 1 across that half): the dash over 0..25 covers + // its first half, ∫₀^½ w = 29/192, the one over 50..75 the wider other half, 83/192. let st = stroke(10.0, |s| { s.profile = Some(WidthProfile::lens()); s.dash = Some(dashed(&[25.0, 25.0], 0.0)); }); - assert!(near(line_outline(&l, &st, 10.0, 1e-3).area().abs(), 1000.0 / 3.0, 0.1)); + assert!(near(line_outline(&l, &st, 10.0, 1e-3).area().abs(), 500.0 * (29.0 + 83.0) / 192.0, 0.05)); assert!(line_outline(&BezPath::new(), &st, 10.0, 1e-3).elements().is_empty()); } diff --git a/crates/effects/src/stroke/tests_fit.rs b/crates/effects/src/stroke/tests_fit.rs index cc69606aee..f7fecb9abc 100644 --- a/crates/effects/src/stroke/tests_fit.rs +++ b/crates/effects/src/stroke/tests_fit.rs @@ -169,10 +169,9 @@ fn each_dash_takes_its_width_from_the_profile_along_the_whole_path() { s.dash = Some(Dash { pattern: vec![10.0, 10.0], offset: 0.0, align_corners: false }); }); let o = line_outline(&line(100.0), &st, 10.0, 1e-3); - // The dash over 40..50 is near the lens's widest point; the one over 0..10 near its tip, - // where the smooth profile is thinner than a straight ramp (a parabola's first tenth). + // The dash over 40..50 is near the lens's widest point; the one over 0..10 near its tip. assert!(o.contains(Point::new(45.0, 4.0)) && o.contains(Point::new(45.0, -4.0)), "middle dash is wide"); - assert!(o.contains(Point::new(5.0, 0.8)) && !o.contains(Point::new(5.0, 1.2)), "first dash is thin"); + assert!(!o.contains(Point::new(5.0, 2.0)) && o.contains(Point::new(5.0, 0.3)), "first dash is thin"); assert!(!o.contains(Point::new(15.0, 0.0)), "gaps stay empty"); // Dots too: a round dot near the middle is bigger than one near an end. let st = stroke(10.0, |s| { @@ -181,7 +180,7 @@ fn each_dash_takes_its_width_from_the_profile_along_the_whole_path() { s.dash = Some(Dash { pattern: vec![0.0, 10.0], offset: 0.0, align_corners: false }); }); let o = line_outline(&line(100.0), &st, 10.0, 1e-3); - assert!(o.contains(Point::new(50.0, 4.5)) && o.contains(Point::new(10.0, 1.4)) && !o.contains(Point::new(10.0, 2.0))); + assert!(o.contains(Point::new(50.0, 4.5)) && !o.contains(Point::new(10.0, 1.5)) && o.contains(Point::new(10.0, 0.5))); } /// An L whose corner turns 90° at (100, 0), or a sharp V turning back at (100, 0). diff --git a/crates/effects/src/stroke/tests_gradient.rs b/crates/effects/src/stroke/tests_gradient.rs index 784c84d1db..55aeda8d7f 100644 --- a/crates/effects/src/stroke/tests_gradient.rs +++ b/crates/effects/src/stroke/tests_gradient.rs @@ -138,8 +138,9 @@ fn across_runs_from_the_left_edge_to_the_right() { let mut lens = st.clone(); lens.profile = Some(WidthProfile::lens()); let sl = slices(&line, &lens); - // A quarter of the way along, the lens is three quarters as wide: its top edge is 3.75 up. - assert!(param(&sl, Point::new(25.0, -3.6)).unwrap() < 0.05); + // A quarter of the way along, the lens is 0.625 as wide (its curve, #5714): its top edge is + // 3.125 up. + assert!(param(&sl, Point::new(25.0, -3.0)).unwrap() < 0.05); assert!((param(&sl, Point::new(50.0, -2.5)).unwrap() - 0.25).abs() < 0.02); } diff --git a/crates/effects/src/stroke/width.rs b/crates/effects/src/stroke/width.rs index 0b307cc6b5..f52b82ba9f 100644 --- a/crates/effects/src/stroke/width.rs +++ b/crates/effects/src/stroke/width.rs @@ -53,7 +53,7 @@ pub(super) fn width_outline_near(bp: &BezPath, width: f64, profile: &WidthProfil kept.push(!(a.x.max(b.x) < near.x0 || a.x.min(b.x) > near.x1 || a.y.max(b.y) < near.y0 || a.y.min(b.y) > near.y1)); } if kept.iter().all(|v| *v) { - ctx.subpath(&mut out, &flat, &segs, closed, (0.0, 1.0), count as f64); + ctx.subpath(&mut out, &flat, &segs, closed, (0.0, 1.0)); continue; } cut = true; @@ -78,14 +78,14 @@ pub(super) fn width_outline_near(bp: &BezPath, width: f64, profile: &WidthProfil } else if let Some(part) = run.take() && part.pts.len() > 1 { - ctx.subpath(&mut out, &part, &segs, false, (from, walked / total), count as f64); + ctx.subpath(&mut out, &part, &segs, false, (from, walked / total)); } walked += lengths[i]; } if let Some(part) = run && part.pts.len() > 1 { - ctx.subpath(&mut out, &part, &segs, false, (from, walked / total), count as f64); + ctx.subpath(&mut out, &part, &segs, false, (from, walked / total)); } } cut.then_some(out) @@ -102,8 +102,7 @@ pub(super) fn outline_spans(bp: &BezPath, spans: &[(f64, f64)], width: f64, prof let flat = flatten(&segs, closed, ctx.tol); if flat.pts.len() > 1 { let span = spans.get(i).copied().unwrap_or((0.0, 1.0)); - let pieces = if closed { flat.pts.len() } else { flat.pts.len() - 1 }.max(1); - ctx.subpath(&mut out, &flat, &segs, closed, span, pieces as f64 / (span.1 - span.0)); + ctx.subpath(&mut out, &flat, &segs, closed, span); } } out @@ -215,25 +214,17 @@ pub(super) fn flatten(segs: &[PathSeg], closed: bool, tol: f64) -> Flat { /// Insert samples where the profile has width points and between them, so its smooth curve is /// drawn as a smooth outline along straight runs too (the two points of a discontinuous point -/// share one sample). `span` maps the subpath onto the profile (see [`outline_spans`]). -fn densify( - flat: &Flat, - segs: &[PathSeg], - closed: bool, - profile: &WidthProfile, - span: (f64, f64), - density: f64, -) -> (Vec, Vec, Vec) { - // Two samples per profile segment: the segment end plus its midpoint. The outline is fitted - // with cubics through these points, so a smooth width curve needs far fewer samples than it - // did when every pair of samples became a separate cubic. A profile with a strong bend gets - // one more subdivision; a flat profile draws the same straight pieces as before. +/// share one sample). `span` maps the subpath onto the profile (see [`outline_spans`]); `bend` is +/// the gap (in width factor) the straight line between samples may leave the curve, the outline +/// tolerance turned into the profile's units (see [`adaptive_samples`]). +fn densify(flat: &Flat, segs: &[PathSeg], closed: bool, profile: &WidthProfile, span: (f64, f64), bend: f64) -> (Vec, Vec, Vec) { + // Start at a midpoint per profile segment: the fit through those keeps a gentle taper smooth + // with little path data. A stronger bend measures itself finer (see `adaptive_samples`): the + // straight line between samples must stay within the outline tolerance, as a plain stroke's + // own flattening does, so the profile's shape does not drift from the one a uniform profile + // draws. const SAMPLES: usize = 2; - const MAX_SAMPLES: usize = 8; - // The gap (in width factor) the straight line between two samples may leave: small enough - // that a sharp peak like the lens' needs one more piece, large enough that a long taper's - // gentle bend does not. - const BEND: f64 = 0.05; + const MAX_SAMPLES: usize = 64; let total = length(&flat.pts, closed); let range = span.1 - span.0; if total <= 1e-12 || range <= 1e-12 { @@ -250,6 +241,15 @@ fn densify( // piece the profile's own points are enough; a straight run has only its ends, so it needs // the extra samples. This keeps curved, profiled art close to a uniform stroke's size. let mut marks = Vec::with_capacity(ts.len() * SAMPLES); + // Where each flattened point falls on the profile, so a segment can see the points inside it. + let mut at = Vec::with_capacity(flat.pts.len()); + let mut walked = 0.0; + for (i, p) in flat.pts.iter().enumerate() { + at.push(span.0 + walked / total * range); + if let Some(next) = flat.pts.get(i + 1) { + walked += p.distance(*next); + } + } for w in ts.windows(2) { let (a, b) = (w[0], w[1]); let samples = if constant { @@ -259,12 +259,11 @@ fn densify( // shifted copy has the same shape, so measure its bend on the unshifted segment. let start = a.rem_euclid(1.0); let end = start + (b - a); - let want = adaptive_samples(profile, start, end, SAMPLES, MAX_SAMPLES, BEND).min(cap); - // How many of the flattened path's points already fall in this profile segment. - // `density` is measured on the whole subpath, not on this piece, so outlining only - // the piece near the view picks the same samples as outlining the whole subpath. - let existing = (b - a) * density; - if existing >= want as f64 { 1 } else { want } + let want = adaptive_samples(profile, start, end, SAMPLES, MAX_SAMPLES, bend).min(cap); + // Judge the flattened points inside this profile segment, not the subpath's overall + // density: a long straight run beside a densely flattened curve has few points of its + // own, and only they can tell whether the run already follows the width curve. + if sampled_enough(profile, &at, a, b, bend) { 1 } else { want } }; for k in 0..samples { marks.push(a + (b - a) * k as f64 / samples as f64); @@ -277,22 +276,17 @@ fn densify( split_at(flat, closed, &marks, segs) } -/// How many pieces one profile segment needs so a cubic fit through their ends keeps the width -/// curve. A straight taper is already straight; a visible bend gets progressively more samples. +/// How many pieces one profile segment needs so the outline follows the width curve to within +/// `bend` (a gap in width factor; the caller turns the outline tolerance into it). A straight +/// taper is already straight; a visible bend gets progressively more samples, up to `max`. fn adaptive_samples(profile: &WidthProfile, t0: f64, t1: f64, base: usize, max: usize, bend: f64) -> usize { let mut samples = base.max(1); while samples < max { // One probe in the middle of each piece: how far the curve leaves the straight line // between the piece's ends. The more pieces, the closer the line follows the curve, so // the loop only stops when the pieces it has are fine enough (or at `max`). - let mut dev = 0.0_f64; - for k in 0..samples { - let (a, b) = (k as f64 / samples as f64, (k + 1) as f64 / samples as f64); - let (la, ra) = profile.at(t0 + (t1 - t0) * a); - let (lb, rb) = profile.at(t0 + (t1 - t0) * b); - let (lm, rm) = profile.at(t0 + (t1 - t0) * (a + b) / 2.0); - dev = dev.max((lm - (la + lb) / 2.0).abs()).max((rm - (ra + rb) / 2.0).abs()); - } + let step = (t1 - t0) / samples as f64; + let dev = (0..samples).fold(0.0_f64, |dev, k| dev.max(deviation(profile, t0 + step * k as f64, t0 + step * (k + 1) as f64))); if dev <= bend { break; } @@ -301,6 +295,46 @@ fn adaptive_samples(profile: &WidthProfile, t0: f64, t1: f64, base: usize, max: samples } +/// How far the width curve leaves the straight line between two profile positions: the widest of +/// its two sides at the span's middle. +fn deviation(profile: &WidthProfile, t0: f64, t1: f64) -> f64 { + let (la, ra) = profile.at(t0); + let (lb, rb) = profile.at(t1); + let (lm, rm) = profile.at((t0 + t1) / 2.0); + (lm - (la + lb) / 2.0).abs().max((rm - (ra + rb) / 2.0).abs()) +} + +/// Whether the flattened points inside profile segment `[a, b]` already follow the width curve to +/// within `bend`, so the segment needs no samples of its own. `at` holds each flattened point's +/// profile position. The subpath's overall point density cannot answer this: a long straight run +/// beside a densely flattened curve has few points of its own, and its width must still follow the +/// curve rather than run straight between its ends. +fn sampled_enough(profile: &WidthProfile, at: &[f64], a: f64, b: f64, bend: f64) -> bool { + let first = at.partition_point(|p| *p < a); + let last = at.partition_point(|p| *p <= b); + // A segment whose flattened points only sit on its boundaries is a straight run: one probe in + // the middle cannot see a bend that matches the chord there but leaves it nearer the ends. Let + // `adaptive_samples` measure it. + if !at[first..last].iter().any(|&p| p > a + 1e-9 && p < b - 1e-9) { + return false; + } + // A dash crossing a closed seam has a window past 1 (`[1.0, 1.5]`), where the widths wrap; + // probe the positions `densify` measured its samples at. `at` stays unwrapped for selection. + let shift = a - a.rem_euclid(1.0); + let mut from = a - shift; + for &p in &at[first..last] { + let p = p - shift; + if p <= from { + continue; + } + if deviation(profile, from, p) > bend { + return false; + } + from = p; + } + deviation(profile, from, b - shift) <= bend +} + /// Length of a flattened subpath (see [`flatten`]). pub(super) fn length(pts: &[Point], closed: bool) -> f64 { let n = pts.len(); @@ -419,8 +453,11 @@ impl<'a> Ctx<'a> { } } - fn subpath(&self, out: &mut BezPath, flat: &Flat, segs: &[PathSeg], closed: bool, span: (f64, f64), density: f64) { - let (pts, corner, dirs) = densify(flat, segs, closed, self.profile, span, density); + fn subpath(&self, out: &mut BezPath, flat: &Flat, segs: &[PathSeg], closed: bool, span: (f64, f64)) { + // The flattened edge and its cubic fit are already within `tol`, so a width bend that + // strays further would show as a dent or a bulge that the plain stroke does not have. + let bend = self.tol.max(1e-9) / self.half.max(1e-12); + let (pts, corner, dirs) = densify(flat, segs, closed, self.profile, span, bend); let n = pts.len(); let seg_count = if closed { n } else { n - 1 }; let seg_dir: Vec = (0..seg_count).map(|i| unit(pts[(i + 1) % n] - pts[i])).collect(); @@ -803,11 +840,11 @@ fn smooth_run(out: &mut BezPath, run: &[Point], cyclic: bool, tol: f64) { } else { (run.to_vec(), t0, unit_or(tans[n - 1], run[n - 1] - run[n - 2])) }; - // Fit tighter than the flattening tolerance: the fit's error is the whole outline's error, - // and a least-squares fit may sit on one side of the sampled edge, which would otherwise - // shift a profile's area visibly. The points lie on the outline's own curve, so the fit follows - // their curve between them rather than the chords through them. - let cubics = fit_cubics_through(&pts, t0, t1, tol * 0.1); + // Fit to the flattening tolerance: the samples lie on the outline's own curve, so the fit + // follows that curve between them rather than the chords through them, and the outline is as + // close to the ideal offset as a plain stroke's flattened edge is. A tighter fit added many + // cubics along a strong width wave without a visible gain. + let cubics = fit_cubics_through(&pts, t0, t1, tol); if cubics.is_empty() { out.line_to(run[n - 1]); return; @@ -860,12 +897,15 @@ mod tests { assert!((area(&width_outline(&line(), 10.0, &p, &capped(LineCap::Square), 0.01)) - 1100.0).abs() < 1e-6); } - /// The lens eases up to full width and back down (a parabolic bump averaging two thirds of - /// the width); a one-sided profile keeps its side at zero and stays on the other. + /// The lens eases up to full width and back down (a smooth bump covering seven twelfths of the + /// full width); a one-sided profile keeps its side at zero and stays on the other. #[test] fn lens_profile_is_a_smooth_bump_and_one_sided_profiles_stay_on_their_side() { let a = area(&width_outline(&line(), 10.0, &WidthProfile::lens(), &capped(LineCap::Butt), 0.01)); - assert!((a - 2000.0 / 3.0).abs() < 0.1, "{a}"); + // Within a couple of square points over the bump's 200 pt of edge: the sampled chords and + // the cubic fit each stay within the outline tolerance (0.01) of the curve, so about + // 200 × 0.01 of area either side is expected and invisible. + assert!((a - 1000.0 * 7.0 / 12.0).abs() < 2.0, "{a}"); let one = WidthProfile { points: vec![(0.0, 1.0, 0.0), (1.0, 1.0, 0.0)] }; let o = width_outline(&line(), 10.0, &one, &capped(LineCap::Butt), 0.01); assert!((area(&o) - 500.0).abs() < 1e-6); @@ -1099,10 +1139,74 @@ mod tests { assert!((a - want).abs() / want < 0.01, "{a} vs {want}"); } + /// A long straight run beside a densely flattened curve still follows the profile across the + /// run: the subpath's overall point count must not stand in for the points the run itself has. + #[test] + fn a_long_run_beside_a_dense_curve_keeps_the_profiles_shape() { + // One 200 pt line whose second half is 128 collinear pieces: the same geometry as the + // two-segment line, with most of the flattened points on the second half. The lens peaks + // at the join, so a straight chord across either half would sit at 2.5 pt half way along + // it rather than the 3.125 the profile has there. + let mut dense = BezPath::new(); + dense.move_to((0.0, 0.0)); + for i in 1..=128 { + dense.line_to((100.0 + 100.0 * i as f64 / 128.0, 0.0)); + } + let mut sparse = BezPath::new(); + sparse.move_to((0.0, 0.0)); + sparse.line_to((200.0, 0.0)); + let p = WidthProfile::lens(); + let dense = width_outline(&dense, 10.0, &p, &capped(LineCap::Butt), 0.01); + let sparse = width_outline(&sparse, 10.0, &p, &capped(LineCap::Butt), 0.01); + // The extra collinear points may not change the outline. + let (a, b) = (area(&dense), area(&sparse)); + assert!((a - b).abs() < 2.0, "{a} vs {b}"); + assert!((b - 10.0 * 200.0 * 7.0 / 12.0).abs() < 2.0, "{b}"); + // ... and the edge at a quarter of the way along each half sits at the lens's width. + for x in [50.0, 150.0] { + assert!(dense.contains(Point::new(x, -3.0)), "{x}: {dense:?}"); + assert!(!dense.contains(Point::new(x, -3.4)), "{x}: no extra samples: {dense:?}"); + } + } + + /// A profile segment whose flattened points only sit on its boundaries is a straight run: the + /// sampler measures it, rather than accepting it on a midpoint that happens to match the chord. + #[test] + fn a_bend_that_matches_the_chords_midpoint_still_gets_samples() { + // Flat at 1, then a smooth rise to 2, with collinear vertices exactly on the rise's + // boundaries: through the rising segment the curve matches its chord at the middle and + // sits below it at a quarter of the way, so one midpoint probe would leave the edge + // 0.47 pt out at the quarter. + let mut b = BezPath::new(); + b.move_to((0.0, 0.0)); + b.line_to((25.0, 0.0)); + b.line_to((75.0, 0.0)); + b.line_to((100.0, 0.0)); + let p = WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.25, 1.0, 1.0), (0.75, 2.0, 2.0), (1.0, 2.0, 2.0)] }; + let o = width_outline(&b, 10.0, &p, &capped(LineCap::Butt), 0.01); + // At a quarter of the way through the rise the width is 1.15625, so that edge is 5.78 pt + // from the path; a chord from 1 to 2 would put it at 6.25. + assert!(!o.contains(Point::new(37.5, -6.0)), "{o:?}"); + assert!(o.contains(Point::new(37.5, -5.5)), "{o:?}"); + } + + /// A window past the seam of a closed path probes the widths it actually wraps to: the + /// flattened points of a dash tail sit before the seam. + #[test] + fn a_window_past_the_seam_measures_the_wrapped_widths() { + let profile = WidthProfile::lens(); + // A dash from 0.9 to 1.1 of the subpath, its flattened points ending at 1.1: `[1.0, 1.5]` + // is the wrapped half of the profile's first segment. + let at = [0.9, 0.95, 1.0, 1.05, 1.1]; + assert!(!sampled_enough(&profile, &at, 1.0, 1.5, 0.002), "the wrapped width bends"); + } + #[test] fn profiled_outlines_stay_compact() { // A smooth profile is fitted with cubics, so it must not turn every profile sample into - // exported path data. Compare it with the same curved path's uniform outline. + // exported path data. The wave genuinely bends four times around this small circle, so it + // takes more cubics than the plain annulus; a fit to every sample would take several times + // as many again. let circle = kurbo::Circle::new((0.0, 0.0), 5.0).to_path(0.01); let count = |points| { let p = WidthProfile { points }; @@ -1112,6 +1216,6 @@ mod tests { let lens = count(WidthProfile::lens().points); let wave = count(vec![(0.0, 0.3, 0.3), (0.25, 1.0, 1.0), (0.5, 0.3, 0.3), (0.75, 1.0, 1.0), (1.0, 0.3, 0.3)]); assert!(lens <= uniform * 3 / 2, "lens {lens} vs uniform {uniform}"); - assert!(wave <= uniform * 3 / 2, "wave {wave} vs uniform {uniform}"); + assert!(wave <= uniform * 3, "wave {wave} vs uniform {uniform}"); } } diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index ac993f7ab5..bc2485962d 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -1687,6 +1687,8 @@ fn move_item(s: &mut Session, p: &Value) -> Result { let from = index_param(p, "from", C)?; let contents = p.get("contents").map(|_| index_param(p, "contents", C)).transpose()?; let mut landed = to; + let active = s.active_appearance_item.as_ref().and_then(|a| a.objects.first().copied()); + let mut active_landed = None; // When every object's stack comes out as it was, the document and its undo history stay as they // are. let before = s.doc()?.doc.clone(); @@ -1694,6 +1696,9 @@ fn move_item(s: &mut Session, p: &Value) -> Result { for id in &ids { let Some(n) = d.node_mut(*id) else { continue }; landed = n.appearance.move_item(from, to).ok_or_else(|| bad(C, format!("no item at index {from}")))?; + if active == Some(*id) { + active_landed = Some(landed); + } if let Some(k) = contents.filter(|_| n.contents_label().is_some()) { n.appearance.set_contents_at(k); } @@ -1703,13 +1708,14 @@ fn move_item(s: &mut Session, p: &Value) -> Result { let labels = super::graph::capture_label_changes(&before, d, &ids, true, None); Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels)) })?; - // The moved row stays the active one; the rows it passed shift by one. + // Track the row in its own object's stack, since other stacks may clamp to a different index. + let at = active_landed.unwrap_or(landed); s.remap_appearance_item(&ids, |a| { Some(if a == from { - landed - } else if from < a && a <= landed { + at + } else if from < a && a <= at { a - 1 - } else if landed <= a && a < from { + } else if at <= a && a < from { a + 1 } else { a diff --git a/crates/engine/src/cmd/dimension.rs b/crates/engine/src/cmd/dimension.rs index 9caec2ae92..4059621e4e 100644 --- a/crates/engine/src/cmd/dimension.rs +++ b/crates/engine/src/cmd/dimension.rs @@ -88,11 +88,13 @@ fn recipe(s: &Session, p: &Value) -> Result { } let a = if source.is_none() || p.get("a").is_some() { point(p, "a")? } else { Point::ZERO }; let b = if source.is_none() || p.get("b").is_some() { point(p, "b")? } else { Point::new(1.0, 0.0) }; - let vertex = if mode == DimensionMode::Angular && (source.is_none() || matches!(source, Some(DimensionSource::Points { .. }))) { - point(p, "vertex")? - } else { - Point::ZERO + // Resolution supplies a linked vertex. An explicit coordinate is still checked when given. + let read_vertex = match &source { + None => true, + Some(DimensionSource::Points { vertex, .. }) => vertex.is_none() || p.get("vertex").is_some(), + _ => false, }; + let vertex = if mode == DimensionMode::Angular && read_vertex { point(p, "vertex")? } else { Point::ZERO }; let orientation = orientation(p, mode)?.unwrap_or_default(); let mut d = Dimension { mode, diff --git a/crates/engine/src/cmd/docsetup.rs b/crates/engine/src/cmd/docsetup.rs index 8aacbb1eb0..a6281a2a7a 100644 --- a/crates/engine/src/cmd/docsetup.rs +++ b/crates/engine/src/cmd/docsetup.rs @@ -131,8 +131,10 @@ fn apply(s: &mut DocSetup, units: &mut vectorcraft_doc::Unit, k: &str, v: &Value let (name, _, quotes) = LANGUAGES.iter().find(|(n, _, _)| n.eq_ignore_ascii_case(l)).ok_or_else(|| { bad(C, format!("unknown language `{l}` (one of {})", LANGUAGES.iter().map(|(n, _, _)| *n).collect::>().join(", "))) })?; + if !s.language.eq_ignore_ascii_case(name) { + s.quotes = *quotes; + } s.language = name.to_string(); - s.quotes = *quotes; } "quotes" => s.quotes = quotes_param(v, s.quotes)?, "typographersQuotes" => s.typographers_quotes = flag(k, v)?, @@ -311,3 +313,19 @@ fn restamp_scripts(d: &mut Document) { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn setup_round_trip_preserves_custom_quotes() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute(C, &json!({"quotes": {"double": "«»", "single": "‹›"}})).unwrap(); + let mut fields = s.execute(C, &json!({})).unwrap(); + fields["bleed"] = json!(4); + let reply = s.execute(C, &fields).unwrap(); + assert_eq!(reply["quotes"], fields["quotes"]); + } +} diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index bce1e24d98..9a2ee80033 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -12,7 +12,7 @@ pub fn specs() -> Vec { "Pencil", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation,wheel]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation. An airbrush pen's finger wheel 0..1: the stroke keeps it for brushes with Stylus Wheel variation, a point without one half way; null for what a point lacks. A pressure, tilt, rotation or wheel outside its range, or a point array of more than seven numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"} (only with extend), redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it. Any other style, extend end or connect end, connect without extend, and a connect that names no other path with an open end are errors, a stroke of one point included, and nothing changes", + "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation,wheel]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation. An airbrush pen's finger wheel 0..1: the stroke keeps it for brushes with Stylus Wheel variation, a point without one half way; null for what a point lacks. A pressure, tilt, rotation or wheel outside its range, or a point array of more than seven numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), leaveSelection?: bool (false; true with keepSelected false: a new path leaves the selection as it is, as the Pencil previews a stroke that redraws a path), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"} (only with extend), redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the way round a closed one that leaves the bigger shape; on an open one the way the stroke runs along it at each end decides: it replaces the part it runs along where it starts and joins the part it runs into where it lands, so it replaces the part between, keeps it and closes the path along the stroke, or, when its ends disagree, ends where it is lifted; an end that leaves or meets the path squarely follows the other end, and when both do it closes only if it goes round both pieces beyond), the stroke's ends bent smoothly onto the path; a stroke that starts on it and returns to the same point adds a loop there, and one lifted farther than `within` from it takes the path with it: a closed subpath opens where the stroke starts, an open one is cut there and drops the part the stroke heads along, and the path ends where the stroke does. Any other style, extend end or connect end, connect without extend, and a connect that names no other path with an open end are errors, a stroke of one point included, and nothing changes", has_doc, freehand ), diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index 607abf8f03..5f281e2e34 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -74,13 +74,329 @@ fn stroke_subpath(pts: &[Point], tol: Option, closed: bool) -> SubPath { } } -/// Pencil's Edit Selected Paths in the middle of a path: a stroke from one point of a subpath of -/// `pd` to another, each within `within` of it, replaces the section between them (the shorter -/// way round a closed subpath) with the stroke fitted at `tol` (with no `tol`, unfitted). The -/// subpath's index and its new shape; None when the stroke doesn't start and end on the same -/// subpath, or meets it once. +/// The anchor of `sp` at the point of it nearest to `q`: the one there, else a new one, and +/// whether it was added. +fn anchor_at(sp: &mut SubPath, q: Point) -> Option<(usize, bool)> { + let (_, seg, t, _, _) = PathData::single(sp.clone()).nearest(q)?; + let n = sp.anchors.len(); + if n == 0 { + return None; + } + Some(if t <= 1e-6 { + (seg % n, false) + } else if t >= 1.0 - 1e-6 { + ((seg + 1) % n, false) + } else { + (sp.insert_anchor(seg, t), true) + }) +} + +/// The direction `sp` leaves anchor `k` going forward (towards the next anchor). +fn forward_at(sp: &SubPath, k: usize) -> Option { + let a = sp.anchors.get(k)?; + let n = sp.anchors.len(); + let next = if sp.closed || k + 1 < n { sp.anchors.get((k + 1) % n) } else { None }; + let toward = if a.h_out != a.p { + a.h_out + } else if let Some(b) = next { + if b.h_in != b.p { b.h_in } else { b.p } + } else { + // The last anchor of an open subpath: forward goes on the way it arrived. + let prev = sp.anchors.get(k.checked_sub(1)?)?; + return Some(a.p - if a.h_in != a.p { a.h_in } else { prev.p }); + }; + let v = toward - a.p; + (v.hypot() > 1e-9).then_some(v) +} + +/// The direction stroke `pts` leaves its first point: towards its first point farther than +/// `reach` from it, or its last point. +fn heading(pts: &[Point], reach: f64) -> Option { + let (&p0, rest) = pts.split_first()?; + let to = rest.iter().find(|q| q.distance(p0) > reach).or(rest.last())?; + let v = *to - p0; + (v.hypot() > 1e-9).then_some(v) +} + +/// `stroke` (its first point moved onto anchor `a` of the path it leaves) fitted at `tol`: its +/// anchors, the first of which is at `a`. +fn fit_from(a: Point, pts: &[Point], tol: Option, reach: f64) -> Vec { + let mut stroke = pts.to_vec(); + bend_ends(&mut stroke, Some(a), None, reach); + stroke_subpath(&stroke, tol, false).anchors.into_vec() +} + +/// Bend the ends of `stroke` onto `a` (its start) and `b` (its end): each end moves all the way +/// and the stroke behind it less and less, to not at all `reach` along it (Edit selected paths +/// within), so a stroke that starts or ends near the path joins it smoothly instead of with a +/// straight piece. A stroke shorter than `reach` bends over its own length, so each end still +/// lands on its target and the other end's bend doesn't move it off. +fn bend_ends(stroke: &mut [Point], a: Option, b: Option, reach: f64) { + let (Some(&first), Some(&last)) = (stroke.first(), stroke.last()) else { return }; + // How far along the stroke each point lies, measured before anything moves. + let mut along = Vec::with_capacity(stroke.len()); + let mut total = 0.0; + let mut prev = first; + for p in stroke.iter() { + total += prev.distance(*p); + prev = *p; + along.push(total); + } + let reach = reach.min(total); + if !reach.is_finite() || reach <= 0.0 { + // No length to bend over: only the ends move. + if let (Some(a), Some(p)) = (a, stroke.first_mut()) { + *p = a; + } + if let (Some(b), Some(p)) = (b, stroke.last_mut()) { + *p = b; + } + return; + } + let weight = |d: f64| (1.0 - d / reach).max(0.0); + let (shift_a, shift_b) = (a.map(|a| a - first), b.map(|b| b - last)); + for (p, &d) in stroke.iter_mut().zip(&along) { + if let Some(s) = shift_a { + *p += s * weight(d); + } + if let Some(s) = shift_b { + *p += s * weight(total - d); + } + } +} + +/// Pencil's Edit Selected Paths for a stroke that starts on a subpath of `pd` (within `within` of +/// it) and ends away from it (#2850 follow-up): the path follows the stroke and ends where the +/// stroke does. A closed subpath opens where the stroke starts and keeps its whole outline, run +/// so that it arrives there heading the stroke's way. An open subpath is cut there and keeps the +/// part behind the stroke: the part the stroke heads along is dropped. The subpath's index and its +/// new shape; None when the stroke doesn't start on `pd`. `runs_up`, when given, says which part of +/// an open subpath the stroke heads along: the part towards its last anchor when true. +fn redraw_extend(pd: &PathData, pts: &[Point], tol: Option, within: f64, runs_up: Option) -> Option<(usize, SubPath)> { + let first = *pts.first()?; + let (si, _, _, _, d) = pd.nearest(first)?; + if d > within || pts.len() < 2 { + return None; + } + let mut sp = pd.subpaths.get(si)?.clone(); + if sp.anchors.len() < 2 { + return None; + } + let (mut k, _) = anchor_at(&mut sp, first)?; + let last = sp.anchors.len() - 1; + // Run the subpath so the stroke goes on from `k` forward; the result runs the subpath's own way + // again below, so a shape's holes stay holes under the non-zero fill rule. A closed subpath + // arrives at `k` heading the stroke's way. An open one drops the part the stroke heads along; + // one it leaves nearly square to it (more than 70° from its direction) drops its shorter + // part, never most of the path. From one of its ends it drops nothing. + let dir = heading(pts, within.max(tol.unwrap_or(0.0) * 2.0))?; + let cos = forward_at(&sp, k).map_or(0.0, |f| f.dot(dir) / (f.hypot() * dir.hypot()).max(1e-12)); + let flipped = if sp.closed { + cos < 0.0 + } else if k == 0 || k == last { + k == 0 + } else if let Some(up) = runs_up { + !up + } else if cos.abs() >= 0.34 { + cos < 0.0 + } else { + let len = |i: usize, j: usize| (i..j).map(|s| kurbo::ParamCurveArclen::arclen(&sp.segment(s), 0.01)).sum::(); + len(0, k) < len(k, last) + }; + if flipped { + sp.reverse(); + k = sp.anchors.len().checked_sub(1 + k)?; + } + let at = *sp.anchors.get(k)?; + let mut anchors: Vec = if sp.closed { + // From `k` all the way round back to `k`: the shape opens there. + let mut v: Vec = sp.anchors.get_range(k..)?.into_iter().chain(sp.anchors.get_range(..k)?).collect(); + if let Some(a0) = v.first_mut() { + *a0 = Anchor::with_handles(a0.p, a0.p, a0.h_out); + } + v.push(at); + v + } else { + sp.anchors.get_range(..=k)? + }; + let fit = fit_from(at.p, pts, tol, within); + let (f0, rest) = fit.split_first()?; + if let Some(a) = anchors.last_mut() { + *a = Anchor::with_handles(a.p, a.h_in, f0.h_out); + } + anchors.extend_from_slice(rest); + let mut out = SubPath::new(anchors, false); + if flipped { + out.reverse(); + } + Some((si, out)) +} + +/// A stroke that leaves anchor `k` of `sp` and comes back to it: the stroke is inserted there as a +/// loop out of the path (#2850 follow-up). +fn redraw_loop(mut sp: SubPath, k: usize, pts: &[Point], tol: Option, within: f64) -> Option { + let at = *sp.anchors.get(k)?; + let mut stroke = pts.to_vec(); + bend_ends(&mut stroke, Some(at.p), Some(at.p), within); + let fit = stroke_subpath(&stroke, tol, false).anchors.into_vec(); + let (Some(f0), Some(fl)) = (fit.first().copied(), fit.last().copied()) else { return None }; + if fit.len() < 3 { + return None; + } + let inner = fit.get(1..fit.len() - 1)?; + let mut anchors = sp.anchors.get_range(..k)?; + anchors.push(Anchor::with_handles(at.p, at.h_in, f0.h_out)); + anchors.extend_from_slice(inner); + anchors.push(Anchor::with_handles(at.p, fl.h_in, at.h_out)); + anchors.extend_from_slice(&sp.anchors.get_range(k + 1..)?); + sp.anchors = anchors.into(); + Some(sp) +} + +/// The area closed subpath `sp` would have with `stroke` (running from anchor `start` to anchor +/// `end`) in place of its run from `start` forward to `end`. +fn redrawn_area(sp: &SubPath, start: usize, end: usize, stroke: impl Iterator) -> f64 { + use kurbo::ParamCurveArea; + let n = sp.anchors.len(); + let (Some(from), Some(to)) = (sp.anchors.get(start), sp.anchors.get(end)) else { return 0.0 }; + let mut area: f64 = (0..(start + n - end) % n).map(|k| sp.segment((end + k) % n).signed_area()).sum(); + let mut at = from.p; + for q in stroke.chain([to.p]) { + area += kurbo::Line::new(at, q).signed_area(); + at = q; + } + area.abs() +} + +/// Which way a stroke runs along open subpath `sp` where it meets it: `stroke` starts at that end +/// of the stroke. It runs along when its first `within` of length stays within `within` of the +/// path and moves along the path more than away from it: Some(true) towards the subpath's last +/// anchor. None when it goes straight off (or onto) the path. +fn run_along(sp: &SubPath, mut stroke: impl Iterator, within: f64) -> Option { + let one = PathData::single(sp.clone()); + let p0 = stroke.next()?; + // The point `within` along the stroke, or its other end when it is shorter. + let (mut prev, mut len, mut q) = (p0, 0.0, p0); + for p in stroke { + let step = prev.distance(p); + if len + step >= within && step > 0.0 { + q = prev.lerp(p, (within - len) / step); + break; + } + len += step; + prev = p; + q = p; + } + let (_, s0, t0, on0, _) = one.nearest(p0)?; + let (_, s1, t1, on1, away) = one.nearest(q)?; + if away > within || on0.distance(on1) <= away { + return None; + } + Some(s1 as f64 + t1 > s0 as f64 + t0) +} + +/// What a stroke from anchor `from` to anchor `to` of open subpath `sp` does to it. +enum OpenRedraw { + /// Replaces the part between and leaves the path open. + Replace, + /// Keeps the part between, drops the pieces beyond and closes the path with the stroke. + Close, + /// Drops the part it starts along (towards the last anchor when true) and ends where it does. + Extend(bool), +} + +/// Pencil's Edit Selected Paths on an open subpath: what a stroke from anchor `from` to anchor `to` +/// of `sp` does, from the way it runs along the path at each end ([`run_along`]; `before` is the +/// subpath before the anchors at `from` and `to` were added). Where it starts, it replaces the part +/// it runs along; where it lands, it joins the part it runs into and the part behind goes. An end +/// that goes straight off or onto the path follows the other end. When both do, it closes only if +/// the shape it makes with the part between goes round both pieces beyond ([`goes_round`]). When +/// the two ends disagree, the start decides and the stroke's end stays where it is lifted. +fn open_redraw(before: &SubPath, sp: &SubPath, from: usize, to: usize, pts: &[Point], within: f64) -> OpenRedraw { + let up = to > from; + // Each end runs towards the last anchor (true) or the first. Running towards the other end + // of the stroke at the start, or on away from it where it lands, replaces the part between; + // the other way keeps the part between and closes the path. + let at_start = run_along(before, pts.iter().copied(), within); + let at_end = run_along(before, pts.iter().rev().copied(), within).map(|back| !back); + match (at_start, at_end) { + (Some(s), Some(e)) if s != e => OpenRedraw::Extend(s), + (Some(r), _) | (None, Some(r)) => { + if r == up { + OpenRedraw::Replace + } else { + OpenRedraw::Close + } + } + (None, None) => { + if goes_round(sp, from, to, pts) { + OpenRedraw::Close + } else { + OpenRedraw::Replace + } + } + } +} + +/// Does the shape that stroke `pts` (from anchor `from` to anchor `to` of open subpath `sp`) makes +/// with the part of `sp` between them go round both pieces of `sp` beyond them? A piece counts as +/// inside when more of it lies inside than outside; a piece of no length counts as inside. +fn goes_round(sp: &SubPath, from: usize, to: usize, pts: &[Point]) -> bool { + use kurbo::{ParamCurve, Shape}; + let (lo, hi) = (from.min(to), from.max(to)); + let Some(middle) = sp.anchors.get_range(lo..=hi) else { return false }; + let mut shape = PathData::single(SubPath::new(middle, false)).to_bezpath(); + // The stroke runs from `hi` back to `lo` to close the shape. + let back: Vec = if from == lo { pts.iter().rev().copied().collect() } else { pts.to_vec() }; + for p in back { + shape.line_to(p); + } + shape.close_path(); + let inside = |segs: std::ops::Range| { + let (mut yes, mut no) = (0, 0); + for k in segs { + let seg = sp.segment(k); + for t in [0.25, 0.5, 0.75] { + if shape.winding(seg.eval(t)) != 0 { yes += 1 } else { no += 1 } + } + } + yes >= no + }; + inside(0..lo) && inside(hi..sp.anchors.len().saturating_sub(1)) +} + +/// Closes open subpath `sp` with stroke `pts`, which runs from anchor `from` to anchor `to`: the +/// anchors between them stay, the pieces beyond go, and the stroke, its ends bent onto those +/// anchors ([`bend_ends`] over `within`), runs from one back to the other. +fn redraw_across_gap(sp: &SubPath, from: usize, to: usize, pts: &[Point], tol: Option, within: f64) -> Option { + let (lo, hi) = (from.min(to), from.max(to)); + let (a_lo, a_hi) = (*sp.anchors.get(lo)?, *sp.anchors.get(hi)?); + let mut stroke = pts.to_vec(); + if from == lo { + stroke.reverse(); + } + bend_ends(&mut stroke, Some(a_hi.p), Some(a_lo.p), within); + let fit = stroke_subpath(&stroke, tol, false).anchors.into_vec(); + let (Some(f0), Some(fl)) = (fit.first().copied(), fit.last().copied()) else { return None }; + let mut anchors = sp.anchors.get_range(lo..=hi)?; + if let Some(a) = anchors.first_mut() { + *a = Anchor::with_handles(a.p, fl.h_in, a.h_out); + } + if let Some(a) = anchors.last_mut() { + *a = Anchor::with_handles(a.p, a.h_in, f0.h_out); + } + anchors.extend_from_slice(fit.get(1..fit.len().saturating_sub(1)).unwrap_or_default()); + Some(SubPath::new(anchors, true)) +} + +/// Pencil's Edit Selected Paths in the middle of a path: a stroke that starts and ends within +/// `within` of a subpath of `pd` replaces the section between with the stroke fitted at `tol` (with +/// no `tol`, unfitted), its ends bent onto the path ([`bend_ends`]). On a closed subpath that is the +/// way round that leaves the bigger shape. On an open one the way the stroke runs along the path +/// at its ends decides ([`open_redraw`]): it replaces the part between, keeps the part between and +/// closes the path, or ends where it is lifted. The subpath's index and its new shape; None when +/// the stroke doesn't start and end on the same subpath. fn redraw_section(pd: &PathData, pts: &[Point], tol: Option, within: f64) -> Option<(usize, SubPath)> { - use kurbo::ParamCurveArclen; let (first, last) = (*pts.first()?, *pts.last()?); let (si, _, _, _, d_a) = pd.nearest(first)?; let (sj, _, _, _, d_b) = pd.nearest(last)?; @@ -91,35 +407,35 @@ fn redraw_section(pd: &PathData, pts: &[Point], tol: Option, within: f64) - if sp.anchors.len() < 2 { return None; } - // The anchor nearest to `q`: the one there, else a new one, and whether it was added. Each - // point is looked up on the subpath as it is by then: splitting a straight segment makes two - // new ones, which a `t` along the old one doesn't measure. - let place = |sp: &mut SubPath, q: Point| { - let (_, seg, t, _, _) = PathData::single(sp.clone()).nearest(q)?; - let n = sp.anchors.len(); - Some(if t <= 1e-6 { - (seg % n, false) - } else if t >= 1.0 - 1e-6 { - ((seg + 1) % n, false) - } else { - (sp.insert_anchor(seg, t), true) - }) - }; - let (mut from, _) = place(&mut sp, first)?; - let (to, added) = place(&mut sp, last)?; + let before = sp.clone(); + // Each point is looked up on the subpath as it is by then: splitting a straight segment makes + // two new ones, which a `t` along the old one doesn't measure. + let (mut from, _) = anchor_at(&mut sp, first)?; + let (to, added) = anchor_at(&mut sp, last)?; if added && to <= from { from += 1; } if from == to { - return None; + // The stroke starts and ends on the same point: it is a loop out of the path there. + return redraw_loop(sp, from, pts, tol, within).map(|sp| (si, sp)); + } + if !sp.closed { + match open_redraw(&before, &sp, from, to, pts, within) { + OpenRedraw::Replace => {} + OpenRedraw::Close => return redraw_across_gap(&sp, from, to, pts, tol, within).map(|sp| (si, sp)), + OpenRedraw::Extend(up) => return redraw_extend(pd, pts, tol, within, Some(up)), + } } let n = sp.anchors.len(); - // The length of the run of segments from anchor i forward to anchor j. - let run = |i: usize, j: usize| (0..(j + n - i) % n).map(|k| sp.segment((i + k) % n).arclen(0.01)).sum::(); // The stroke goes from `start` to `end` and replaces the run between them; `kept` runs from // `end` round to `start`, then the stroke's inner anchors follow. let (start, end, reversed) = if sp.closed { - if run(from, to) <= run(to, from) { (from, to, false) } else { (to, from, true) } + // The bigger of the two shapes the stroke could make stays: carving across a shape replaces + // the part it cuts off, drawing round outside it the part it goes round. Picking the side + // nearer the stroke instead threw away a thin shape under a tall arch over its long side. + let forward = redrawn_area(&sp, from, to, pts.iter().copied()); + let backward = redrawn_area(&sp, to, from, pts.iter().rev().copied()); + if forward >= backward { (from, to, false) } else { (to, from, true) } } else if from < to { (from, to, false) } else { @@ -129,10 +445,8 @@ fn redraw_section(pd: &PathData, pts: &[Point], tol: Option, within: f64) - if reversed { stroke.reverse(); } - let (Some(s0), Some(s1)) = (stroke.first_mut(), sp.anchors.get(start)) else { return None }; - *s0 = s1.p; - let (Some(e0), Some(e1)) = (stroke.last_mut(), sp.anchors.get(end)) else { return None }; - *e0 = e1.p; + let (Some(s1), Some(e1)) = (sp.anchors.get(start), sp.anchors.get(end)) else { return None }; + bend_ends(&mut stroke, Some(s1.p), Some(e1.p), within); let fit = stroke_subpath(&stroke, tol, false).anchors.into_vec(); let (Some(f0), Some(f1)) = (fit.first().copied(), fit.last().copied()) else { return None }; let inner = fit.get(1..fit.len().saturating_sub(1)).unwrap_or_default(); @@ -212,6 +526,9 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s // The undo step's name: a stroke painted with a brush is a Paintbrush stroke, whatever its style. let label = if brush || brush_name.is_some() { "Paintbrush" } else { "Pencil" }; let keep_selected = switch_or(p, "keepSelected", true, C)?; + // The Pencil's preview of a stroke that redraws a path draws it as a new path but leaves the + // selection as it is: the path being redrawn stays selected until the release redraws it. + let leave_selection = switch_or(p, "leaveSelection", false, C)?; let filled = switch_or(p, "fill", false, C)?; let extend = p.get("extend").filter(|v| !v.is_null()); if extend.is_none() && p.get("connect").is_some_and(|v| !v.is_null()) { @@ -416,7 +733,9 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s // shortcut: a stroke's pressure, tilt, bearing and rotation profiles are left as they // were, measured along the old path; fit them to the new length if strokes drawn with a // pen get redrawn. - if let Some((si, sp)) = redraw_section(&pd, &pts, fit_tol, within) { + // A stroke that ends back on the path redraws the section between; one that ends away from + // it takes the path with it (it is where the pen is lifted that decides). + if let Some((si, sp)) = redraw_section(&pd, &pts, fit_tol, within).or_else(|| redraw_extend(&pd, &pts, fit_tol, within, None)) { // A member path of a compound path is redrawn in it: the compound path is what is // selected, and what a brush paints. let whole = brush_target(&s.doc()?.doc, id); @@ -461,7 +780,7 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s } } let out = insert_look(s, label, path_kind(PathData::single(sp)), look, None, keep_selected)?; - if !keep_selected { + if !keep_selected && !leave_selection { // A new stroke with Keep selected off leaves nothing selected: Illustrator starts the stroke // by dropping the earlier selection, it does not keep it (#5752). s.select(|_, sel| sel.clear())?; @@ -628,3 +947,32 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result { })?; Ok(json!({ "id": keep.0 })) } + +#[cfg(test)] +mod bend_tests { + use super::*; + + /// The ends move onto their targets, the stroke behind them less and less, and nothing farther + /// along than `reach`. + #[test] + fn bend_ends_moves_the_ends_and_fades_out_along_the_reach() { + let mut pts: Vec = (0..=10).map(|i| Point::new(f64::from(i) * 10.0, 0.0)).collect(); + bend_ends(&mut pts, Some(Point::new(0.0, 8.0)), Some(Point::new(100.0, -8.0)), 40.0); + assert_eq!(pts[0], Point::new(0.0, 8.0)); + assert_eq!(pts[10], Point::new(100.0, -8.0)); + assert!((pts[2].y - 8.0 * 0.5).abs() < 1e-9, "halfway along the reach, half the shift: {:?}", pts[2]); + assert!((pts[8].y + 8.0 * 0.5).abs() < 1e-9, "{:?}", pts[8]); + assert_eq!(pts[5], Point::new(50.0, 0.0), "the middle doesn't move"); + } + + /// A stroke shorter than `reach` still has both ends on their targets: bending one end onto + /// its target doesn't pull the other end off its own. + #[test] + fn bend_ends_keeps_both_ends_on_target_for_a_short_stroke() { + let mut pts = vec![Point::new(40.0, -12.0), Point::new(44.0, -12.0), Point::new(48.0, -12.0)]; + bend_ends(&mut pts, Some(Point::new(40.0, 0.0)), Some(Point::new(48.0, 0.0)), 16.0); + assert_eq!(pts[0], Point::new(40.0, 0.0), "{pts:?}"); + assert_eq!(pts[2], Point::new(48.0, 0.0), "{pts:?}"); + assert_eq!(pts[1], Point::new(44.0, 0.0), "halfway, half of each end's shift: {pts:?}"); + } +} diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index b07950d52a..80277d64b8 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -695,6 +695,7 @@ fn undo_group_end(s: &mut Session, p: &Value) -> Result { /// goes to the running command's result or the tool's status messages, as the tool's own commit /// reports it ([`Session::note_settled_warning`]). pub(crate) fn settle_interaction(s: &mut Session) -> Result<()> { + s.put_back_interaction(); let typing = typing_in_progress(s); match s.unapplied_interaction_preview().filter(|_| !s.previewing) { Some((cmd, p)) => match s.preview(&cmd, &p) { @@ -894,8 +895,10 @@ fn clear_history(s: &mut Session, _: &Value) -> Result { fn new_document_from_state(s: &mut Session, p: &Value) -> Result { const C: &str = "edit.newDocumentFromState"; let created = date_param(p, "created", C)?; + // The row as the panel lists it now, with a drag in progress on show: keeping it below + // changes the rows. + s.put_back_interaction(); let st = s.doc()?; - // The row as the panel lists it now: keeping an edit in progress below changes the rows. let chosen = match super::index_opt(p, "index", C)? { None => None, Some(row) => { diff --git a/crates/engine/src/cmd/fileio/pdfimport.rs b/crates/engine/src/cmd/fileio/pdfimport.rs index 11f7c0b3d1..8ffb3f8133 100644 --- a/crates/engine/src/cmd/fileio/pdfimport.rs +++ b/crates/engine/src/cmd/fileio/pdfimport.rs @@ -159,7 +159,8 @@ impl LoadOptions { trust_editing_data, embedded_fonts, legacy_names, - native: true, + // The command's opt-out also skips the embedded VectorCraft document. + native: editing_data, link_pages, }) } diff --git a/crates/engine/src/cmd/fileio/tests_pdfedit.rs b/crates/engine/src/cmd/fileio/tests_pdfedit.rs index c38dfc390d..75761364ee 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfedit.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfedit.rs @@ -53,6 +53,27 @@ fn a_pdf_saved_with_preserve_editing_reopens_as_the_same_document() { assert!(vectorcraft_pdf::editing(&b64(&v)).is_some_and(|e| e.intact)); } +#[test] +fn opening_a_preserve_editing_pdf_without_editing_data_imports_its_pages() { + let mut s = rich(); + assert!(!s.doc().unwrap().doc.symbols.is_empty()); + let exported = s.execute("document.exportPdf", &json!({"preserveEditing": true})).unwrap(); + let reopened = s + .execute( + "document.open", + &json!({ + "name": "rich.pdf", + "dataBase64": exported["dataBase64"], + "cropTo": "media", + "editingData": false, + }), + ) + .unwrap(); + + assert_eq!(reopened["restored"], false, "{reopened}"); + assert!(s.doc().unwrap().doc.symbols.is_empty(), "the PDF page has no native symbol definitions"); +} + #[test] fn pages_changed_elsewhere_open_as_artwork_with_a_warning() { let mut s = rich(); diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 9082850dff..8ce478ad97 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -79,7 +79,7 @@ pub fn specs() -> Vec { "Nudge", [], None, - "{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)} arrow-key nudge by the keyboard increment (the selected anchors, else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)", + "{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)} arrow-key nudge by the keyboard increment (the selected anchors (a selected curved segment bends instead: its anchors stay and its handles keep their directions while its middle moves by the step), else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)", has_selection_or_guides, nudge ), diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index 536dcf9c98..1ccd74d57f 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -347,7 +347,10 @@ pub(super) fn nudge(s: &mut Session, p: &Value) -> Result { if dx == 0.0 && dy == 0.0 { return ok(); } - return crate::cmd::path::move_anchors(s, &json!({ "dx": dx, "dy": dy, "patterns": p.get("patterns"), "interpolate": p.get("interpolate") })); + return crate::cmd::path::nudge_anchors( + s, + &json!({ "dx": dx, "dy": dy, "patterns": p.get("patterns"), "interpolate": p.get("interpolate") }), + ); } if objects && s.doc()?.selection.is_empty() { let copy = bool_or(p, "copy", false); diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index feb1c0ad10..b7df3dc467 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -4,7 +4,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use serde_json::{Value, json}; -use vectorcraft_doc::{AnchorRef, Document, Node, NodeId, NodeKind, Scaling, Selection}; +use vectorcraft_doc::{AnchorRef, Document, Node, NodeId, NodeKind, Scaling, SegmentRef, Selection}; use vectorcraft_geom::{Anchor, AnchorKind, Anchors, PathData, Point, SubPath, Vec2}; use super::create::anchor_from_json; @@ -140,7 +140,7 @@ pub fn specs() -> Vec { "Add Anchor Point", [], None, - "{id, subpath?, segment, t: 0..1} add an anchor at t on the segment → {anchor}; the direct-selected anchors and selected segments keep the same points (a selected segment it splits stays selected as its two halves), and a path that isn't selected becomes the selection with the new anchor direct-selected", + "{id, subpath?, segment, t: 0..1, selectAnchor?: bool (the path becomes the selection with only the new anchor direct-selected, also when it is selected)} add an anchor at t on the segment → {anchor}; the direct-selected anchors and selected segments keep the same points (a selected segment it splits stays selected as its two halves), and a path that isn't selected becomes the selection with the new anchor direct-selected", has_doc, insert_anchor ), @@ -244,19 +244,48 @@ fn close(s: &mut Session, p: &Value) -> Result { } pub(crate) fn move_anchors(s: &mut Session, p: &Value) -> Result { - let d = Vec2::new(number_or(p, "dx", 0.0, "path.moveAnchors")?, number_or(p, "dy", 0.0, "path.moveAnchors")?); - check_switches(p, &["patterns", "interpolate"], "path.moveAnchors")?; + move_selected(s, p, false) +} + +/// The arrow keys with direct-selected anchors or segments: as `path.moveAnchors`, except that a +/// selected curved segment bends ([`SubPath::nudge_segment`]). +pub(crate) fn nudge_anchors(s: &mut Session, p: &Value) -> Result { + move_selected(s, p, true) +} + +/// Move the selection by `(dx, dy)`: its direct-selected anchors with their handles, and the +/// objects selected whole. With `bend`, each selected curved segment bends instead and its anchors +/// stay, except an anchor that also ends a selected straight segment, which moves with it. +fn move_selected(s: &mut Session, p: &Value, bend: bool) -> Result { + const C: &str = "path.moveAnchors"; + let d = Vec2::new(number_or(p, "dx", 0.0, C)?, number_or(p, "dy", 0.0, C)?); + check_switches(p, &["patterns", "interpolate"], C)?; // An object selected in a symbol instance's art stays where the symbol puts it. super::edit::refuse_symbol_part(s)?; + let st = s.doc()?; + let mut sel = st.selection.clone(); + let (held, bends) = if bend { held_segments(&st.doc, &mut sel, d) } else { (false, vec![]) }; + // Segments that hold their anchors and don't bend, with nothing else to move, change nothing. + if held && bends.is_empty() && sel.whole().is_empty() && sel.guides.is_empty() && sel.anchors.values().all(BTreeSet::is_empty) { + return ok(); + } // Objects selected whole move as objects, and their pattern tiles move with them when // `patterns` (default: General › Transform Pattern Tiles) is on. - let whole = s.doc()?.selection.whole(); - let sc = Scaling { patterns: super::object::transform_patterns(s, p, &whole)?, ..Scaling::default() }; - let interpolate = interpolates_handles(s, p, "path.moveAnchors")?; - transform_anchors(s, "Move", vectorcraft_geom::Affine::translate(d), sc, interpolate)?; - // Transform Again repeats a move that moved something; a drag records it when it commits. + let sc = Scaling { patterns: super::object::transform_patterns(s, p, &sel.whole())?, ..Scaling::default() }; + let interpolate = interpolates_handles(s, p, C)?; + s.edit(if bends.is_empty() { "Move" } else { "Reshape" }, |doc, _| { + transform_selected(doc, &sel, vectorcraft_geom::Affine::translate(d), sc, interpolate)?; + for &(id, si, seg) in &bends { + if let Some(sp) = path_mut(doc, id)?.subpaths.get_mut(si) { + sp.nudge_segment(seg, d); + } + } + Ok(()) + })?; + // Transform Again repeats a move that moved something; a drag records it when it commits. A + // move that held segments' anchors is not one move of the selection. let st = s.doc_mut()?; - if st.interaction.is_none() && (d.x != 0.0 || d.y != 0.0) { + if !held && st.interaction.is_none() && (d.x != 0.0 || d.y != 0.0) { let options = json!({ "copy": false, "patterns": sc.patterns, "interpolate": interpolate }); st.last_transform = Some(crate::LastTransform::Matrix(vectorcraft_geom::Affine::translate(d), options)); st.last_perspective = None; @@ -264,6 +293,29 @@ pub(crate) fn move_anchors(s: &mut Session, p: &Value) -> Result { ok() } +/// Take the anchors of `sel`'s selected curved segments out of its `anchors`, except those that +/// also end a selected straight segment, and list the segments that a bend by `d` changes. Also +/// whether any curved segment is selected. +fn held_segments(doc: &Document, sel: &mut Selection, d: Vec2) -> (bool, Vec<(NodeId, usize, usize)>) { + let (mut held, mut bends) = (false, vec![]); + for (&id, refs) in &sel.segments { + let (Some(path), Some(set)) = (doc.node(id).and_then(Node::path_data), sel.anchors.get_mut(&id)) else { continue }; + let ends = |(si, seg): SegmentRef| path.subpaths.get(si).map(|sp| [(si, seg), (si, (seg + 1) % sp.anchors.len())]); + let curved = |&(si, seg): &SegmentRef| path.subpaths.get(si).is_some_and(|sp| seg < sp.segment_count() && !sp.segment_is_line(seg)); + let moved: BTreeSet = refs.iter().filter(|r| !curved(r)).filter_map(|&r| ends(r)).flatten().collect(); + for &(si, seg) in refs.iter().filter(|r| curved(r)) { + held = true; + for end in ends((si, seg)).into_iter().flatten().filter(|e| !moved.contains(e)) { + set.remove(&end); + } + if path.subpaths.get(si).is_some_and(|sp| sp.nudged_handles(seg, d).is_some()) { + bends.push((id, si, seg)); + } + } + } + (held, bends) +} + /// Interpolate Control Points: does a move of direct-selected anchors re-map the handles of the /// segments beside them (`interpolate` param, else General › Interpolate Control Points When /// Moving Anchors)? Noted in the journal, so a replay re-maps them alike whatever the preference @@ -276,56 +328,59 @@ pub(crate) fn interpolates_handles(s: &mut Session, p: &Value, cmd: &str) -> Res Ok(on) } +/// [`transform_selected`] on the active document's selection, as one undo step `label`. +pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> { + let sel = s.doc()?.selection.clone(); + s.edit(label, |doc, _| transform_selected(doc, &sel, xf, sc, interpolate)) +} + /// Apply `xf` to the direct-selected anchors, their handles with them, and (with `sc`) to the -/// objects selected whole (those with no entry in the selection's `anchors`). An object inside +/// objects selected whole (those with no entry in `sel`'s `anchors`). An object inside /// another selected object, such as a path in a selected group, moves once, with that object. /// When `xf` is a move and `interpolate` is on, the handles of each segment with one moved end /// are re-mapped ([`move_interpolating_handles`]). -pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> { - let sel = s.doc()?.selection.clone(); - let ids = super::edit::outermost(&s.doc()?.doc, sel.objects.clone()); +fn transform_selected(doc: &mut Document, sel: &Selection, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> { + let ids = super::edit::outermost(doc, sel.objects.clone()); let c = xf.as_coeffs(); let is_translation = (c[0] - 1.0).abs() < 1e-9 && c[1].abs() < 1e-9 && c[2].abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9; let delta = vectorcraft_geom::Vec2::new(c[4], c[5]); - s.edit(label, |doc, _| { - for id in &ids { - match sel.anchors.get(id) { - Some(set) => { - let path = path_mut(doc, *id)?; - // Only an exact move takes the interpolating path: a near-identity scale or - // turn still transforms the anchors as asked. - if interpolate && c[..4] == [1.0, 0.0, 0.0, 1.0] { - move_interpolating_handles(path, set, delta); - } else { - for &(si, ai) in set { - if let Some(a) = path.anchor_mut(si, ai) { - *a = a.transform(xf); - } + for id in &ids { + match sel.anchors.get(id) { + Some(set) => { + let path = path_mut(doc, *id)?; + // Only an exact move takes the interpolating path: a near-identity scale or + // turn still transforms the anchors as asked. + if interpolate && c[..4] == [1.0, 0.0, 0.0, 1.0] { + move_interpolating_handles(path, set, delta); + } else { + for &(si, ai) in set { + if let Some(a) = path.anchor_mut(si, ai) { + *a = a.transform(xf); } } - // A pixel-aligned path, or the pixel-aligned compound path that holds it, snaps - // to the pixel grid again after its anchors move. - let top = compound_or_self(doc, *id); - if let Some(n) = doc.node_mut(top) { - super::object::snap_if_aligned(n); - } } - None => { - if let Some(n) = doc.node_mut(*id) { - n.transform(xf, sc); - super::object::keep_pixel_aligned(n, sc); - } - super::object::keep_compound_aligned(doc, *id, sc); + // A pixel-aligned path, or the pixel-aligned compound path that holds it, snaps + // to the pixel grid again after its anchors move. + let top = compound_or_self(doc, *id); + if let Some(n) = doc.node_mut(top) { + super::object::snap_if_aligned(n); } } - } - if is_translation && (delta.x != 0.0 || delta.y != 0.0) { - for &i in &sel.guides { - doc.edit_ruler_guide(i, |g| *g = g.moved(delta)); + None => { + if let Some(n) = doc.node_mut(*id) { + n.transform(xf, sc); + super::object::keep_pixel_aligned(n, sc); + } + super::object::keep_compound_aligned(doc, *id, sc); } } - Ok(()) - }) + } + if is_translation && (delta.x != 0.0 || delta.y != 0.0) { + for &i in &sel.guides { + doc.edit_ruler_guide(i, |g| *g = g.moved(delta)); + } + } + Ok(()) } /// Move the anchors `set` of `path` by `d`, their handles with them, then re-map the two handles @@ -2155,6 +2210,7 @@ fn insert_anchor(s: &mut Session, p: &Value) -> Result { let si = usize_opt(p, "subpath", "path.insertAnchor")?.unwrap_or(0); let seg = index_opt(p, "segment", "path.insertAnchor")?.ok_or_else(|| bad("path.insertAnchor", "missing segment"))?; let t = number_or(p, "t", 0.5, "path.insertAnchor")?.clamp(0.0, 1.0); + let select_anchor = switch_or(p, "selectAnchor", false, "path.insertAnchor")?; let idx = s.edit("Add Anchor Point", |d, sel| { let path = path_mut(d, id)?; let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; @@ -2164,8 +2220,9 @@ fn insert_anchor(s: &mut Session, p: &Value) -> Result { let idx = sp.insert_anchor(seg, t); renumber_after_insert(sel, id, si, idx); // A path that wasn't selected becomes the selection, its new anchor direct-selected, so - // the point added shows and can be edited at once (#4237). - if !sel.contains(id) { + // the point added shows and can be edited at once (#4237). `selectAnchor` does the same + // for a path that is selected. + if select_anchor || !sel.contains(id) { sel.clear(); sel.add(id); sel.anchors.entry(id).or_default().insert((si, idx)); diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index 890f72455d..86c22d2776 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -141,6 +141,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("disableAutoAddDelete", "General", "Options", "Disable Auto Add/Delete", bool), p!("interpolateControlPoints", "General", "Options", "Interpolate Control Points When Moving Anchors", bool), p!("deleteKeepsPathsJoined", "General", "Options", "Delete Removes Anchor Points and Keeps Paths Joined", bool), + p!("doubleClickAddsAnchorPoints", "General", "Options", "Double-Click Adds Anchor Points", bool), p!("usePreciseCursors", "General", "Options", "Use Precise Cursors", bool), p!("showToolTips", "General", "Options", "Show Tool Tips", bool), p!("showToolCards", "General", "Options", "Show Tool Cards", bool), diff --git a/crates/engine/src/cmd/swatch.rs b/crates/engine/src/cmd/swatch.rs index 511352b9a5..8137e561cf 100644 --- a/crates/engine/src/cmd/swatch.rs +++ b/crates/engine/src/cmd/swatch.rs @@ -1252,7 +1252,7 @@ fn swatch_rename_group(s: &mut Session, p: &Value) -> Result { return Err(bad(C, format!("a swatch or color group named `{name}` already exists"))); } // A drag still in progress is a step of its own, so canceling or undoing it leaves the rename. - if !s.previewing && s.batch_stash.is_none() && s.in_interaction() { + if !s.previewing && s.batch_stash.is_none() && (s.in_interaction() || s.holds_interaction()) { super::settle_interaction(s)?; } s.edit("Color Group Options", |d, _| { diff --git a/crates/engine/src/cmd/webexport.rs b/crates/engine/src/cmd/webexport.rs index 14c5fa6ebd..5f2d2cbffd 100644 --- a/crates/engine/src/cmd/webexport.rs +++ b/crates/engine/src/cmd/webexport.rs @@ -340,11 +340,16 @@ pub struct ColorTable { type Shift = ([u8; 3], [u8; 3]); /// The most colours a colour table list holds. -const MAX_TABLE: usize = 256; +pub const MAX_TABLE: usize = 256; /// The error for a deletion that would leave the color table no color for the pixels. pub const KEEP_ONE: &str = "colorTable.deleted: at least one color has to stay in the color table"; +/// The error for a colour table list `what` (`colorTable.`) with more than [`MAX_TABLE`] colours. +pub fn too_many(what: &str) -> String { + format!("colorTable.{what}: at most {MAX_TABLE} colours") +} + impl ColorTable { /// Whether the table is a Custom one: a color was deleted or the palette is fixed. pub fn is_custom(&self) -> bool { @@ -353,7 +358,7 @@ impl ColorTable { fn colors(list: &[String], what: &str) -> std::result::Result, String> { if list.len() > MAX_TABLE { - return Err(format!("colorTable.{what}: at most {MAX_TABLE} colours")); + return Err(too_many(what)); } list.iter().map(|h| Self::rgb(h).ok_or_else(|| format!("colorTable.{what}: `{h}` is not a colour such as \"#ff8800\""))).collect() } diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index 33ede81772..f7f9197f1d 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -8,6 +8,10 @@ pub struct Interaction { /// The selection the previews start from (shared, so a preview frame copies nothing). pub selection: Arc, pub preview: Option<(String, Value)>, + /// The active tool began it (a drag): a command from outside the tool runs as a step of its + /// own under it ([`crate::Session::outside_interaction`]). A dialog or a panel that begins an + /// interaction runs its commands inside it. + pub(crate) tool: bool, /// A replaced or canceled preview restores these new-art paints from before the interaction. pub(crate) paint: vectorcraft_tools::PaintDefaults, /// A preview of the interaction gave `defaultsOnly: true`: every later preview and a cancel put @@ -41,6 +45,61 @@ pub struct Interaction { pub keep_on_switch: bool, } +/// An interaction that a command from outside the tool set aside while it runs +/// ([`crate::Session::outside_interaction`]). +#[derive(Debug)] +pub(crate) struct HeldInteraction { + /// The [`crate::DocState::uid`] of the interaction's document. + pub(crate) uid: u64, + pub(crate) interaction: Interaction, + /// The document and the selection on show when the command began, when a preview had changed + /// them from the interaction's snapshot. + pub(crate) shown: Option<(Arc, Selection)>, + /// The document's current layer, highlighted Layers panel rows, highlighted variable and + /// isolation when the command began; a cancel puts back the ones it changed as it left them. + pub(crate) state: ViewState, + /// The new-art paints when the command began: a change the command makes to them stays when + /// the interaction's next preview or a cancel puts back the paints it began with. + pub(crate) paint: vectorcraft_tools::PaintDefaults, +} + +/// The per-document state an interaction puts back when it is canceled, besides the document and +/// the selection. +#[derive(Debug, PartialEq)] +pub(crate) struct ViewState { + pub(crate) active_layer: Option, + pub(crate) layer_rows: Vec, + pub(crate) variables_highlight: Option, + pub(crate) isolation: Option, +} + +impl ViewState { + pub(crate) fn of(st: &crate::DocState) -> Self { + ViewState { + active_layer: st.active_layer, + layer_rows: st.layer_rows.clone(), + variables_highlight: st.variables_highlight.clone(), + isolation: st.isolation, + } + } + + /// Give `it` the parts of `now` that differ from `self`, the state before a command. + pub(crate) fn rebase(&self, now: ViewState, it: &mut Interaction) { + if now.active_layer != self.active_layer { + it.active_layer = now.active_layer; + } + if now.layer_rows != self.layer_rows { + it.layer_rows = now.layer_rows; + } + if now.variables_highlight != self.variables_highlight { + it.variables_highlight = now.variables_highlight; + } + if now.isolation != self.isolation { + it.isolation = now.isolation; + } + } +} + /// What Object → Transform → Transform Again (⌘D) repeats ([`SessionState::last_transform`]). #[derive(Clone, Debug, PartialEq)] pub enum LastTransform { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 3ca9435cc8..9863cf7b76 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -338,6 +338,9 @@ pub struct Session { /// The warnings of the previews that settling an interaction applied, while a top-level command /// or the tool's actions collect them ([`Session::collect_settled_warnings`]). settled_warnings: Option>, + /// The interaction a command from outside the tool set aside while it runs + /// ([`Session::outside_interaction`]). + held_interaction: Option, /// While [`Session::preview`] runs its command: its edits are the interaction's own. previewing: bool, /// The images Remove Background decoded during the interaction's preview steps, emptied when @@ -456,7 +459,7 @@ pub use error::{EngineError, READ_ONLY_LOCATION, Result, SCRIPT_BUSY}; #[cfg(test)] use history::history_budget_for; pub use history::{History, HistoryEntry, NamedStep, default_history_budget}; -pub(crate) use interaction::PreviewCopies; +pub(crate) use interaction::{HeldInteraction, PreviewCopies}; pub use interaction::{Interaction, LastTransform, UndoGroup, UndoScope}; pub use prefs::{DrawMode, KEY_HOLD_DELAY, KEY_HOLD_DELAY_RANGE, PluginBudget, Prefs}; pub use sanity::TOO_DEEP; diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 990cbd25c2..1e0edb076e 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -61,6 +61,9 @@ pub struct Prefs { /// the curve around each one, instead of deleting them with their segments. Off (the default), /// Clear opens the path there. pub delete_keeps_paths_joined: bool, + /// General › Double-Click Adds Anchor Points: on, a plain double-click on a path segment with + /// Direct Selection adds an anchor there. Off (the default), the double-click adds nothing. + pub double_click_adds_anchor_points: bool, pub use_precise_cursors: bool, pub show_tool_tips: bool, /// General › Show Tool Cards: with tool tips on, a tool button's tool tip is a card with what the @@ -486,6 +489,7 @@ impl Default for Prefs { disable_auto_add_delete: false, interpolate_control_points: false, delete_keeps_paths_joined: false, + double_click_adds_anchor_points: false, use_precise_cursors: false, show_tool_tips: true, show_tool_cards: false, diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index d924813def..1ed2654d51 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -141,6 +141,7 @@ impl Session { recovery: Default::default(), in_tool_actions: false, settled_warnings: None, + held_interaction: None, previewing: false, decoded_images: Default::default(), envelope_defaults: None, diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 2504d8984a..cc7af44898 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -287,6 +287,190 @@ impl Session { (r, settled) } + /// Run `f`, the top-level command `id` with `params` from outside the tool (a panel, a menu + /// item, an automation client), with the active document's tool drag set aside: the command + /// runs on the document the drag started from and records its own undo step and journal entry. + /// The drag then starts from what the command left, and its preview is applied again, so the + /// next preview, the commit and a cancel keep the command's edit, and Undo takes back the drag's + /// step before the command's. While the command runs, [`Session::in_interaction`] is false, so + /// it updates Recent Colors and converts or remaps the new-art paints at once, as it does with + /// no drag in progress. + /// + /// The interaction stays as it is, and the command runs inside it, for an interaction a dialog + /// or a panel began (it builds its preview from commands), for typing in progress + /// ([`Session::edit`] keeps it as a step of its own), for the Quick Pen (an edit made outside + /// it ends the path it draws), and for a copy made with `object.transform` during a drag that + /// copies (it copies the document as the drag's move left it). A command that settles, + /// commits or cancels the interaction, or that hands the active tool actions to apply, gets it + /// back first ([`Session::put_back_interaction`]), as it found it. + pub(crate) fn outside_interaction(&mut self, id: &str, params: &Value, f: impl FnOnce(&mut Self) -> Result) -> Result { + if cmd::typing_in_progress(self) || self.tool_id() == vectorcraft_tools::quickpen::ID { + return f(self); + } + let Some(st) = self.active_mut() else { return f(self) }; + let Some(it) = st.interaction.as_ref().filter(|it| it.tool) else { return f(self) }; + // A drag that copies: its latest preview, applied or held back by Real-time Drawing off, copies. + let copying = it.preview.as_ref().is_some_and(|(c, p)| c == "object.transform" && p.get("copy").and_then(Value::as_bool) == Some(true)); + if copying && id == "object.transform" && params.get("copy").and_then(Value::as_bool) == Some(true) { + return f(self); + } + let Some(interaction) = st.interaction.take() else { return f(self) }; + // The document and selection on show, when a preview changed them. + let previewed = !Arc::ptr_eq(&st.doc, &interaction.doc) || st.selection != *interaction.selection; + let shown = previewed.then(|| (st.doc.clone(), st.selection.clone())); + if previewed { + st.doc = interaction.doc.clone(); + st.selection.clone_from(&interaction.selection); + st.revision += 1; + cmd::globaledit::follow_history(st); + } + let (uid, state) = (st.uid, crate::interaction::ViewState::of(st)); + let paint = self.paint.clone(); + self.held_interaction = Some(crate::HeldInteraction { uid, interaction, shown, state, paint }); + if previewed { + self.sync_front_profiles(); + } + let r = f(self); + self.put_back_interaction(); + r + } + + /// Put back the interaction [`Session::outside_interaction`] set aside. When the command left + /// the document and the selection as it found them, the preview on show before it is on show + /// again. Otherwise the interaction starts from the document the command left and from its + /// own selection, without the objects the command removed, hid or locked, and the preview that Real-time + /// Drawing showed is applied to it again. The warning or the error of that preview goes to + /// the command's result ([`Session::note_settled_warning`]); a preview that fails leaves the + /// interaction with nothing to commit. An interaction whose document the command closed ends, + /// and so does one with anchors or segments selected on a path the command changed in more + /// than a move. A document + /// the command left an interaction of its own on keeps that one. + pub(crate) fn put_back_interaction(&mut self) { + let Some(crate::HeldInteraction { uid, interaction: mut it, shown, state, paint }) = self.held_interaction.take() else { return }; + // A selection command loaded the paints of the selection it made into the fill and stroke + // proxies. The drag goes on with its own selection, so they show its paints again. + if self.paint != paint + && let Some(st) = self.active_mut().filter(|d| d.uid == uid && d.interaction.is_none()) + { + let own = drag_selection(&it.selection, &st.doc); + if st.selection != own { + let made = std::mem::replace(&mut st.selection, own); + self.inherit_new_art(); + self.load_selection_paints(); + if let Some(st) = self.active_mut() { + st.selection = made; + } + } + } + // A change the command made to the new-art paints stays when the next preview or a cancel + // puts back the paints the interaction began with (the Live Paint Bucket's colors); the + // parts it left alone keep the interaction's. The pattern lists every field, so a field + // added to `PaintDefaults` does not compile until it is handled here. + let vectorcraft_tools::PaintDefaults { fill, stroke, stroke_width, appearance, opacity, blend, style, inherited } = &self.paint; + let start = &mut it.paint; + if *fill != paint.fill { + start.fill.clone_from(fill); + } + if *stroke != paint.stroke { + start.stroke.clone_from(stroke); + } + if *stroke_width != paint.stroke_width { + start.stroke_width = *stroke_width; + } + if *appearance != paint.appearance { + start.appearance.clone_from(appearance); + } + if *opacity != paint.opacity { + start.opacity = *opacity; + } + if *blend != paint.blend { + start.blend = *blend; + } + if *style != paint.style { + start.style.clone_from(style); + } + if *inherited != paint.inherited { + start.inherited = *inherited; + } + let active = self.active().is_some_and(|d| d.uid == uid); + let Some(st) = self.docs.iter_mut().find(|d| d.uid == uid) else { return }; + if st.interaction.is_some() { + return; + } + // A change the command made to the current layer, the highlighted rows or variable, or + // isolation stays when the interaction is canceled. + state.rebase(crate::interaction::ViewState::of(st), &mut it); + let previewed = shown.is_some(); + if Arc::ptr_eq(&st.doc, &it.doc) && st.selection == *it.selection { + if let Some((doc, selection)) = shown { + st.doc = doc; + st.selection = selection; + st.revision += 1; + cmd::globaledit::follow_history(st); + } + st.interaction = Some(it); + if previewed { + self.sync_front_profiles(); + } + return; + } + // The drag's anchors and segments are numbered in the paths it began on. When the command + // changed one of those paths in more than a move, the numbers can name other points, and + // the drag ends without a step. + if renumbered(&it.selection, &it.doc, &st.doc) { + self.clear_deferred_overlay_cache(); + return; + } + let began = std::mem::replace(&mut it.doc, st.doc.clone()); + // The drag acts on the objects it began with: a selection the command made (a paste, a + // duplicate, Select All) does not change what the drag moves. + it.selection = Arc::new(drag_selection(&it.selection, &st.doc)); + // The journal holds the selection the command left. The drag's own selection is journaled + // after it, so the drag and the commands after it replay on the objects they act on. + let reselect = (active && st.selection != *it.selection) + .then(|| selection_steps(&it.selection, &st.selection, &st.doc, st.active_layer, &st.highlighted_rows())); + // The objects the drag's preview names leave out those the command removed, hid or locked. + // A preview left naming none has nothing to apply, and the drag records no step. + if it.preview.as_mut().is_some_and(|(_, p)| !drag_targets(p, &began, &st.doc)) { + it.preview = None; + } + it.copies = None; + it.move_box = std::sync::OnceLock::new(); + // With Real-time Drawing off the preview waits for the commit, as it did before the command. + let again = it.preview.clone().filter(|_| previewed && active); + // Without a preview to apply, the drag's own selection is on show, as a preview would leave + // it before it acts. + if again.is_none() && st.selection != *it.selection { + st.selection.clone_from(&it.selection); + st.revision += 1; + } + st.interaction = Some(it); + if let Some(steps) = reselect { + let (from, grouped) = (self.journal.len(), self.undo_group_docs()); + for step in steps { + self.journal.push(step); + } + self.journal_in_undo_groups(Some(uid), &grouped, from); + } + self.clear_deferred_overlay_cache(); + if let Some((cmd, p)) = again { + match self.preview(&cmd, &p) { + Ok(v) => { + if let Some(w) = v.get("warning").and_then(Value::as_str) { + self.note_settled_warning(w); + } + } + Err(e) => self.note_settled_warning(&e.to_string()), + } + } + } + + /// While a command from outside the tool runs: the interaction it set aside + /// ([`Session::outside_interaction`]). + pub(crate) fn holds_interaction(&self) -> bool { + self.held_interaction.is_some() + } + /// [`Session::begin_interaction`] for a dialog or a panel that starts a preview → the warnings /// of the preview that keeping typing in progress applied, for its status bar. pub fn begin_interaction_warned(&mut self, label: &str) -> Result> { @@ -311,6 +495,8 @@ impl Session { if label != "Typing" && cmd::typing_in_progress(self) { cmd::settle_interaction(self)?; } + // A command from outside the tool that begins an interaction during a drag joins the drag's. + self.put_back_interaction(); // An edit the tool computes on another thread (a Shape Builder merge) is applied first too, // so the snapshot the interaction previews from and goes back to holds it. if !self.in_interaction() { @@ -327,6 +513,7 @@ impl Session { doc: st.doc.clone(), selection: Arc::new(st.selection.clone()), preview: None, + tool: false, paint, used_defaults_only: false, preview_paint: None, @@ -347,6 +534,7 @@ impl Session { /// Re-apply `cmd` on top of the interaction snapshot (replacing the previous preview). pub fn preview(&mut self, cmd: &str, params: &Value) -> Result { + self.put_back_interaction(); if self.script_running() { return Err(EngineError::Busy); } @@ -438,6 +626,7 @@ impl Session { fn commit_interaction_unwatched(&mut self) -> Result<()> { self.clear_deferred_overlay_cache(); self.decoded_images.empty(); + self.put_back_interaction(); if let Some(paint) = self.active().and_then(|st| st.interaction.as_ref()).and_then(|it| it.preview_paint.clone()) { self.paint = paint; } @@ -527,6 +716,7 @@ impl Session { } pub fn cancel_interaction(&mut self) -> Result<()> { + self.put_back_interaction(); self.clear_deferred_overlay_cache(); self.decoded_images.empty(); self.pending_paint = None; @@ -567,3 +757,163 @@ impl Session { self.active().is_some_and(|d| d.interaction.is_some()) } } + +/// The selection a drag began with, without the objects that a command run during it removed, +/// hid or locked in `doc`. +fn drag_selection(began: &Selection, doc: &Document) -> Selection { + let mut selection = began.clone(); + selection.prune(doc); + let editable = doc.editable(); + let held: Vec<_> = selection.objects.iter().copied().filter(|&id| !editable(id)).collect(); + selection.remove_all(held); + selection +} + +/// Take out of the `ids` of a drag's preview `params` the objects that a command run during the +/// drag removed from `doc`, or hid or locked there while they were editable in `began` → false +/// when the preview named objects and none of them is left. +fn drag_targets(params: &mut Value, began: &Document, doc: &Document) -> bool { + let Some(ids) = params.get_mut("ids").and_then(Value::as_array_mut) else { return true }; + if ids.is_empty() { + return true; + } + let (was, now) = (began.editable(), doc.editable()); + ids.retain(|v| v.as_u64().map(vectorcraft_doc::NodeId).is_none_or(|id| doc.node(id).is_some() && (now(id) || !was(id)))); + !ids.is_empty() +} + +/// Whether a path with anchors or segments in `selection` is other in `doc` than in `began`, the +/// document a drag began from, in more than a move: its anchors added, removed, put in another +/// order (Reverse Path Direction) or reshaped, or a subpath opened or closed. A path the command +/// moved as a whole keeps its numbers. +fn renumbered(selection: &Selection, began: &Document, doc: &Document) -> bool { + fn path(d: &Document, id: vectorcraft_doc::NodeId) -> Option<&[vectorcraft_geom::SubPath]> { + d.node(id).and_then(|n| n.path_data()).map(|p| p.subpaths.as_slice()) + } + selection.anchors.keys().chain(selection.segments.keys()).any(|&id| match (path(began, id), path(doc, id)) { + (Some(was), Some(now)) => !moved_whole(was, now), + (was, now) => was.is_some() != now.is_some(), + }) +} + +/// Whether the subpaths `now` are the subpaths `was` moved by one offset: the same number of each, +/// each opened or closed as before, every anchor of the same kind, and every anchor and handle +/// offset alike. +fn moved_whole(was: &[vectorcraft_geom::SubPath], now: &[vectorcraft_geom::SubPath]) -> bool { + if was.len() != now.len() || was.iter().zip(now).any(|(a, b)| a.closed != b.closed || a.anchors.len() != b.anchors.len()) { + return false; + } + let mut pairs = was.iter().zip(now).flat_map(|(a, b)| a.anchors.iter().zip(b.anchors.iter())); + let Some((a0, b0)) = pairs.next() else { return true }; + let (dx, dy) = (b0.p.x - a0.p.x, b0.p.y - a0.p.y); + let alike = |a: vectorcraft_geom::Point, b: vectorcraft_geom::Point| { + (b.x - a.x - dx).abs() <= vectorcraft_geom::EPS && (b.y - a.y - dy).abs() <= vectorcraft_geom::EPS + }; + std::iter::once((a0, b0)).chain(pairs).all(|(a, b)| a.kind == b.kind && alike(a.p, b.p) && alike(a.h_in, b.h_in) && alike(a.h_out, b.h_out)) +} + +/// The journal entries that select `selection` again in `doc` after `made`, the selection a +/// command left with `layer` current and `rows` highlighted in the Layers panel ([`object_steps`]). +/// When selecting the objects would make another layer current, `layer.setCurrent` makes `layer` +/// current again, as the drag leaves it, and `layer.highlight` gives back the highlighted rows. +fn selection_steps( + selection: &Selection, + made: &Selection, + doc: &Document, + layer: Option, + rows: &[vectorcraft_doc::NodeId], +) -> Vec<(String, Value)> { + let mut steps = object_steps(selection, doc); + // `layer.target` on a layer makes it current; any other change to the selected objects makes + // the layer of the last selected object current. + let targeted = steps.first().is_some_and(|(id, _)| id == "layer.target"); + let selects = match selection.target.filter(|t| targeted && doc.node(*t).is_some_and(|n| n.is_layer())) { + Some(t) => Some(t), + None if selection.objects != made.objects => { + selection.objects.last().and_then(|id| doc.layer_containing(*id)).filter(|l| doc.is_editable(*l)) + } + None => None, + }; + if let Some(layer) = layer.filter(|l| selects.is_some_and(|s| s != *l)) { + steps.push(("layer.setCurrent".into(), serde_json::json!({ "id": layer.0 }))); + // `layer.setCurrent` highlights the layer's row. `layer.highlight` sets the rows the command + // left instead; it keeps `layer` current while the last of them is on `layer`, or none is left. + if rows != [layer] && rows.last().is_none_or(|r| doc.layer_containing(*r) == Some(layer)) { + let ids: Vec = rows.iter().map(|r| r.0).collect(); + steps.push(("layer.highlight".into(), serde_json::json!({ "ids": ids, "mode": "set" }))); + } + } + steps +} + +/// The journal entries that select `selection` in `doc`: the selections made on their own (its +/// slices with `object.slice.select`, its target with `layer.target`, its symbol part with +/// `symbol.instance.selectPart`, its Objects on Path member with +/// `object.objectsOnPath.selectMember`), or its objects in their order (`select.set`), the anchors +/// left out on paths that are not selected whole (`select.anchorsMany`), the anchors of paths with +/// every anchor selected (`select.anchors`) and its segments (`select.segments`); after its objects +/// or its target, its ruler guides (`guide.select`) and its key object, key guide or key anchor +/// (`select.key`). +fn object_steps(selection: &Selection, doc: &Document) -> Vec<(String, Value)> { + use serde_json::json; + if !selection.slices.is_empty() { + let slices: Vec = selection.slices.iter().map(|id| id.0).collect(); + return vec![("object.slice.select".into(), json!({ "slices": slices }))]; + } + // A target is selected again only while targeting it selects the same objects: when a command + // added art to a targeted layer, `select.set` selects the drag's objects. + let targets = |t: vectorcraft_doc::NodeId| match doc.node(t) { + Some(n) if n.is_layer() => n.layer_art(true) == selection.objects, + _ => selection.objects == [t], + }; + let json_refs = |refs: &mut dyn Iterator| Value::Array(refs.map(|&(a, b)| json!([a, b])).collect()); + // A targeted object keeps the ruler guides and the key selected beside it. + let mut steps = if let Some(t) = selection.target.filter(|&t| targets(t)) { + vec![("layer.target".to_string(), json!({ "id": t.0 }))] + } else if let Some(part) = &selection.symbol_part { + return vec![("symbol.instance.selectPart".into(), json!({ "id": part.instance.0, "path": part.path }))]; + } else if let Some(member) = selection.on_path_member { + return vec![("object.objectsOnPath.selectMember".into(), json!({ "member": member.0 }))]; + } else { + let ids: Vec = selection.objects.iter().map(|id| id.0).collect(); + let mut steps = vec![("select.set".to_string(), json!({ "ids": ids }))]; + // `select.set` selects each path whole: subtracting the anchors that are not selected leaves + // the ones that are, and keeps the order of the objects. A path with every anchor selected + // as anchors gets them back with `select.anchors`, which keeps them all as anchors. + let mut every = Vec::new(); + let partial: Vec = selection + .objects + .iter() + .filter_map(|id| { + let refs = selection.anchors.get(id)?; + let path = doc.node(*id)?.path_data()?; + let out: Vec<(usize, usize)> = path.anchors().map(|(s, i, _)| (s, i)).filter(|r| !refs.contains(r)).collect(); + if out.is_empty() { + every.push(("select.anchors".to_string(), json!({ "id": id.0, "anchors": json_refs(&mut refs.iter()), "mode": "add" }))); + return None; + } + Some(json!({ "id": id.0, "anchors": json_refs(&mut out.iter()) })) + }) + .collect(); + if !partial.is_empty() { + steps.push(("select.anchorsMany".into(), json!({ "items": partial, "mode": "subtract" }))); + } + steps.extend(every); + for (id, refs) in &selection.segments { + steps.push(("select.segments".into(), json!({ "id": id.0, "segments": json_refs(&mut refs.iter()), "mode": "add" }))); + } + steps + }; + if !selection.guides.is_empty() { + let indexes = cmd::guide_indexes(doc, &selection.guides); + steps.push(("guide.select".into(), json!({ "indexes": indexes, "toggle": true }))); + } + if let Some((id, (s, i))) = selection.key_anchor { + steps.push(("select.key".into(), json!({ "id": id.0, "anchor": [s, i] }))); + } else if let Some(g) = selection.key_guide.and_then(|g| cmd::guide_indexes(doc, &[g]).first().copied()) { + steps.push(("select.key".into(), json!({ "guide": g }))); + } else if let Some(key) = selection.key { + steps.push(("select.key".into(), json!({ "id": key.0 }))); + } + steps +} diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index a6d2faec6d..f87d37691f 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -99,10 +99,17 @@ impl Session { self.finish_tool_edit_later()?; } let outer = std::mem::replace(&mut self.reading, !spec.journal || JOURNALED_READS.contains(&id)); + // A command from outside the tool, while the tool's drag is in progress, is a step of its + // own before the drag's ([`Session::outside_interaction`]). Find Objects with `select` is + // journaled (`Session::journal_query`), so it is one too. + let find_selects = id == "document.find" && params.get("select").and_then(Value::as_bool) == Some(true); + let outside = (spec.journal || find_selects) && !self.previewing && !self.in_tool_actions; // A preview that a top-level command applied first (a drag with Real-time Drawing off, kept // before Undo) reports its warning in the command's result. let r = if self.depth == 0 { - let (r, settled) = self.collect_settled_warnings(|s| s.execute_spec(spec, id, params)); + let (r, settled) = self.collect_settled_warnings(|s| { + if outside { s.outside_interaction(id, params, |s| s.execute_spec(spec, id, params)) } else { s.execute_spec(spec, id, params) } + }); r.map(|v| with_settled_warnings(v, &settled)) } else { self.execute_spec(spec, id, params) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 9e22f5034e..cd3ff27d5d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -54,6 +54,7 @@ mod distort; mod docsetup; mod document_close; mod document_move; +mod double_click_adds_anchor; mod draw2; mod dynamic_symbols; mod dynamic_text; @@ -88,6 +89,7 @@ mod history_document; mod history_mem; mod ids_without_selection; mod inline; +mod interaction_commands; mod interactivity; mod interpolate_handles; mod intertwine; @@ -180,6 +182,7 @@ mod script_include; mod script_io; mod script_run; mod scripts; +mod segment_nudge; mod select_effects; mod select_ids_first; mod shaper; diff --git a/crates/engine/src/tests/appearance.rs b/crates/engine/src/tests/appearance.rs index 9a29f9e026..44b49f148d 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -145,6 +145,23 @@ fn item_rows_follow_remove_and_move() { assert_eq!(s.appearance_item(), None); } +#[test] +fn moving_a_single_row_keeps_the_active_objects_landing() { + let mut s = session(); + let short = rect(&mut s, 50.0); + let long = rect(&mut s, 200.0); + run(&mut s, "appearance.addFill", json!({})); + run(&mut s, "select.set", json!({"ids": [short.0, long.0]})); + run(&mut s, "appearance.setActiveItem", json!({"index": 0})); + + let moved = run(&mut s, "appearance.moveItem", json!({"ids": [short.0, long.0], "from": 0, "to": 2})); + + assert_eq!(moved["index"], 2, "the command still reports the last target's landing"); + assert!(matches!(node(&s, short).appearance.items[1], AppearanceItem::Fill(_))); + assert!(matches!(node(&s, long).appearance.items[0], AppearanceItem::Stroke(_))); + assert_eq!(s.appearance_item(), Some(1), "the active row follows its own object's landing"); +} + #[test] fn transparency_goes_to_the_targeted_item() { let mut s = session(); diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 62b1bac629..427def6754 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -1357,7 +1357,10 @@ fn brush_freehand_refuses_unknown_keys() { let spec = crate::cmd::find_command("brush.freehand").unwrap(); let mut keys = crate::cmd::params::accepted_keys(spec.params).expect("the description names every key"); keys.sort_unstable(); - assert_eq!(keys, ["brush", "closed", "connect", "extend", "fidelity", "fill", "fit", "keepSelected", "points", "redraw", "style"]); + assert_eq!( + keys, + ["brush", "closed", "connect", "extend", "fidelity", "fill", "fit", "keepSelected", "leaveSelection", "points", "redraw", "style"] + ); let mut s = session(); let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); select(&mut s, &[a]); diff --git a/crates/engine/src/tests/double_click_adds_anchor.rs b/crates/engine/src/tests/double_click_adds_anchor.rs new file mode 100644 index 0000000000..ed4c2b33e3 --- /dev/null +++ b/crates/engine/src/tests/double_click_adds_anchor.rs @@ -0,0 +1,124 @@ +//! General › Double-Click Adds Anchor Points (`doubleClickAddsAnchorPoints`). With it on, a +//! Direct Selection double-click on a path segment adds an anchor there. Off (the default), the +//! double-click adds nothing. + +use serde_json::json; +use vectorcraft_geom::kurbo::ParamCurveNearest; +use vectorcraft_geom::{ParamCurve, PathData, Point}; +use vectorcraft_tools::{PointerEvent, PointerKind}; + +use super::history; +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s +} + +fn set_pref(s: &mut Session, key: &str, on: bool) { + s.execute("prefs.set", &json!({"key": key, "value": on})).unwrap(); +} + +fn path_of(s: &Session, id: NodeId) -> Option { + s.doc().unwrap().doc.node(id).and_then(|n| n.path_data().cloned()) +} + +fn points(s: &Session, id: NodeId) -> Vec { + path_of(s, id).unwrap().subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)).collect() +} + +/// Two clicks and the double-click that follows them, with Direct Selection, at `at`. On a segment +/// the clicks select it, so the double-click finds its path selected. +fn double_click(s: &mut Session, at: Point) { + let v = ViewInfo::default(); + s.select_tool("directSelection", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] { + s.pointer(&PointerEvent::new(kind, at.x, at.y), v).unwrap(); + } +} + +/// An open curve from (100, 300) to (300, 300) whose middle, at t = 0.5, is (200, 225). +fn arch(s: &mut Session) -> NodeId { + let anchors = json!([{"x": 100, "y": 300, "out": [100, 200]}, {"x": 300, "y": 300, "in": [300, 200]}]); + NodeId(s.execute("path.create", &json!({ "anchors": anchors, "closed": false })).unwrap()["id"].as_u64().unwrap()) +} + +#[test] +fn off_by_default() { + let s = session(); + assert!(!s.prefs.double_click_adds_anchor_points); +} + +#[test] +fn with_the_preference_on_a_double_click_on_a_segment_adds_an_anchor_in_one_undo_step() { + // The clicks before the double-click select the segment either way; an unselected path at the + // double-click is covered by the tools crate's tests. + for selected in [true, false] { + let mut s = session(); + set_pref(&mut s, "doubleClickAddsAnchorPoints", true); + let id = arch(&mut s); + if !selected { + s.execute("select.none", &json!({})).unwrap(); + } + let curve = path_of(&s, id).unwrap().subpaths[0].segment(0); + let before = history(&s).0; + double_click(&mut s, Point::new(200.0, 225.0)); + assert_eq!(history(&s).0, before + 1, "one undo step (selected before the clicks: {selected})"); + assert_eq!(points(&s, id).len(), 3, "an anchor is added (selected before the clicks: {selected})"); + assert!(points(&s, id)[1].distance(Point::new(200.0, 225.0)) < 0.5, "at the clicked point: {:?}", points(&s, id)); + let halves = path_of(&s, id).unwrap().subpaths[0].clone(); + for seg in 0..2 { + for t in [0.25, 0.5, 0.75] { + let q = ParamCurve::eval(&halves.segment(seg), t); + let d = ParamCurveNearest::nearest(&curve, q, 1e-9).distance_sq; + assert!(d < 1e-6, "the curve keeps its shape at {q:?}"); + } + } + let st = s.doc().unwrap(); + assert_eq!(st.selection.objects, vec![id]); + assert_eq!(st.selection.anchors.get(&id), Some(&[(0, 1)].into()), "only the new anchor is selected (selected before the clicks: {selected})"); + assert!(st.selection.segments.get(&id).is_none_or(|s| s.is_empty()), "no segment stays selected"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(points(&s, id).len(), 2, "undo removes it"); + } +} + +#[test] +fn with_the_preference_off_a_double_click_on_a_segment_adds_nothing() { + let mut s = session(); + let id = arch(&mut s); + let before = history(&s).0; + double_click(&mut s, Point::new(200.0, 225.0)); + assert_eq!(history(&s).0, before); + assert_eq!(points(&s, id).len(), 2); +} + +/// The two General preferences are separate: Delete Removes Anchor Points and Keeps Paths Joined +/// does not turn on the double-click, and the double-click preference does not change Delete. +#[test] +fn the_double_click_and_delete_preferences_are_separate() { + let mut s = session(); + set_pref(&mut s, "deleteKeepsPathsJoined", true); + let id = arch(&mut s); + let before = history(&s).0; + double_click(&mut s, Point::new(200.0, 225.0)); + assert_eq!(history(&s).0, before, "deleteKeepsPathsJoined alone adds no anchor"); + assert_eq!(points(&s, id).len(), 2); + + let mut s = session(); + set_pref(&mut s, "doubleClickAddsAnchorPoints", true); + let anchors = json!([{"x": 100, "y": 100}, {"x": 200, "y": 100}, {"x": 200, "y": 200}, {"x": 100, "y": 200}]); + let id = NodeId(s.execute("path.create", &json!({ "anchors": anchors, "closed": true })).unwrap()["id"].as_u64().unwrap()); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + assert!(!path_of(&s, id).unwrap().subpaths[0].closed, "Delete still opens the path"); +} + +#[test] +fn the_select_anchor_param_must_be_a_boolean() { + let mut s = session(); + let id = arch(&mut s); + assert!(s.execute("path.insertAnchor", &json!({"id": id.0, "segment": 0, "selectAnchor": "yes"})).is_err()); + assert_eq!(points(&s, id).len(), 2, "a refused call changes nothing"); +} diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 25f954dc4b..5017316c44 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -198,6 +198,12 @@ fn near(a: Point, b: Point) -> bool { a.distance(b) < 1e-6 } +/// Whether open subpath `sp`'s two ends are at `a` and `b`, in either order (within `tol`). +fn ends_at(sp: &vectorcraft_geom::SubPath, a: Point, b: Point, tol: f64) -> bool { + let (Some(f), Some(l)) = (sp.anchors.first(), sp.anchors.last()) else { return false }; + (f.p.distance(a) < tol && l.p.distance(b) < tol) || (f.p.distance(b) < tol && l.p.distance(a) < tol) +} + fn area(pd: &PathData) -> f64 { vectorcraft_pathops::area(pd, FillRule::NonZero) } @@ -519,7 +525,8 @@ fn pencil_redraws_the_section_of_a_selected_path_between_its_ends() { } /// On a closed path the stroke replaces the shorter way between where it starts and ends, and the -/// path stays closed; a stroke that doesn't end on the path draws a new one. +/// path stays closed; a stroke that doesn't end on the path opens it where the stroke starts and +/// ends where the stroke does (no new path). #[test] fn pencil_redraws_the_shorter_way_round_a_closed_path() { let mut s = session(); @@ -536,11 +543,12 @@ fn pencil_redraws_the_shorter_way_round_a_closed_path() { } let top = kurbo::Shape::bounding_box(&path(&s, id).to_bezpath()).y0; assert!(top < -20.0, "the dip: top {top}"); - // Not ending on the path: a new path, the rectangle as it was. - let before = path(&s, id); + // Not ending on the path: the rectangle opens at (50, 100) and follows the stroke out. s.execute("path.freehand", &json!({"points": [[50, 100], [80, 150], [120, 160]], "redraw": {"id": id.0, "within": 4}})).unwrap(); - assert_eq!(paths(&s).len(), 2); - assert_eq!(path(&s, id), before); + assert_eq!(paths(&s).len(), 1, "no new path"); + let sp = &path(&s, id).subpaths[0]; + assert!(!sp.closed, "the rectangle opened"); + assert!(ends_at(sp, Point::new(50.0, 100.0), Point::new(120.0, 160.0), 1e-6), "from the opening to the stroke's end: {sp:?}"); assert!(s.execute("path.freehand", &json!({"points": [[0, 0], [1, 1]], "redraw": {"id": id.0, "within": -1}})).is_err()); } @@ -7037,6 +7045,382 @@ fn pencil_redraws_a_selected_compound_path() { assert!(members(&s)[1] != before[1], "the hole is redrawn"); } +/// A Pencil stroke that starts on a selected closed shape and is lifted away from it takes the +/// shape with it: the shape opens where the stroke started, keeps its whole outline, fill and +/// selection, and ends where the pen was lifted. While the stroke is drawn the shape stays as it +/// was and the selection with it (the preview shows the stroke on its own); the release leaves no +/// new path. +#[test] +fn a_stroke_lifted_away_from_a_closed_shape_opens_it_and_follows_the_stroke() { + let mut s = session(); + s.execute("select.none", &json!({})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + let id = rect(&mut s, 100.0, 100.0, 200.0, 100.0); + let fill = s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint().clone(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.set_tool_option_cmd(&json!({"tool": "pencil", "values": {"editWithin": 12}})).unwrap(); + let v = view(); + s.select_tool("pencil", v).unwrap(); + let count = |s: &Session| s.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); + let shape = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone(); + let before = shape(&s); + // From the right edge, a little hook up and out to the right. + s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 150.0), v).unwrap(); + for (x, y) in [(303.0, 140.0), (308.0, 128.0), (316.0, 118.0), (326.0, 112.0), (338.0, 110.0)] { + s.pointer(&PointerEvent::new(PointerKind::Drag, x, y), v).unwrap(); + assert!(shape(&s) == before, "the shape stays as it was while the stroke is drawn"); + assert_eq!(s.doc().unwrap().selection.objects, vec![id], "and stays selected"); + } + s.pointer(&PointerEvent::new(PointerKind::Up, 338.0, 110.0), v).unwrap(); + assert_eq!(count(&s), 1, "no new path"); + assert_eq!(s.doc().unwrap().selection.objects, vec![id], "the shape stays selected"); + let n = s.doc().unwrap().doc.node(id).unwrap(); + assert_eq!(n.appearance.fill_paint(), fill, "the fill stays"); + let sp = &n.path_data().unwrap().subpaths[0]; + assert!(!sp.closed, "the shape opened"); + let ps: Vec = sp.anchors.iter().map(|a| a.p).collect(); + for corner in [(100.0, 100.0), (300.0, 100.0), (300.0, 200.0), (100.0, 200.0)] { + assert!(ps.iter().any(|p| near(*p, Point::new(corner.0, corner.1))), "{corner:?} kept: {ps:?}"); + } + assert!(ends_at(sp, Point::new(300.0, 150.0), Point::new(338.0, 110.0), 0.5), "from the opening to where the pen was lifted: {ps:?}"); + // The outline joins the stroke heading up, the stroke's way: next to the anchor where the + // stroke leaves the opening is the bottom right corner. + let last = ps.len() - 1; + let k = (1..last).find(|&i| ps[i].distance(Point::new(300.0, 150.0)) < 0.5).unwrap(); + assert!(near(ps[k - 1], Point::new(300.0, 200.0)) || near(ps[k + 1], Point::new(300.0, 200.0)), "joins from below: {ps:?}"); +} + +/// On an open path, a stroke from its middle lifted away from it cuts the path there and drops the +/// part the stroke heads along; the part behind stays and ends where the pen was lifted. +#[test] +fn a_stroke_lifted_away_from_an_open_path_drops_the_part_it_heads_along() { + for (towards_end, kept) in [(true, Point::new(100.0, 100.0)), (false, Point::new(300.0, 100.0))] { + let mut s = session(); + let id = line(&mut s, 100.0, 100.0, 300.0, 100.0); + let dx = if towards_end { 1.0 } else { -1.0 }; + let pts: Vec<_> = (0..8).map(|i| json!([200.0 + dx * 4.0 * f64::from(i), 100.0 - 5.0 * f64::from(i)])).collect(); + s.execute("path.freehand", &json!({"points": pts, "redraw": {"id": id.0, "within": 4}})).unwrap(); + assert_eq!(paths(&s).len(), 1, "no new path"); + let sp = &path(&s, id).subpaths[0]; + let ps: Vec = sp.anchors.iter().map(|a| a.p).collect(); + assert!( + ends_at(sp, kept, Point::new(200.0 + dx * 28.0, 65.0), 0.5), + "towards the end {towards_end}: the part behind stays and ends where the pen was lifted: {ps:?}" + ); + let dropped = Point::new(if towards_end { 300.0 } else { 100.0 }, 100.0); + assert!(!ps.iter().any(|p| p.distance(dropped) < 1.0), "the part ahead is dropped: {ps:?}"); + } +} + +/// A stroke that leaves a selected path and comes back to the same point adds a loop there; the +/// path stays closed and keeps its corners. +#[test] +fn a_stroke_back_to_where_it_started_adds_a_loop() { + let mut s = session(); + let id = rect(&mut s, 0.0, 0.0, 200.0, 100.0); + let before = path(&s, id).subpaths[0].anchors.len(); + let loop_pts = json!([[100, 0], [90, -15], [95, -35], [110, -38], [120, -20], [108, -8], [100, 0]]); + s.execute("path.freehand", &json!({"points": loop_pts, "redraw": {"id": id.0, "within": 4}})).unwrap(); + assert_eq!(paths(&s).len(), 1, "no new path"); + let sp = &path(&s, id).subpaths[0]; + assert!(sp.closed && sp.anchors.len() > before, "{sp:?}"); + let top = kurbo::Shape::bounding_box(&path(&s, id).to_bezpath()).y0; + assert!(top < -30.0, "the loop: top {top}"); + for corner in [(0.0, 0.0), (200.0, 0.0), (200.0, 100.0), (0.0, 100.0)] { + assert!(sp.anchors.iter().any(|a| near(a.p, Point::new(corner.0, corner.1))), "{corner:?} kept"); + } +} + +/// On a closed path the stroke replaces the way round it heads from its start, even when that is +/// the longer way: the shape doesn't flip to the other side as the stroke goes on. +#[test] +fn a_redraw_of_a_closed_path_goes_the_way_the_stroke_heads() { + let mut s = session(); + let id = rect(&mut s, 0.0, 0.0, 200.0, 100.0); + // From (20, 0) out to the left, round below the rectangle and up its right side to (180, 0). + let pts = json!([[20, 0], [10, -15], [-20, -10], [-25, 50], [-20, 120], [100, 125], [220, 120], [225, 50], [210, -10], [190, -12], [180, 0]]); + s.execute("path.freehand", &json!({"points": pts, "redraw": {"id": id.0, "within": 4}})).unwrap(); + assert_eq!(paths(&s).len(), 1); + let sp = &path(&s, id).subpaths[0]; + assert!(sp.closed); + let ps: Vec = sp.anchors.iter().map(|a| a.p).collect(); + // The rectangle's left, bottom and right sides went with the stroke; its top between 20 and + // 180 stays. + for corner in [(0.0, 0.0), (0.0, 100.0), (200.0, 100.0), (200.0, 0.0)] { + assert!(!ps.iter().any(|p| p.distance(Point::new(corner.0, corner.1)) < 1.0), "{corner:?} replaced: {ps:?}"); + } + let b = kurbo::Shape::bounding_box(&path(&s, id).to_bezpath()); + assert!(b.y1 > 115.0 && b.x0 < -15.0, "the stroke's way round: {b:?}"); +} + +/// A stroke lifted farther from the path than Edit selected paths within takes the path with it; +/// one lifted within that distance joins it again, its end bent smoothly onto it. +#[test] +fn a_stroke_lifted_beyond_the_edit_distance_takes_the_path_along() { + let mut s = session(); + let id = rect(&mut s, 0.0, 0.0, 200.0, 100.0); + // A hook out of the right side that ends 8 pt from it. + let hook = json!([[200, 50], [210, 40], [222, 38], [226, 46], [222, 56], [208, 58]]); + s.execute("path.freehand", &json!({"points": hook, "redraw": {"id": id.0, "within": 4}})).unwrap(); + let sp = &path(&s, id).subpaths[0]; + assert!(!sp.closed, "8 pt away with 4 pt to edit within: the shape opened"); + let ends = [sp.anchors.first().unwrap().p, sp.anchors.last().unwrap().p]; + assert!(ends.iter().any(|p| p.distance(Point::new(208.0, 58.0)) < 0.5), "it ends where the pen was lifted: {ends:?}"); +} + +/// A shape with a hole that opens keeps its outline running its own way, so the hole stays a hole. +#[test] +fn opening_a_shape_with_a_hole_keeps_the_hole() { + for heads_back in [false, true] { + let mut s = session(); + let outer = rect(&mut s, 0.0, 0.0, 200.0, 200.0); + let hole = rect(&mut s, 50.0, 50.0, 100.0, 100.0); + s.execute("select.set", &json!({"ids": [outer.0, hole.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = s.doc().unwrap().selection.objects[0]; + let member = |s: &Session, i: usize| s.doc().unwrap().doc.node(compound).unwrap().children().unwrap()[i].clone(); + let (outer_id, sign) = { + let m = member(&s, 0); + (m.id, m.path_data().unwrap().subpaths[0].signed_area().signum()) + }; + // A hook out of the top edge, heading one way or the other along it. + let dx = if heads_back { -1.0 } else { 1.0 }; + let hook: Vec<_> = (0..6).map(|i| json!([100.0 + dx * 6.0 * f64::from(i), -5.0 * f64::from(i)])).collect(); + s.execute("path.freehand", &json!({"points": hook, "redraw": {"id": outer_id.0, "within": 4}})).unwrap(); + let sp = member(&s, 0).path_data().unwrap().subpaths[0].clone(); + assert!(!sp.closed, "heads back {heads_back}: opened"); + assert_eq!(sp.signed_area().signum(), sign, "heads back {heads_back}: the outline runs its own way, the hole stays a hole"); + } +} + +/// A stroke across a shape from one point of its outline to another carves off the part it cuts +/// across, the lobe on that side, and keeps the rest, whichever way it is drawn. +#[test] +fn a_stroke_across_a_shape_carves_off_the_part_it_cuts() { + for reversed in [false, true] { + let mut s = session(); + // A wide shape with a lobe on top between x = 80 and x = 120. + let shape = json!([[0, 0], [80, 0], [80, -60], [120, -60], [120, 0], [300, 0], [300, 100], [0, 100]]); + let id = NodeId(s.execute("path.freehand", &json!({"points": shape, "closed": true, "fidelity": 0.01})).unwrap()["id"].as_u64().unwrap()); + // Across the lobe's base, a little inside the shape. + let mut cut = vec![json!([70, 0]), json!([85, 8]), json!([100, 10]), json!([115, 8]), json!([130, 0])]; + if reversed { + cut.reverse(); + } + s.execute("path.freehand", &json!({"points": cut, "redraw": {"id": id.0, "within": 4}})).unwrap(); + let sp = &path(&s, id).subpaths[0]; + assert!(sp.closed, "reversed {reversed}"); + let b = kurbo::Shape::bounding_box(&path(&s, id).to_bezpath()); + assert!(b.y0 > -20.0, "reversed {reversed}: the lobe (up to y = -60) is carved off: {b:?}"); + assert!(b.x1 > 295.0 && b.y1 > 95.0, "reversed {reversed}: the rest stays: {b:?}"); + } +} + +/// A stroke leaving an open path across it (no direction along it) drops the nearer, short side, +/// not most of the path. +#[test] +fn a_stroke_leaving_an_open_path_across_it_drops_the_side_it_is_near() { + let mut s = session(); + let id = line(&mut s, 100.0, 100.0, 300.0, 100.0); + // Straight up from x = 280, then bending towards the near end. + let up = json!([[280, 100], [280, 90], [281, 75], [284, 60], [290, 50]]); + s.execute("path.freehand", &json!({"points": up, "redraw": {"id": id.0, "within": 4}})).unwrap(); + let sp = &path(&s, id).subpaths[0]; + assert!(ends_at(sp, Point::new(100.0, 100.0), Point::new(290.0, 50.0), 0.5), "the long side stays: {sp:?}"); +} + +/// A stroke drawn over an open shape's open ends, from near one end to near the other, redraws +/// those ends along the stroke and closes the shape, whichever way it is drawn; the shape's body +/// between stays. +#[test] +fn a_stroke_over_an_open_shapes_ends_closes_it_along_the_stroke() { + for reversed in [false, true] { + let mut s = session(); + // A C open on the right: from the top right round the left to the bottom right. + let c: Vec<_> = (0..=30) + .map(|i| { + let a = (40.0 + 280.0 * f64::from(i) / 30.0).to_radians(); + json!([200.0 + 100.0 * a.cos(), 200.0 - 100.0 * a.sin()]) + }) + .collect(); + let id = NodeId(s.execute("path.freehand", &json!({"points": c, "fidelity": 0.5})).unwrap()["id"].as_u64().unwrap()); + let on = |deg: f64| { + let a = deg.to_radians(); + (200.0 + 100.0 * a.cos(), 200.0 - 100.0 * a.sin()) + }; + // From the C near its top end, out round the open side, back onto it near the bottom end. + let (a, b) = (on(60.0), on(300.0)); + let mut stroke = vec![json!([a.0, a.1]), json!([290.0, 150.0]), json!([315.0, 200.0]), json!([290.0, 250.0]), json!([b.0, b.1])]; + if reversed { + stroke.reverse(); + } + s.execute("path.freehand", &json!({"points": stroke, "redraw": {"id": id.0, "within": 4}})).unwrap(); + assert_eq!(paths(&s).len(), 1, "reversed {reversed}: no new path"); + let sp = &path(&s, id).subpaths[0]; + assert!(sp.closed, "reversed {reversed}: the shape closed"); + let bb = kurbo::Shape::bounding_box(&path(&s, id).to_bezpath()); + assert!(bb.x1 > 310.0 && bb.x0 < 105.0, "reversed {reversed}: closed along the stroke, the body kept: {bb:?}"); + // The old ends (at 40° and 320°) are gone. + for deg in [40.0, 320.0] { + let e = on(deg); + assert!(!sp.anchors.iter().any(|q| q.p.distance(Point::new(e.0, e.1)) < 1.0), "reversed {reversed}: the end at {deg}° is redrawn"); + } + } +} + +/// A stroke that starts and ends on an open path decides by the way it runs along the path at its +/// ends: where it starts it replaces the part it runs along, where it lands it joins the part it runs +/// into, an end that goes straight off or onto the path follows the other end, and when both do it +/// closes only round both pieces beyond. A stroke lifted away from the path ends there. The path is +/// an L whose bottom arm turns up and back over to a hook near the upright arm. +#[test] +fn a_redraw_on_an_open_path_follows_the_way_its_ends_run() { + // From the upright arm's top (100, 0) down, along the bottom, up the right side, back along the + // top to the hook, which ends at (160, 60). + let shape = [[100.0, 0.0], [100.0, 300.0], [400.0, 300.0], [400.0, 100.0], [160.0, 100.0], [160.0, 60.0]]; + // A stroke through `pts`, a point every 2 pt, as a hand draws it. + let dense = |pts: &[[f64; 2]]| { + let mut out = vec![json!(pts[0])]; + for w in pts.windows(2) { + let (a, b) = (Point::new(w[0][0], w[0][1]), Point::new(w[1][0], w[1][1])); + let n = (a.distance(b) / 2.0).ceil().max(1.0) as usize; + out.extend((1..=n).map(|i| { + let q = a.lerp(b, i as f64 / n as f64); + json!([q.x, q.y]) + })); + } + out + }; + let has = |sp: &vectorcraft_geom::SubPath, x: f64, y: f64| sp.anchors.iter().any(|a| a.p.distance(Point::new(x, y)) < 1.0); + // Over the loop above the path, from the top edge round to the left of the upright arm. + let over = [[250.0, 40.0], [200.0, -30.0], [100.0, -40.0], [40.0, 0.0]]; + // Each: its name, the stroke, and whether the path is closed and keeps the bottom right corner, + // the upright arm's top and the hook's end. + let cases = [ + // Runs along the top towards the hook, then up the upright arm: the hook goes, the end is + // left where the pen is lifted, on the arm, and the rest of the path stays. + ( + "towards the hook, landing up the arm", + vec![[250.0, 100.0], [165.0, 100.0], [130.0, 95.0], [100.0, 90.0], [100.0, 40.0]], + [false, true, true, false], + ), + // Runs along the top away from the hook, then lands running up the arm: the part between + // is replaced, both ends stay. + ( + "away from the hook, landing up the arm", + vec![[250.0, 100.0], [300.0, 100.0], [320.0, 60.0], [250.0, 30.0], [140.0, 40.0], [100.0, 90.0], [100.0, 60.0]], + [false, false, true, true], + ), + // Straight up off the top, over the arm's top, landing running down the arm: the arm's top and + // the hook go and the path closes round the rest. + ( + "straight off, landing down the arm", + [&[[250.0, 100.0]][..], &over, &[[40.0, 120.0], [85.0, 140.0], [100.0, 150.0], [100.0, 180.0]]].concat(), + [true, true, false, false], + ), + // Straight off and straight onto the arm, round both the arm's top and the hook: it closes. + ("straight off and on, round both", [&[[250.0, 100.0]][..], &over, &[[40.0, 150.0], [100.0, 150.0]]].concat(), [true, true, false, false]), + // The same loop carried on across the arm and lifted inside: the path ends there; the hook, + // the shorter side, goes. + ( + "across the arm, lifted away", + [&[[250.0, 100.0]][..], &over, &[[40.0, 150.0], [100.0, 150.0], [200.0, 160.0]]].concat(), + [false, true, true, false], + ), + ]; + for (name, stroke, [closed, body, top, hook]) in cases { + let mut s = session(); + let id = NodeId(s.execute("path.freehand", &json!({"points": shape, "fit": false})).unwrap()["id"].as_u64().unwrap()); + s.execute("path.freehand", &json!({"points": dense(&stroke), "redraw": {"id": id.0, "within": 12}})).unwrap(); + assert_eq!(paths(&s).len(), 1, "{name}: no new path"); + let sp = &path(&s, id).subpaths[0]; + assert_eq!(sp.closed, closed, "{name}: closed: {sp:?}"); + assert_eq!(has(sp, 400.0, 300.0), body, "{name}: the bottom right corner: {sp:?}"); + assert_eq!(has(sp, 100.0, 0.0), top, "{name}: the upright arm's top: {sp:?}"); + assert_eq!(has(sp, 160.0, 60.0), hook, "{name}: the hook's end: {sp:?}"); + } +} + +/// A stroke that starts on an open C's upper arm running towards its end, goes round the opening +/// and lands on the lower arm running back into the C closes it into a ring. +#[test] +fn a_stroke_run_over_both_arms_of_a_c_closes_it() { + let mut s = session(); + let on = |deg: f64| { + let a = deg.to_radians(); + json!([200.0 + 100.0 * a.cos(), 200.0 - 100.0 * a.sin()]) + }; + let c: Vec<_> = (0..=28).map(|i| on(40.0 + 10.0 * f64::from(i))).collect(); + let id = NodeId(s.execute("path.freehand", &json!({"points": c, "fidelity": 0.5})).unwrap()["id"].as_u64().unwrap()); + let mut stroke: Vec<_> = (0..=8).map(|i| on(56.0 - 2.0 * f64::from(i))).collect(); + stroke.extend([json!([300.0, 160.0]), json!([310.0, 200.0]), json!([300.0, 240.0])]); + stroke.extend((0..=8).map(|i| on(324.0 - 2.0 * f64::from(i)))); + s.execute("path.freehand", &json!({"points": stroke, "redraw": {"id": id.0, "within": 4}})).unwrap(); + let sp = &path(&s, id).subpaths[0]; + assert!(sp.closed, "a ring: {sp:?}"); + let bb = kurbo::Shape::bounding_box(&path(&s, id).to_bezpath()); + assert!(bb.x0 < 105.0 && bb.x1 > 300.0, "the C's body and the stroke: {bb:?}"); +} + +/// A tall bump redrawn over most of an open line replaces that part: the ends beyond it stay and +/// the line stays open. +#[test] +fn a_tall_redraw_over_most_of_an_open_line_keeps_its_ends() { + for reversed in [false, true] { + let mut s = session(); + let id = line(&mut s, 100.0, 300.0, 700.0, 300.0); + let mut bump = + vec![json!([200, 300]), json!([250, 226]), json!([325, 148]), json!([400, 120]), json!([475, 148]), json!([550, 226]), json!([600, 300])]; + if reversed { + bump.reverse(); + } + s.execute("path.freehand", &json!({"points": bump, "redraw": {"id": id.0, "within": 12}})).unwrap(); + let sp = &path(&s, id).subpaths[0]; + assert!(!sp.closed, "reversed {reversed}: still open"); + assert!(ends_at(sp, Point::new(100.0, 300.0), Point::new(700.0, 300.0), 1e-6), "reversed {reversed}: both ends stay: {sp:?}"); + assert!(kurbo::Shape::bounding_box(&path(&s, id).to_bezpath()).y0 < 135.0, "reversed {reversed}: the bump"); + } +} + +/// A tall arch over one long side of a thin closed shape replaces that side: the result is the +/// bigger of the two shapes the stroke could make, not the arch alone. +#[test] +fn a_tall_arch_over_a_thin_shapes_side_keeps_the_shape() { + for reversed in [false, true] { + let mut s = session(); + let id = rect(&mut s, 100.0, 300.0, 600.0, 60.0); + let mut arch = + vec![json!([130, 300]), json!([197, 216]), json!([265, 144]), json!([400, 80]), json!([535, 144]), json!([603, 216]), json!([670, 300])]; + if reversed { + arch.reverse(); + } + s.execute("path.freehand", &json!({"points": arch, "redraw": {"id": id.0, "within": 12}})).unwrap(); + let sp = &path(&s, id).subpaths[0]; + assert!(sp.closed, "reversed {reversed}"); + for corner in [(100.0, 300.0), (700.0, 300.0), (700.0, 360.0), (100.0, 360.0)] { + assert!(sp.anchors.iter().any(|a| near(a.p, Point::new(corner.0, corner.1))), "reversed {reversed}: {corner:?} kept: {sp:?}"); + } + assert!(kurbo::Shape::bounding_box(&path(&s, id).to_bezpath()).y0 < 95.0, "reversed {reversed}: the arch"); + } +} + +/// A stroke that comes back near the path, within Edit selected paths within but not on it, joins +/// it again: the shape stays one closed path, and the stroke's end bends onto it, so no anchor +/// lies off the stroke's way back. +#[test] +fn a_stroke_back_near_the_path_joins_it_smoothly() { + let mut s = session(); + let id = rect(&mut s, 0.0, 0.0, 200.0, 100.0); + // A bump out of the top edge that comes back down to 10 pt above it. + let bump = json!([[40, 0], [45, -20], [60, -40], [80, -45], [100, -40], [115, -25], [120, -10]]); + s.execute("path.freehand", &json!({"points": bump, "redraw": {"id": id.0, "within": 20}})).unwrap(); + assert_eq!(paths(&s).len(), 1); + let sp = &path(&s, id).subpaths[0]; + assert!(sp.closed, "joined again: still closed"); + let top = kurbo::Shape::bounding_box(&path(&s, id).to_bezpath()).y0; + assert!(top < -35.0, "the bump: top {top}"); +} + /// With the Pencil's Live preview off, nothing is added to the document while a filled stroke is /// drawn; the release draws the path with its fill, as one undo step. #[test] diff --git a/crates/engine/src/tests/interaction_commands.rs b/crates/engine/src/tests/interaction_commands.rs new file mode 100644 index 0000000000..d0d12cce94 --- /dev/null +++ b/crates/engine/src/tests/interaction_commands.rs @@ -0,0 +1,829 @@ +//! A command run from outside the tool (a panel, a menu item, an automation client) while a tool's drag is +//! in progress is a step of its own, before the drag's: the drag's next preview, its release and +//! Escape keep the command's edit, and the release still draws what the drag drew, with Real-time +//! Drawing on and off. + +use serde_json::json; +use vectorcraft_geom::Rect; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + +use crate::*; + +/// The view the gestures run in: page coordinates, with Smart Guides off so nothing snaps. +fn view() -> ViewInfo { + ViewInfo { smart_guides: false, ..ViewInfo::default() } +} + +/// Feed the pointer event `(kind, x, y)` to the active tool. +fn pointer(s: &mut Session, kind: PointerKind, x: f64, y: f64) { + s.pointer(&PointerEvent::new(kind, x, y), view()).unwrap(); +} + +/// A new 400 × 400 pt document with Real-time Drawing `real_time`, holding one 20 × 20 pt rectangle +/// (returned), nothing selected, and the Rectangle tool chosen. +fn session(real_time: bool) -> (Session, NodeId) { + let mut s = Session::new(); + s.prefs.real_time_drawing = real_time; + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let other = s.doc().unwrap().selection.objects[0]; + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("rectangle", view()).unwrap(); + (s, other) +} + +fn visible(s: &Session, id: NodeId) -> bool { + s.doc().unwrap().doc.node(id).expect("the object is in the document").visible +} + +/// The objects of the document's first layer. +fn objects(s: &Session) -> usize { + s.doc().unwrap().doc.layers[0].children().map_or(0, Vec::len) +} + +/// The commands journaled from entry `start` on. +fn journaled(s: &Session, start: usize) -> Vec { + s.journal.iter().skip(start).map(|(id, _)| id.clone()).collect() +} + +#[test] +fn a_command_during_a_drag_is_a_step_of_its_own_before_the_drag() { + for real_time in [true, false] { + let (mut s, other) = session(real_time); + let (steps, start) = (s.doc().unwrap().history.undo.len(), s.journal.len()); + pointer(&mut s, PointerKind::Down, 100.0, 100.0); + pointer(&mut s, PointerKind::Drag, 150.0, 150.0); + s.execute("object.hide", &json!({"ids": [other.0]})).unwrap(); + assert!(!visible(&s, other), "real time {real_time}: the command hides the object at once"); + pointer(&mut s, PointerKind::Drag, 200.0, 180.0); + assert!(!visible(&s, other), "real time {real_time}: the drag's next preview keeps the command's edit"); + pointer(&mut s, PointerKind::Up, 200.0, 180.0); + assert!(!visible(&s, other), "real time {real_time}: the release keeps the command's edit"); + assert_eq!(objects(&s), 2, "real time {real_time}: the release draws the rectangle"); + let drawn = s.doc().unwrap().selection.objects[0]; + assert_ne!(drawn, other); + assert_eq!(s.doc().unwrap().doc.bounds_of(&[drawn], false), Some(Rect::new(100.0, 100.0, 200.0, 180.0)), "real time {real_time}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "real time {real_time}: the command and the drag are a step each"); + assert_eq!(journaled(&s, start), ["object.hide", "shape.rectangle"], "real time {real_time}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(objects(&s), 1, "real time {real_time}: Undo takes back the drawn rectangle"); + assert!(!visible(&s, other), "real time {real_time}: and leaves the command's edit"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(visible(&s, other), "real time {real_time}: the next Undo takes back the command's edit"); + } +} + +#[test] +fn escape_after_a_command_during_a_drag_keeps_the_command() { + for real_time in [true, false] { + let (mut s, other) = session(real_time); + let steps = s.doc().unwrap().history.undo.len(); + pointer(&mut s, PointerKind::Down, 100.0, 100.0); + pointer(&mut s, PointerKind::Drag, 150.0, 150.0); + s.execute("object.hide", &json!({"ids": [other.0]})).unwrap(); + s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap(); + pointer(&mut s, PointerKind::Up, 150.0, 150.0); + assert!(!visible(&s, other), "real time {real_time}: Escape takes back only the drag"); + assert_eq!(objects(&s), 1, "real time {real_time}: nothing is drawn"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "real time {real_time}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(visible(&s, other), "real time {real_time}"); + } +} + +/// Every object of the first layer but `other`, as the document has it. +fn others(s: &Session, other: NodeId) -> Vec { + let d = &s.doc().unwrap().doc; + d.layers[0].children().map_or_else(Vec::new, |c| c.iter().filter(|n| n.id != other).map(|n| (**n).clone()).collect()) +} + +/// A new 400 × 400 pt document with Real-time Drawing `real_time`, holding a 40 × 40 pt square at +/// (100, 100) and a 20 × 20 pt one at (10, 10) → the session, the larger square (selected) and the +/// smaller one. +fn two_squares(real_time: bool) -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + s.prefs.real_time_drawing = real_time; + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let other = s.doc().unwrap().selection.objects[0]; + s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 40, "height": 40})).unwrap(); + let target = s.doc().unwrap().selection.objects[0]; + (s, target, other) +} + +/// A press at the first point of `pts`, drags to the others and a release at the last, with +/// `mid` run after the first drag. +fn drag_with(s: &mut Session, pts: &[(f64, f64)], mid: impl FnOnce(&mut Session)) { + let (&(x0, y0), rest) = pts.split_first().expect("a press"); + pointer(s, PointerKind::Down, x0, y0); + let mut mid = Some(mid); + for &(x, y) in rest { + pointer(s, PointerKind::Drag, x, y); + if let Some(f) = mid.take() { + f(s); + } + } + let &(x, y) = pts.last().expect("a release"); + pointer(s, PointerKind::Up, x, y); +} + +/// Is `id` filled red? +fn red(s: &Session, id: NodeId) -> bool { + s.doc().unwrap().doc.node(id).and_then(|n| n.appearance.fill_paint().color()).is_some_and(|c| c.to_hex() == "#ff0000") +} + +/// The Selection tool's move, the Scale and Rotate tools and the Pen, each with a command that +/// fills another object red during the drag: the release keeps both, as two undo steps, and Undo +/// takes back the drag first. +#[test] +fn the_move_scale_rotate_and_pen_drags_keep_a_command_run_during_them() { + let drags: [(&str, &[(f64, f64)]); 4] = [ + ("selection", &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)]), + ("scale", &[(150.0, 150.0), (170.0, 170.0), (190.0, 190.0)]), + ("rotate", &[(160.0, 120.0), (150.0, 150.0), (120.0, 160.0)]), + ("pen", &[(300.0, 300.0), (320.0, 300.0), (350.0, 320.0)]), + ]; + for (tool, pts) in drags { + for real_time in [true, false] { + let at = format!("{tool}, real time {real_time}"); + let (mut s, _, other) = two_squares(real_time); + if tool == "pen" { + s.execute("select.none", &json!({})).unwrap(); + } + s.select_tool(tool, view()).unwrap(); + let (before, steps) = (others(&s, other), s.doc().unwrap().history.undo.len()); + drag_with(&mut s, pts, |s| { + s.execute("paint.setFill", &json!({"ids": [other.0], "color": "#ff0000"})).unwrap(); + }); + assert!(!s.in_interaction(), "{at}"); + assert!(red(&s, other), "{at}: the release keeps the command's edit"); + assert_ne!(others(&s, other), before, "{at}: the release keeps the drag's edit"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "{at}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(others(&s, other), before, "{at}: Undo takes back the drag"); + assert!(red(&s, other), "{at}: and leaves the command's edit"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!red(&s, other), "{at}: the next Undo takes back the command's edit"); + } + } +} + +/// A command that changes the object being moved: the move applies to the changed object. +#[test] +fn a_move_drag_moves_the_object_as_a_command_during_it_changed_it() { + for real_time in [true, false] { + let (mut s, target, _) = two_squares(real_time); + s.select_tool("selection", view()).unwrap(); + let fill = |s: &Session| s.doc().unwrap().doc.node(target).unwrap().appearance.fill_paint().color().map(|c| c.to_hex()); + let was = fill(&s); + drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| { + s.execute("paint.setFill", &json!({"ids": [target.0], "color": "#ff0000"})).unwrap(); + }); + let moved = s.doc().unwrap().doc.bounds_of(&[target], false); + assert_eq!(moved, Some(Rect::new(150.0, 130.0, 190.0, 170.0)), "real time {real_time}"); + assert_eq!(fill(&s).as_deref(), Some("#ff0000"), "real time {real_time}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.bounds_of(&[target], false), Some(Rect::new(100.0, 100.0, 140.0, 140.0)), "real time {real_time}"); + assert_eq!(fill(&s).as_deref(), Some("#ff0000"), "real time {real_time}: the fill is a step of its own"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(fill(&s), was, "real time {real_time}"); + } +} + +/// A command that deletes the object being moved: the drag goes on and ends without an edit of +/// its own, on release and on Escape, and the deletion stays. +#[test] +fn a_move_drag_of_an_object_a_command_deleted_ends_without_an_edit() { + for (real_time, escape) in [(true, false), (false, false), (true, true), (false, true)] { + let at = format!("real time {real_time}, Escape {escape}"); + let (mut s, target, other) = two_squares(real_time); + s.select_tool("selection", view()).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + pointer(&mut s, PointerKind::Down, 120.0, 120.0); + pointer(&mut s, PointerKind::Drag, 140.0, 130.0); + s.execute("edit.clear", &json!({"ids": [target.0]})).unwrap(); + assert!(s.doc().unwrap().doc.node(target).is_none(), "{at}"); + pointer(&mut s, PointerKind::Drag, 170.0, 150.0); + if escape { + s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap(); + } + pointer(&mut s, PointerKind::Up, 170.0, 150.0); + assert!(!s.in_interaction(), "{at}"); + assert!(s.doc().unwrap().doc.node(target).is_none(), "{at}: the deletion stays"); + assert_eq!(others(&s, other), [], "{at}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "{at}: only the deletion is a step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.bounds_of(&[target], false), Some(Rect::new(100.0, 100.0, 140.0, 140.0)), "{at}"); + } +} + +/// A command that hides or locks the object being moved: the object stays where it was and +/// unselected, and the drag ends without an edit of its own. +#[test] +fn a_move_drag_of_an_object_a_command_hid_or_locked_leaves_it_alone() { + for command in ["object.hide", "object.lock"] { + for real_time in [true, false] { + let at = format!("{command}, real time {real_time}"); + let (mut s, target, _) = two_squares(real_time); + s.select_tool("selection", view()).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| { + s.execute(command, &json!({"ids": [target.0]})).unwrap(); + }); + assert!(!s.in_interaction(), "{at}"); + assert_eq!(s.doc().unwrap().doc.bounds_of(&[target], false), Some(Rect::new(100.0, 100.0, 140.0, 140.0)), "{at}: not moved"); + assert!(!s.doc().unwrap().selection.objects.contains(&target), "{at}: not selected"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "{at}: only the command is a step"); + } + } +} + +/// The commands that end a drag first still do: Undo during a drag keeps the drag as a step and +/// takes it back, and `command.batch` and `swatch.renameGroup` keep it as a step before their own. +#[test] +fn undo_and_a_batch_during_a_drag_still_keep_the_drag_first() { + for real_time in [true, false] { + let (mut s, target, other) = two_squares(real_time); + s.select_tool("selection", view()).unwrap(); + pointer(&mut s, PointerKind::Down, 120.0, 120.0); + pointer(&mut s, PointerKind::Drag, 170.0, 150.0); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!s.in_interaction(), "real time {real_time}"); + assert_eq!(s.doc().unwrap().doc.bounds_of(&[target], false), Some(Rect::new(100.0, 100.0, 140.0, 140.0)), "real time {real_time}"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.bounds_of(&[target], false), Some(Rect::new(150.0, 130.0, 190.0, 170.0)), "real time {real_time}"); + pointer(&mut s, PointerKind::Up, 170.0, 150.0); + + let (mut s, target, other2) = two_squares(real_time); + assert_eq!(other, other2); + s.select_tool("selection", view()).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + pointer(&mut s, PointerKind::Down, 120.0, 120.0); + pointer(&mut s, PointerKind::Drag, 170.0, 150.0); + s.execute("command.batch", &json!({"commands": [{"command": "object.hide", "params": {"ids": [other.0]}}]})).unwrap(); + assert!(!s.in_interaction(), "real time {real_time}: the batch keeps the drag first"); + pointer(&mut s, PointerKind::Up, 170.0, 150.0); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "real time {real_time}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(visible(&s, other), "real time {real_time}: Undo takes back the batch first"); + assert_eq!(s.doc().unwrap().doc.bounds_of(&[target], false), Some(Rect::new(150.0, 130.0, 190.0, 170.0)), "real time {real_time}"); + + // A color group renamed during the drag keeps the drag as a step before the rename. + let (mut s, target, _) = two_squares(real_time); + s.select_tool("selection", view()).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + pointer(&mut s, PointerKind::Down, 120.0, 120.0); + pointer(&mut s, PointerKind::Drag, 170.0, 150.0); + s.execute("swatch.renameGroup", &json!({"group": "Brights", "name": "Vivid"})).unwrap(); + assert!(!s.in_interaction(), "real time {real_time}: the rename keeps the drag first"); + pointer(&mut s, PointerKind::Up, 170.0, 150.0); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "real time {real_time}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.swatch_groups.iter().any(|g| g.name == "Brights"), "real time {real_time}: Undo takes back the rename"); + assert_eq!(s.doc().unwrap().doc.bounds_of(&[target], false), Some(Rect::new(150.0, 130.0, 190.0, 170.0)), "real time {real_time}"); + } +} + +/// A copy made with `object.transform` during an Alt-drag runs inside the drag, with Real-time +/// Drawing on and off: the release records one step that holds both. +#[test] +fn a_copy_during_an_alt_drag_is_part_of_the_drag() { + for real_time in [true, false] { + let (mut s, target, _) = two_squares(real_time); + s.select_tool("selection", view()).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + let alt = Mods { alt: true, ..Mods::default() }; + for (kind, x, y) in [(PointerKind::Down, 120.0, 120.0), (PointerKind::Drag, 170.0, 150.0)] { + s.pointer(&PointerEvent::new(kind, x, y).with_mods(alt), view()).unwrap(); + } + s.execute("object.transform", &json!({"matrix": [1, 0, 0, 1, 0, 60], "copy": true, "ids": [target.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 170.0, 150.0).with_mods(alt), view()).unwrap(); + assert!(!s.in_interaction(), "real time {real_time}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "real time {real_time}: one step for the drag and the copy"); + + // With Alt let go during the drag, the drag moves again, and the copy is a step of its own. + let (mut s, target, _) = two_squares(real_time); + s.select_tool("selection", view()).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + s.pointer(&PointerEvent::new(PointerKind::Down, 120.0, 120.0).with_mods(alt), view()).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 150.0, 140.0).with_mods(alt), view()).unwrap(); + pointer(&mut s, PointerKind::Drag, 170.0, 150.0); + s.execute("object.transform", &json!({"matrix": [1, 0, 0, 1, 0, 60], "copy": true, "ids": [target.0]})).unwrap(); + pointer(&mut s, PointerKind::Up, 170.0, 150.0); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "real time {real_time}: the copy and the move"); + } +} + +/// A command that changes only the current layer during a drag keeps its change through Escape. +#[test] +fn escape_keeps_a_current_layer_set_during_a_drag() { + for real_time in [true, false] { + let (mut s, _) = session(real_time); + let first = s.doc().unwrap().active_layer; + let second = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + let first = first.expect("a current layer"); + s.execute("layer.setCurrent", &json!({"id": first.0})).unwrap(); + pointer(&mut s, PointerKind::Down, 100.0, 100.0); + pointer(&mut s, PointerKind::Drag, 150.0, 150.0); + s.execute("layer.setCurrent", &json!({"id": second.0})).unwrap(); + s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap(); + pointer(&mut s, PointerKind::Up, 150.0, 150.0); + assert_eq!(s.doc().unwrap().active_layer, Some(second), "real time {real_time}"); + } +} + +/// With Real-time Drawing on, the drag's preview is on show again right after the command. +#[test] +fn the_drag_preview_shows_again_after_the_command() { + let (mut s, other) = session(true); + pointer(&mut s, PointerKind::Down, 100.0, 100.0); + pointer(&mut s, PointerKind::Drag, 150.0, 150.0); + assert_eq!(objects(&s), 2, "the preview draws the rectangle"); + s.execute("object.hide", &json!({"ids": [other.0]})).unwrap(); + assert_eq!(objects(&s), 2, "the preview is on show after the command"); + s.execute("object.showAll", &json!({})).unwrap(); + assert_eq!(objects(&s), 2, "and after a second one"); + assert!(visible(&s, other)); + assert!(s.in_interaction()); + pointer(&mut s, PointerKind::Up, 150.0, 150.0); + assert_eq!(objects(&s), 2); + assert!(visible(&s, other)); +} + +/// A command that changes the selection during a move drag (Select All, Deselect, a duplicate) +/// leaves the drag moving the object it began with. +#[test] +fn a_selection_made_during_a_move_drag_leaves_the_drag_moving_its_object() { + for command in ["select.all", "select.none", "edit.duplicate"] { + for real_time in [true, false] { + let at = format!("{command}, real time {real_time}"); + let (mut s, target, other) = two_squares(real_time); + s.select_tool("selection", view()).unwrap(); + drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| { + s.execute(command, &json!({})).unwrap(); + }); + let d = &s.doc().unwrap().doc; + assert_eq!(d.bounds_of(&[target], false), Some(Rect::new(150.0, 130.0, 190.0, 170.0)), "{at}: the drag moves its object"); + assert_eq!(d.bounds_of(&[other], false), Some(Rect::new(10.0, 10.0, 30.0, 30.0)), "{at}: and nothing else"); + if command == "edit.duplicate" { + let copies = others(&s, other).into_iter().filter(|n| n.id != target).map(|n| n.id).collect::>(); + assert_eq!(copies.len(), 1, "{at}"); + assert_eq!(d.bounds_of(&copies, false), Some(Rect::new(100.0, 100.0, 140.0, 140.0)), "{at}: the copy stays where it was made"); + } + } + } +} + +/// A command that selects another object during a move drag: the drag's object stays selected, +/// and the fill and stroke proxies keep showing its paints. +#[test] +fn a_selection_made_during_a_move_drag_leaves_the_paints_of_the_drag_object() { + for real_time in [true, false] { + let at = format!("real time {real_time}"); + let (mut s, target, other) = two_squares(real_time); + s.execute("paint.setFill", &json!({"ids": [target.0], "color": "#ff0000"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [other.0], "color": "#0000ff"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [target.0]})).unwrap(); + s.select_tool("selection", view()).unwrap(); + let fill = |s: &Session| s.paint.fill.color().map(|c| c.to_hex()); + assert_eq!(fill(&s).as_deref(), Some("#ff0000"), "{at}"); + pointer(&mut s, PointerKind::Down, 120.0, 120.0); + pointer(&mut s, PointerKind::Drag, 140.0, 130.0); + s.execute("select.set", &json!({"ids": [other.0]})).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects, [target], "{at}"); + assert_eq!(fill(&s).as_deref(), Some("#ff0000"), "{at}: after the command"); + pointer(&mut s, PointerKind::Drag, 170.0, 150.0); + pointer(&mut s, PointerKind::Up, 170.0, 150.0); + assert_eq!(s.doc().unwrap().selection.objects, [target], "{at}"); + assert_eq!(fill(&s).as_deref(), Some("#ff0000"), "{at}: after the release"); + } +} + +/// Replay the journal of `s` from `start` on `replayed`. +fn replay_from(s: &Session, start: usize, replayed: &mut Session) { + for (id, p) in s.journal.iter().skip(start) { + replayed.replay(id, p).unwrap(); + } +} + +/// The journal of a move drag with a selection command run during it replays as the drag went: +/// the drag moves its own object, not the one the command selected. +#[test] +fn a_move_drag_after_a_selection_command_replays_on_its_own_object() { + for real_time in [true, false] { + let at = format!("real time {real_time}"); + let (mut s, target, other) = two_squares(real_time); + s.select_tool("selection", view()).unwrap(); + let start = s.journal.len(); + drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| { + s.execute("select.set", &json!({"ids": [other.0]})).unwrap(); + }); + let bounds = |s: &Session| { + let d = &s.doc().unwrap().doc; + (d.bounds_of(&[target], false), d.bounds_of(&[other], false)) + }; + assert_eq!(bounds(&s), (Some(Rect::new(150.0, 130.0, 190.0, 170.0)), Some(Rect::new(10.0, 10.0, 30.0, 30.0))), "{at}"); + let (mut replayed, _, _) = two_squares(real_time); + replay_from(&s, start, &mut replayed); + assert_eq!(bounds(&replayed), bounds(&s), "{at}: {:?}", journaled(&s, start)); + assert_eq!(replayed.doc().unwrap().selection.objects, s.doc().unwrap().selection.objects, "{at}"); + assert_eq!(replayed.doc().unwrap().active_layer, s.doc().unwrap().active_layer, "{at}"); + } +} + +/// Find Objects with `select` during a drag is a step of its own, as it is journaled: it finds and +/// selects only the objects outside the drag's preview, as its replay before the drag does. +#[test] +fn find_objects_with_select_during_a_drag_skips_the_drag_preview() { + for real_time in [true, false] { + let at = format!("real time {real_time}"); + let (mut s, other) = session(real_time); + let start = s.journal.len(); + let find = json!({"intersects": [0, 0, 400, 400], "select": true}); + pointer(&mut s, PointerKind::Down, 100.0, 100.0); + pointer(&mut s, PointerKind::Drag, 150.0, 150.0); + let r = s.execute("document.find", &find).unwrap(); + assert_eq!(r["total"], 1, "{at}: {r}"); + assert_eq!(r["matches"][0]["id"], other.0, "{at}: {r}"); + pointer(&mut s, PointerKind::Up, 200.0, 180.0); + assert_eq!(objects(&s), 2, "{at}: the release draws the rectangle"); + // The drag's own selection is journaled after the find, so the release replays on it. + assert_eq!(journaled(&s, start), ["document.find", "select.set", "shape.rectangle"], "{at}"); + let (mut replayed, _) = session(real_time); + replay_from(&s, start, &mut replayed); + assert_eq!(objects(&replayed), 2, "{at}"); + assert_eq!(replayed.doc().unwrap().selection.objects, s.doc().unwrap().selection.objects, "{at}"); + } +} + +/// A square on a second layer selected with a ruler guide, and a square on the first layer → +/// the session (with Real-time Drawing `real_time`) and the square on the first layer. +fn square_and_guide(real_time: bool) -> (Session, NodeId) { + let mut s = Session::new(); + s.prefs.real_time_drawing = real_time; + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let other = s.doc().unwrap().selection.objects[0]; + s.execute("layer.new", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 40, "height": 40})).unwrap(); + let target = s.doc().unwrap().selection.objects[0]; + s.execute("guide.add", &json!({"vertical": true, "pos": 300})).unwrap(); + s.execute("select.set", &json!({"ids": [target.0]})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + (s, other) +} + +/// The journal of a move drag of a square and a ruler guide, with a command during it that +/// selects an object on another layer, replays with the drag's selection, guide included, with +/// the layer the command made current and with the Layers panel rows the command left highlighted. +#[test] +fn a_move_drag_of_a_guide_after_a_selection_command_replays_its_selection_and_layer() { + for real_time in [true, false] { + let at = format!("real time {real_time}"); + let (mut s, other) = square_and_guide(real_time); + s.select_tool("selection", view()).unwrap(); + let start = s.journal.len(); + drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| { + s.execute("select.set", &json!({"ids": [other.0]})).unwrap(); + }); + let (mut replayed, _) = square_and_guide(real_time); + replay_from(&s, start, &mut replayed); + let state = |s: &mut Session| { + let d = s.doc().unwrap(); + let state = ( + d.selection.objects.clone(), + d.selection.guides.clone(), + d.active_layer, + d.highlighted_rows(), + d.doc.bounds_of(&d.selection.objects, false), + ); + (state, s.execute("guide.list", &json!({})).unwrap()) + }; + assert_eq!(state(&mut replayed), state(&mut s), "{at}: {:?}", journaled(&s, start)); + } +} + +/// The journal of a move drag of a targeted square, with a command during it that selects another +/// square, replays with the square targeted, as the drag leaves it. +#[test] +fn a_move_drag_of_a_targeted_object_after_a_selection_command_replays_its_target() { + for real_time in [true, false] { + let at = format!("real time {real_time}"); + let setup = || { + let (mut s, target, other) = two_squares(real_time); + s.execute("layer.target", &json!({"id": target.0})).unwrap(); + s.select_tool("selection", view()).unwrap(); + (s, other) + }; + let (mut s, other) = setup(); + let start = s.journal.len(); + drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| { + s.execute("select.set", &json!({"ids": [other.0]})).unwrap(); + }); + let (mut replayed, _) = setup(); + replay_from(&s, start, &mut replayed); + let state = |s: &Session| { + let d = s.doc().unwrap(); + (d.selection.objects.clone(), d.selection.target, d.doc.bounds_of(&d.selection.objects, false)) + }; + assert_eq!(state(&replayed), state(&s), "{at}: {:?}", journaled(&s, start)); + } +} + +/// The journal of a move drag of a targeted square and a ruler guide, with a command during it +/// that selects another square, replays with the square targeted and the guide selected. +#[test] +fn a_move_drag_of_a_targeted_object_and_a_guide_after_a_selection_command_replays_both() { + for real_time in [true, false] { + let at = format!("real time {real_time}"); + let setup = || { + let (mut s, target, other) = two_squares(real_time); + s.execute("guide.add", &json!({"vertical": true, "pos": 300})).unwrap(); + s.execute("layer.target", &json!({"id": target.0})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + s.select_tool("selection", view()).unwrap(); + (s, target, other) + }; + let (mut s, target, other) = setup(); + let start = s.journal.len(); + drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| { + s.execute("select.set", &json!({"ids": [other.0]})).unwrap(); + }); + let state = |s: &mut Session| { + let d = s.doc().unwrap(); + let state = (d.selection.objects.clone(), d.selection.target, d.selection.guides.clone(), d.doc.bounds_of(&d.selection.objects, false)); + (state, s.execute("guide.list", &json!({})).unwrap()) + }; + let live = state(&mut s); + assert_eq!((live.0.1, live.0.2.len()), (Some(target), 1), "{at}: the drag leaves the square targeted and the guide selected"); + let (mut replayed, _, _) = setup(); + replay_from(&s, start, &mut replayed); + assert_eq!(state(&mut replayed), live, "{at}: {:?}", journaled(&s, start)); + } +} + +/// The journal of a move drag of a path with every anchor selected as anchor points, with a +/// command during it that selects another square, replays with those anchors selected. +#[test] +fn a_move_drag_of_every_anchor_of_a_path_after_a_selection_command_replays_its_anchors() { + for real_time in [true, false] { + let at = format!("real time {real_time}"); + let setup = || { + let (mut s, target, other) = two_squares(real_time); + s.execute("select.set", &json!({"ids": [target.0]})).unwrap(); + s.execute("select.anchors", &json!({"id": target.0, "anchors": [[0, 0]], "mode": "add"})).unwrap(); + s.select_tool("selection", view()).unwrap(); + (s, target, other) + }; + let (mut s, target, other) = setup(); + let every = s.doc().unwrap().selection.anchors.get(&target).cloned(); + assert!(every.as_ref().is_some_and(|a| a.len() > 1), "{at}: {every:?}"); + let start = s.journal.len(); + drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| { + s.execute("select.set", &json!({"ids": [other.0]})).unwrap(); + }); + let state = |s: &Session| { + let d = s.doc().unwrap(); + (d.selection.objects.clone(), d.selection.anchors.clone(), d.doc.bounds_of(&d.selection.objects, false)) + }; + assert_eq!(state(&s).1.get(&target), every.as_ref(), "{at}: the drag leaves every anchor selected as anchors"); + let (mut replayed, _, _) = setup(); + replay_from(&s, start, &mut replayed); + assert_eq!(state(&replayed), state(&s), "{at}: {:?}", journaled(&s, start)); + } +} + +/// The journal of a move drag of a targeted layer's art, with a duplicate made on that layer +/// during it, replays with the drag moving its own objects, not the duplicates. +#[test] +fn a_move_drag_of_a_targeted_layer_after_a_duplicate_replays_its_objects() { + for real_time in [true, false] { + let at = format!("real time {real_time}"); + let setup = || { + let (mut s, _, _) = two_squares(real_time); + let layer = s.doc().unwrap().doc.layers[0].id; + s.execute("layer.target", &json!({"id": layer.0})).unwrap(); + s.select_tool("selection", view()).unwrap(); + s + }; + let mut s = setup(); + let start = s.journal.len(); + drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| { + s.execute("edit.duplicate", &json!({})).unwrap(); + }); + let mut replayed = setup(); + replay_from(&s, start, &mut replayed); + let state = |s: &Session| { + let d = s.doc().unwrap(); + (d.selection.objects.clone(), d.doc.bounds_of(&d.selection.objects, false), objects(s)) + }; + assert_eq!(state(&replayed), state(&s), "{at}: {:?}", journaled(&s, start)); + } +} + +/// A selected user slice and a square → the session (with Real-time Drawing `real_time`), the +/// slice and the square. +fn slice_and_square(real_time: bool) -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + s.prefs.real_time_drawing = real_time; + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let other = s.doc().unwrap().selection.objects[0]; + let slice = s.execute("object.slice.create", &json!({"x": 200, "y": 200, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.slice.select", &json!({"slices": [slice]})).unwrap(); + (s, NodeId(slice), other) +} + +/// The journal of a Slice Selection drag, with a command during it that selects an object, +/// replays with the slice selected, as the drag leaves it. +#[test] +fn a_slice_drag_after_a_selection_command_replays_its_slice_selection() { + for real_time in [true, false] { + let at = format!("real time {real_time}"); + let (mut s, slice, other) = slice_and_square(real_time); + s.select_tool("sliceSelection", view()).unwrap(); + let start = s.journal.len(); + drag_with(&mut s, &[(220.0, 220.0), (230.0, 230.0), (240.0, 240.0)], |s| { + s.execute("select.set", &json!({"ids": [other.0]})).unwrap(); + }); + assert_eq!(s.doc().unwrap().selection.slices, [slice], "{at}"); + let (mut replayed, _, _) = slice_and_square(real_time); + replay_from(&s, start, &mut replayed); + let state = |s: &Session| { + let sel = &s.doc().unwrap().selection; + (sel.objects.clone(), sel.slices.clone()) + }; + assert_eq!(state(&replayed), state(&s), "{at}: {:?}", journaled(&s, start)); + } +} + +/// A Warp stroke over two selected squares, with a command that deletes one of them during the +/// stroke: the release still warps the other square, and the stroke's journal entry names it. +#[test] +fn a_warp_stroke_over_an_object_a_command_deleted_still_warps_the_others() { + for real_time in [true, false] { + let at = format!("real time {real_time}"); + let (mut s, target, other) = two_squares(real_time); + s.execute("select.all", &json!({})).unwrap(); + s.select_tool("warp", view()).unwrap(); + let before = s.doc().unwrap().doc.node(target).cloned(); + let steps = s.doc().unwrap().history.undo.len(); + pointer(&mut s, PointerKind::Down, 120.0, 120.0); + pointer(&mut s, PointerKind::Drag, 135.0, 125.0); + let r = s.execute("edit.clear", &json!({"ids": [other.0]})).unwrap(); + assert!(r.get("warning").is_none(), "{at}: {r}"); + pointer(&mut s, PointerKind::Up, 135.0, 125.0); + assert!(!s.in_interaction(), "{at}"); + assert!(s.doc().unwrap().doc.node(other).is_none(), "{at}: the deletion stays"); + assert_ne!(s.doc().unwrap().doc.node(target).cloned(), before, "{at}: the release warps the other square"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "{at}: the deletion and the stroke are a step each"); + let (id, p) = s.journal.last().unwrap(); + assert_eq!((id.as_str(), &p["ids"]), ("object.liquify", &json!([target.0])), "{at}"); + } +} + +/// The Scale and Rotate tools and the Pen adding to a path, with a command that deletes the +/// object they act on during the drag: the drag ends without an edit of its own and the deletion +/// stays. +#[test] +fn a_scale_rotate_or_pen_drag_of_an_object_a_command_deleted_ends_without_an_edit() { + let drags: [(&str, &[(f64, f64)]); 3] = [ + ("scale", &[(150.0, 150.0), (170.0, 170.0), (190.0, 190.0)]), + ("rotate", &[(160.0, 120.0), (150.0, 150.0), (120.0, 160.0)]), + ("pen", &[(350.0, 350.0), (370.0, 360.0), (380.0, 380.0)]), + ]; + for (tool, pts) in drags { + for real_time in [true, false] { + let at = format!("{tool}, real time {real_time}"); + let (mut s, target, _) = two_squares(real_time); + s.select_tool(tool, view()).unwrap(); + let target = if tool == "pen" { + s.execute("select.none", &json!({})).unwrap(); + for (x, y) in [(300.0, 300.0), (350.0, 300.0)] { + pointer(&mut s, PointerKind::Down, x, y); + pointer(&mut s, PointerKind::Up, x, y); + } + s.doc().unwrap().selection.objects[0] + } else { + target + }; + let before = s.doc().unwrap().doc.clone(); + let steps = s.doc().unwrap().history.undo.len(); + drag_with(&mut s, pts, |s| { + s.execute("edit.clear", &json!({"ids": [target.0]})).unwrap(); + }); + assert!(!s.in_interaction(), "{at}"); + assert!(s.doc().unwrap().doc.node(target).is_none(), "{at}: the deletion stays"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "{at}: only the deletion is a step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(*s.doc().unwrap().doc, *before, "{at}: Undo brings the object back as it was"); + } + } +} + +/// A Direct Selection drag of an anchor, with a command during it that numbers the path's anchors +/// anew (Add Anchor Point before the dragged one, Reverse Path Direction): the command's edit +/// stays, the drag ends without an edit of its own and moves no other anchor of the path. +#[test] +fn an_anchor_drag_after_a_command_renumbers_its_anchors_moves_no_other_anchor() { + let commands = [("path.insertAnchor", json!({"segment": 0, "t": 0.5}), 1), ("path.reverse", json!({}), 0)]; + for ((id, params, added), real_time) in commands.iter().flat_map(|c| [(c, true), (c, false)]) { + let at = format!("{id}, real time {real_time}"); + let (mut s, target, _) = two_squares(real_time); + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("directSelection", view()).unwrap(); + let points = |s: &Session| -> Vec<(f64, f64)> { + let doc = &s.doc().unwrap().doc; + let path = doc.node(target).and_then(|n| n.path_data()).expect("the square is a path"); + path.anchors().map(|(_, _, a)| (a.p.x, a.p.y)).collect() + }; + let before = points(&s); + let &(x, y) = before.last().expect("the square has anchors"); + let steps = s.doc().unwrap().history.undo.len(); + let mut params = params.clone(); + params["id"] = json!(target.0); + drag_with(&mut s, &[(x, y), (x + 10.0, y + 10.0), (x + 30.0, y + 20.0)], |s| { + s.execute(id, ¶ms).unwrap(); + }); + assert!(!s.in_interaction(), "{at}"); + let after = points(&s); + assert_eq!(after.len(), before.len() + added, "{at}: the command's edit stays"); + assert!(before.iter().all(|p| after.contains(p)), "{at}: no anchor of the square moved: {before:?} → {after:?}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "{at}: only the command is a step"); + } +} + +/// A Direct Selection drag of an anchor, with a command during it that moves the path: the drag +/// goes on and moves the same anchor of the moved path. +#[test] +fn an_anchor_drag_after_a_command_moves_its_path_moves_the_same_anchor() { + for real_time in [true, false] { + let at = format!("real time {real_time}"); + let (mut s, target, _) = two_squares(real_time); + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("directSelection", view()).unwrap(); + let points = |s: &Session| -> Vec<(f64, f64)> { + let doc = &s.doc().unwrap().doc; + let path = doc.node(target).and_then(|n| n.path_data()).expect("the square is a path"); + path.anchors().map(|(_, _, a)| (a.p.x, a.p.y)).collect() + }; + let before = points(&s); + let &(x, y) = before.last().expect("the square has anchors"); + let steps = s.doc().unwrap().history.undo.len(); + drag_with(&mut s, &[(x, y), (x + 10.0, y + 10.0), (x + 30.0, y + 20.0)], |s| { + s.execute("object.move", &json!({"ids": [target.0], "dx": 0, "dy": 50})).unwrap(); + }); + let after = points(&s); + let last = before.len() - 1; + let moved: Vec<(f64, f64)> = + before.iter().enumerate().map(|(i, &(px, py))| if i == last { (px + 30.0, py + 70.0) } else { (px, py + 50.0) }).collect(); + assert_eq!(after, moved, "{at}: the drag moves the same anchor of the moved square"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "{at}: the move and the drag are a step each"); + } +} + +/// With the Live Paint Bucket's Selection tool (Cmd+drag), a fill chosen during the drag stays the +/// new-art fill after the release and after Escape, though the drag puts back the bucket's colors +/// it began with. +#[test] +fn a_fill_chosen_during_a_bucket_drag_stays() { + for (real_time, escape) in [(true, false), (false, false), (true, true), (false, true)] { + let at = format!("real time {real_time}, Escape {escape}"); + let (mut s, _, _) = two_squares(real_time); + s.select_tool("livePaintBucket", view()).unwrap(); + let cmd = Mods { cmd: true, ..Mods::default() }; + for (kind, x, y) in [(PointerKind::Down, 120.0, 120.0), (PointerKind::Drag, 140.0, 130.0)] { + s.pointer(&PointerEvent::new(kind, x, y).with_mods(cmd), view()).unwrap(); + } + assert!(s.in_interaction(), "{at}: the lent Selection tool drags the square"); + s.execute("paint.setFill", &json!({"color": "#00ff00", "ids": []})).unwrap(); + let green = s.paint.fill.clone(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 170.0, 150.0).with_mods(cmd), view()).unwrap(); + if escape { + s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::Up, 170.0, 150.0).with_mods(cmd), view()).unwrap(); + assert_eq!(s.paint.fill, green, "{at}"); + } +} + +/// A command run during a Quick Pen press still runs inside the press, so it records no undo +/// step of its own while the press is held. +#[test] +fn a_command_during_a_quick_pen_press_runs_inside_it() { + for real_time in [true, false] { + let at = format!("real time {real_time}"); + let (mut s, other) = session(real_time); + s.select_tool(vectorcraft_tools::quickpen::ID, view()).unwrap(); + pointer(&mut s, PointerKind::Down, 50.0, 50.0); + pointer(&mut s, PointerKind::Up, 50.0, 50.0); + pointer(&mut s, PointerKind::Down, 100.0, 100.0); + pointer(&mut s, PointerKind::Drag, 150.0, 120.0); + assert!(s.in_interaction(), "{at}: the press drags a piece"); + let steps = s.doc().unwrap().history.undo.len(); + s.execute("object.hide", &json!({"ids": [other.0]})).unwrap(); + assert!(s.in_interaction(), "{at}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{at}: no step of its own during the press"); + } +} diff --git a/crates/engine/src/tests/outlinestroke.rs b/crates/engine/src/tests/outlinestroke.rs index 16b57a628c..494ac8dc52 100644 --- a/crates/engine/src/tests/outlinestroke.rs +++ b/crates/engine/src/tests/outlinestroke.rs @@ -73,13 +73,14 @@ fn arrowheads_are_part_of_the_outline() { assert_eq!(path_of(&n).subpaths.len(), 1, "line and head are one shape"); } -/// Outline Stroke of a Lens-profile line covers 2/3 of the full-width rectangle. +/// Outline Stroke of a Lens-profile line covers 7/12 of the full-width rectangle. #[test] -fn a_lens_profile_outlines_to_two_thirds_of_the_rectangle() { +fn a_lens_profile_outlines_to_seven_twelfths_of_the_rectangle() { let mut s = session(); line(&mut s, json!({"weight": 10, "profile": "lens"})); let n = outline(&mut s); - assert!(near(area(&n), 2.0 / 3.0 * 10.0 * 100.0, 2.0), "{}", area(&n)); + // Each half of the lens swells on a cubic, flat at the middle (#5714). + assert!(near(area(&n), 7.0 / 12.0 * 10.0 * 100.0, 2.0), "{}", area(&n)); } #[test] diff --git a/crates/engine/src/tests/segment_nudge.rs b/crates/engine/src/tests/segment_nudge.rs new file mode 100644 index 0000000000..9a6e4c7523 --- /dev/null +++ b/crates/engine/src/tests/segment_nudge.rs @@ -0,0 +1,160 @@ +//! The arrow keys with a curved segment selected bend it: its anchors stay, its handles keep their +//! directions, and the middle of the curve moves toward the arrow. + +use std::sync::Arc; + +use serde_json::json; +use vectorcraft_doc::{Appearance, Document, Node, NodeId}; +use vectorcraft_geom::{Anchor, ParamCurve, PathData, Point, SubPath, Vec2}; + +use crate::*; + +/// A session with one open path of one segment from (100, 300) to (400, 300), with the handles +/// `out` at its start and `in` at its end, and that segment selected with Direct Selection. +fn selected_segment(out: Point, h_in: Point) -> (Session, NodeId) { + let (p0, p1) = (Point::new(100.0, 300.0), Point::new(400.0, 300.0)); + let (s, id) = session_with(vec![Anchor::with_handles(p0, p0, out), Anchor::with_handles(p1, h_in, p1)]); + (select(s, id, &[0]), id) +} + +/// A session with one open path through `anchors`. +fn session_with(anchors: Vec) -> (Session, NodeId) { + let mut d = Document::new(1000.0, 1000.0); + let id = d.alloc_id(); + let node = Node::path(id, PathData::single(SubPath::new(anchors, false)), Appearance::default_art()); + if let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() { + ch.push(Arc::new(node)); + } + let mut s = Session::new(); + s.add_document(d, None); + (s, id) +} + +/// `s` with segments `segments` of path `id` selected with Direct Selection. +fn select(mut s: Session, id: NodeId, segments: &[usize]) -> Session { + let refs: Vec<_> = segments.iter().map(|&seg| [0, seg]).collect(); + s.execute("select.segments", &json!({"id": id.0, "segments": refs})).unwrap(); + s +} + +fn undo_steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn segment(s: &Session, id: NodeId) -> SubPath { + s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].clone() +} + +/// Each handle as a vector from its anchor: the outgoing one at the start, the incoming one at +/// the end. +fn handles(sp: &SubPath) -> (Vec2, Vec2) { + (sp.anchors[0].h_out - sp.anchors[0].p, sp.anchors[1].h_in - sp.anchors[1].p) +} + +fn middle(sp: &SubPath) -> Point { + sp.segment(0).eval(0.5) +} + +#[test] +fn arrows_bend_a_selected_curved_segment_and_keep_its_anchors() { + // The handle at the start points up, the one at the end left. + let (mut s, id) = selected_segment(Point::new(100.0, 150.0), Point::new(300.0, 300.0)); + let step = s.prefs.keyboard_increment; + let before = segment(&s, id); + let (up, left) = handles(&before); + + // Up: the upward handle grows, the one across the arrow stays. + s.execute("object.nudge", &json!({"dx": 0, "dy": -1})).unwrap(); + let after = segment(&s, id); + let (up2, left2) = handles(&after); + assert_eq!((after.anchors[0].p, after.anchors[1].p), (before.anchors[0].p, before.anchors[1].p), "the anchors stay"); + assert!(up2.hypot() > up.hypot() && up2.cross(up).abs() < 1e-9 && up2.dot(up) > 0.0, "the upward handle grows in its direction: {up2:?}"); + assert_eq!(left2, left, "the handle across the arrow stays"); + assert!((middle(&after) - middle(&before) - Vec2::new(0.0, -step)).hypot() < 1e-9, "the middle moves one step up"); + + // Right: the handle pointing left shrinks, the upward one stays. + s.execute("object.nudge", &json!({"dx": 1, "dy": 0})).unwrap(); + let last = segment(&s, id); + let (up3, left3) = handles(&last); + assert_eq!(up3, up2, "the handle across the arrow stays"); + assert!(left3.hypot() < left2.hypot() && left3.cross(left2).abs() < 1e-9 && left3.dot(left2) > 0.0, "the leftward handle shrinks: {left3:?}"); + assert!((middle(&last) - middle(&after) - Vec2::new(step, 0.0)).hypot() < 1e-9, "the middle moves one step right"); +} + +#[test] +fn arrows_move_a_selected_straight_segment_whole() { + let (mut s, id) = selected_segment(Point::new(100.0, 300.0), Point::new(400.0, 300.0)); + let step = s.prefs.keyboard_increment; + let before = segment(&s, id); + s.execute("object.nudge", &json!({"dx": 0, "dy": 1})).unwrap(); + let after = segment(&s, id); + for (a, b) in before.anchors.iter().zip(&after.anchors) { + assert_eq!(b.p - a.p, Vec2::new(0.0, step)); + } +} + +#[test] +fn a_selected_straight_segment_beside_a_curved_one_moves_whole() { + let (p0, p1, p2) = (Point::new(100.0, 300.0), Point::new(400.0, 300.0), Point::new(600.0, 300.0)); + let (s, id) = session_with(vec![ + Anchor::with_handles(p0, p0, Point::new(100.0, 150.0)), + Anchor::with_handles(p1, Point::new(300.0, 300.0), p1), + Anchor::corner(p2), + ]); + let mut s = select(s, id, &[0, 1]); + let step = s.prefs.keyboard_increment; + let before = segment(&s, id); + s.execute("object.nudge", &json!({"dx": 0, "dy": -1})).unwrap(); + let after = segment(&s, id); + assert_eq!(after.anchors[0].p, before.anchors[0].p, "the curved segment's other anchor stays"); + for i in [1, 2] { + assert_eq!(after.anchors[i].p - before.anchors[i].p, Vec2::new(0.0, -step), "the straight segment's anchor {i} moves"); + } +} + +#[test] +fn a_segment_whose_handles_lie_across_the_arrow_records_no_undo_step() { + // Both handles point up: ← and → bend nothing. + let (mut s, id) = selected_segment(Point::new(100.0, 150.0), Point::new(400.0, 150.0)); + let (before, steps) = (segment(&s, id), undo_steps(&s)); + s.execute("object.nudge", &json!({"dx": 1, "dy": 0})).unwrap(); + assert_eq!(segment(&s, id), before); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn a_handle_bent_through_a_smooth_anchor_leaves_the_next_segment_as_it_is() { + // A smooth anchor between the selected segment, whose handle there is short and points up, + // and the next one. + let (p0, p1, p2) = (Point::new(100.0, 300.0), Point::new(400.0, 300.0), Point::new(700.0, 300.0)); + let smooth = Anchor::with_handles(p0, Point::new(100.0, 310.0), Point::new(100.0, 299.5)); + let (s, id) = session_with(vec![ + Anchor::corner(Point::new(-200.0, 300.0)), + smooth, + Anchor::with_handles(p1, Point::new(300.0, 300.0), p1), + Anchor::corner(p2), + ]); + assert_eq!(smooth.kind, vectorcraft_geom::AnchorKind::Smooth); + let mut s = select(s, id, &[1]); + let h_in = segment(&s, id).anchors[1].h_in; + // ↓ shrinks the upward handle through its anchor. + s.execute("object.nudge", &json!({"dx": 0, "dy": 1})).unwrap(); + let after = segment(&s, id).anchors[1]; + assert!(after.h_out.y > p0.y, "the handle comes out pointing down: {:?}", after.h_out); + assert_eq!(after.h_in, h_in, "the next segment's handle stays"); +} + +#[test] +fn a_retracted_handle_the_arrow_leaves_keeps_its_smooth_anchor_smooth() { + // A smooth anchor whose outgoing handle is retracted, so it points toward the other handle's + // end, level with it and across ↓; only the other handle, pointing up, changes. + let (p0, p1) = (Point::new(100.0, 300.0), Point::new(200.0, 400.0)); + let smooth = Anchor { p: p0, h_in: Point::new(0.0, 300.0), h_out: p0, kind: vectorcraft_geom::AnchorKind::Smooth }; + let (s, id) = session_with(vec![Anchor::corner(Point::new(-200.0, 300.0)), smooth, Anchor::with_handles(p1, Point::new(200.0, 300.0), p1)]); + let mut s = select(s, id, &[1]); + let before = segment(&s, id); + s.execute("object.nudge", &json!({"dx": 0, "dy": 1})).unwrap(); + let after = segment(&s, id); + assert_ne!(after.anchors[2].h_in, before.anchors[2].h_in, "the upward handle changes"); + assert_eq!(after.anchors[1], before.anchors[1], "the smooth anchor stays as it was"); +} diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index b94baa9233..653ed92752 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -618,6 +618,7 @@ impl Session { path_only: self.prefs.object_selection_by_path_only, type_path_only: self.prefs.type_selection_by_path_only, double_click_isolate: self.prefs.double_click_to_isolate, + double_click_adds_anchor: self.prefs.double_click_adds_anchor_points, select_behind: self.prefs.ctrl_click_selects_behind, highlight_anchors: self.prefs.highlight_anchors_on_hover, snap_tolerance: self.prefs.snap_to_point_tolerance, @@ -1727,6 +1728,10 @@ impl Session { /// Apply tool actions. Errors from previews are reported but keep the interaction alive. pub fn apply_actions(&mut self, acts: Vec) -> Result> { + // The tool acts on its own interaction, which a command from outside it may have set aside. + if !acts.is_empty() { + self.put_back_interaction(); + } let outer = std::mem::replace(&mut self.in_tool_actions, true); let outer_bucket = self.back_to_bucket; // The Eyedropper's sample into a stop of the Live Paint Bucket's gradient, which switches back to the bucket. @@ -1752,7 +1757,16 @@ impl Session { let mut ui = vec![]; for a in acts { match a { - Action::Begin(label) => self.begin_interaction(&label)?, + Action::Begin(label) => { + // The snapshot of the interaction open before, which the tool's drag then joins. + let open = self.active().and_then(|st| st.interaction.as_ref()).map(|it| std::sync::Arc::as_ptr(&it.doc)); + self.begin_interaction(&label)?; + if let Some(it) = self.active_mut().and_then(|st| st.interaction.as_mut()) + && open != Some(std::sync::Arc::as_ptr(&it.doc)) + { + it.tool = true; + } + } Action::Preview(cmd, p) => { // Performance › Real-time Drawing and Editing (#394): off, remember the latest // params and apply them once on Commit instead of every move. A ruler guide diff --git a/crates/engine/tests/it/dimensions.rs b/crates/engine/tests/it/dimensions.rs index 1407d10378..e1832f3d17 100644 --- a/crates/engine/tests/it/dimensions.rs +++ b/crates/engine/tests/it/dimensions.rs @@ -225,6 +225,28 @@ fn dimension_angles_circles_arcs_and_curves() { assert_eq!(text(&s, id), "100 pt"); } +#[test] +fn an_angular_dimension_can_take_its_vertex_from_an_anchor() { + let mut s = session(); + let line = edge(&mut s); + let request = json!({ + "mode": "angular", "a": [172, 100], "b": [100, 172], "options": {"precision": 1}, + "source": {"kind": "points", "vertex": {"node": line, "subpath": 0, "anchor": 0}} + }); + let id = run(&mut s, "dimension.create", request.clone())["id"].as_u64().unwrap(); + assert_eq!(text(&s, id), "90.0°"); + run(&mut s, "select.set", json!({"ids": [line]})); + run(&mut s, "object.move", json!({"dx": 18, "dy": 0})); + assert!(near(recipe(&s, id).vertex, vectorcraft_geom::Point::new(118.0, 100.0))); + + let mut invalid = request.clone(); + invalid["vertex"] = json!("bad point"); + assert!(s.execute("dimension.create", &invalid).is_err()); + let mut missing = request; + missing["source"]["vertex"] = Value::Null; + assert!(s.execute("dimension.create", &missing).is_err()); +} + #[test] fn dimension_rejects_bad_input_without_mutation() { let mut s = session(); diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index 8182553b00..79316319a4 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -39,6 +39,7 @@ mod ai; mod ate; mod cid; mod data; +mod file_fonts; mod graphics; mod interp; mod lex; @@ -113,6 +114,10 @@ const MAX_SIDE: f64 = 1e5; /// The start of the warning that type was set in fonts that aren't available, before ": " and /// their families: PDF import's words, as type in those fonts comes in the same way. pub(crate) const MISSING_FONTS_NOTE: &str = "fonts that aren't available show in the fallback font until they are"; +/// The start of the warning that type in fonts that aren't available is drawn in the fonts the +/// file carries (see `file_fonts`), before ": " and their families: PDF import's words. +pub(crate) const CARRIED_FONTS_NOTE: &str = + "fonts that aren't available show as the file draws them, in the fonts it carries, until their text is edited (then in the fallback font)"; /// Most families named in that warning. const MAX_MISSING_FONTS: usize = 64; @@ -304,30 +309,41 @@ pub fn import_ai(bytes: &[u8], editing_data: bool, trust: bool, names: NameEncod /// [`import_names`] (a `.ai` when `ai_file`, see [`import_ai`]). fn read_checked(bytes: &[u8], editing_data: bool, trust: bool, names: NameEncoding, ai_file: bool) -> Result { let mut r = read_names(bytes, editing_data, trust, names, ai_file)?; - let missing = missing_fonts(&r.document); - if !missing.is_empty() { - r.warnings.push(format!("{MISSING_FONTS_NOTE}: {}", missing.join(", "))); + r.warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut r.document)); + let (carried, missing) = missing_fonts(&r.document); + for (note, families) in [(CARRIED_FONTS_NOTE, carried), (MISSING_FONTS_NOTE, missing)] { + if !families.is_empty() { + r.warnings.push(format!("{note}: {}", families.join(", "))); + } } Ok(r) } /// The families of the type in `d` (its layers and its symbols) that aren't available, each once -/// in the order the type comes, at most [`MAX_MISSING_FONTS`]: the document's, whether its type -/// came from the page or from an editing copy, and none for type only measured or outlined. -fn missing_fonts(d: &Document) -> Vec { +/// in the order the type comes, at most [`MAX_MISSING_FONTS`] a list: the document's, whether its +/// type came from the page or from an editing copy, and none for type only measured or outlined. +/// The first list holds those of type drawn in fonts the file carries (bound to that type), the +/// second those of type in the fallback font; a family both happen to is in both. +fn missing_fonts(d: &Document) -> (Vec, Vec) { let db = vectorcraft_text::FontDb::global(); - let mut checked: HashSet = HashSet::new(); - let mut missing: Vec = Vec::new(); + let (mut carried, mut missing): (Vec, Vec) = (Vec::new(), Vec::new()); let mut add = |n: &Node| { let NodeKind::Text(t) = &n.kind else { return }; + // The families and styles this type is drawn in from fonts the file carries. + let bound: Vec<(&str, &str)> = t + .file_fonts_in_use() + .iter() + .filter(|font| t.file_fonts.as_ref().and_then(|fonts| fonts.face(&font.key)).is_some()) + .map(|font| (font.family.as_str(), font.style.as_str())) + .collect(); for run in &t.runs { - let family = run.style.font_family.as_str(); - if missing.len() >= MAX_MISSING_FONTS || family.is_empty() || checked.contains(family) { + let (family, style) = (run.style.font_family.as_str(), run.style.font_style.as_str()); + if family.is_empty() { continue; } - checked.insert(family.to_string()); - if db.find_family(family).is_none() { - missing.push(family.to_string()); + let list = if bound.contains(&(family, style)) { &mut carried } else { &mut missing }; + if list.len() < MAX_MISSING_FONTS && !list.iter().any(|f| f == family) && db.find_family(family).is_none() { + list.push(family.to_string()); } } }; @@ -335,7 +351,7 @@ fn missing_fonts(d: &Document) -> Vec { for s in &d.symbols { s.art.walk(&mut add); } - missing + (carried, missing) } /// [`import_names`] before the type's fonts are checked (a `.ai` when `ai_file`, see [`import_ai`]). @@ -406,6 +422,9 @@ fn finish(mut out: Out) -> Imported { if !out.shadings.is_empty() { graphics::collapse(&mut children, &out.shadings); } + // The fonts made of the glyphs of fonts the file carries, for their type. + let kept = std::mem::take(&mut out.file_glyphs).keep(&mut out.doc.images); + file_fonts::keep_file_fonts(&mut children, &kept, &out.doc.images); let mut layer = Node::layer(out.doc.alloc_id(), "Layer 1", LayerColor::Preset(0)); if let Some(c) = layer.children_mut() { *c = children; diff --git a/crates/eps/src/import/data/filters.rs b/crates/eps/src/import/data/filters.rs index 3dc9662bdf..cada27219a 100644 --- a/crates/eps/src/import/data/filters.rs +++ b/crates/eps/src/import/data/filters.rs @@ -76,14 +76,28 @@ fn flate(raw: &[u8]) -> Res<(Vec, usize)> { /// LZW data (`EarlyChange` 1) decoded, and how many bytes of `raw` it took. fn lzw(raw: &[u8]) -> Res<(Vec, usize)> { + let mut out = vec![]; + let used = lzw_into(raw, &mut |bytes| { + out.extend_from_slice(bytes); + if out.len() > MAX_DATA { + return Err(PsError::Limit("decoded data is too large")); + } + Ok(()) + })?; + Ok((out, used)) +} + +/// LZW data (`EarlyChange` 1) decoded into `sink` as it goes, and how many bytes of `raw` it +/// took. +fn lzw_into(raw: &[u8], sink: &mut dyn FnMut(&[u8]) -> Res) -> Res { let mut table: Vec> = (0..=255u8).map(|b| vec![b]).collect(); table.push(vec![]); table.push(vec![]); - let (mut out, mut prev): (Vec, Option>) = (vec![], None); + let mut prev: Option> = None; let (mut acc, mut bits, mut width, mut i) = (0u32, 0u32, 9u32, 0usize); loop { while bits < width { - let Some(&b) = raw.get(i) else { return Ok((out, i)) }; + let Some(&b) = raw.get(i) else { return Ok(i) }; i += 1; acc = (acc << 8) | u32::from(b); bits += 8; @@ -96,7 +110,7 @@ fn lzw(raw: &[u8]) -> Res<(Vec, usize)> { width = 9; prev = None; } - 257 => return Ok((out, i)), + 257 => return Ok(i), _ => { let entry = match (table.get(code), &prev) { (Some(e), _) if !e.is_empty() => e.clone(), @@ -107,7 +121,7 @@ fn lzw(raw: &[u8]) -> Res<(Vec, usize)> { } _ => return io("LZWDecode"), }; - out.extend_from_slice(&entry); + sink(&entry)?; if let Some(mut p) = prev.take() && table.len() < 4096 { @@ -121,14 +135,78 @@ fn lzw(raw: &[u8]) -> Res<(Vec, usize)> { _ => 9, }; prev = Some(entry); - if out.len() > MAX_DATA { - return Err(PsError::Limit("decoded data is too large")); - } } } } } +/// zlib data inflated into `sink` as it goes (64 KiB at a time), and how many bytes of `raw` it +/// took. +fn flate_into(raw: &[u8], sink: &mut dyn FnMut(&[u8]) -> Res) -> Res { + let mut z = flate2::Decompress::new(true); + let mut scratch = vec![0u8; 64 * 1024]; + loop { + let before = (z.total_in(), z.total_out()); + let input = raw.get(usize::try_from(z.total_in()).unwrap_or(usize::MAX)..).unwrap_or_default(); + let status = z.decompress(input, &mut scratch, flate2::FlushDecompress::None).map_err(|_| PsError::Ps("ioerror", "FlateDecode".into()))?; + let made = usize::try_from(z.total_out() - before.1).unwrap_or(0); + sink(scratch.get(..made).unwrap_or_default())?; + match status { + flate2::Status::StreamEnd => break, + _ if (z.total_in(), z.total_out()) == before => break, + _ => {} + } + } + Ok(usize::try_from(z.total_in()).unwrap_or(raw.len())) +} + +/// Data compressed with filter `f` (`FlateDecode` or `LZWDecode` without a predictor) decoded +/// into `sink` as it goes, and how many bytes of `raw` it took; `None` for other filters. +pub(super) fn decode_into(f: &Filter, raw: &[u8], sink: &mut dyn FnMut(&[u8]) -> Res) -> Option> { + match &*f.name { + _ if f.predictor.is_some() => None, + "FlateDecode" => Some(flate_into(raw, sink)), + "LZWDecode" => Some(lzw_into(raw, sink)), + _ => None, + } +} + +/// How many bytes of `raw` filter `f` would read, found without keeping what it decodes, for +/// data whose decoded form is too large to hold: compressed data (`FlateDecode`, `LZWDecode`, +/// `RunLengthDecode`) is decoded and dropped as it goes, a JPEG ends at its end-of-image +/// marker, as [`dct`] reads it. `None` for other filters, data that can't be decoded, or data +/// that decodes to more than `most` bytes (what the caller's operation budget still pays for). +/// With it, how many bytes were decoded on the way, for the caller to charge: measuring costs +/// the work of decoding, so a program that measures the same data in a loop has to end. +pub(super) fn encoded_len(f: &Filter, raw: &[u8], most: usize) -> (Option, usize) { + let mut decoded = 0usize; + let mut count = |bytes: &[u8]| -> Res { + decoded = decoded.saturating_add(bytes.len()); + if decoded > most { + return Err(PsError::Limit("the program runs too long")); + } + Ok(()) + }; + let used = match &*f.name { + "FlateDecode" => flate_into(raw, &mut count).ok(), + "LZWDecode" => lzw_into(raw, &mut count).ok(), + "RunLengthDecode" => { + let mut i = 0usize; + while let Some(&n) = raw.get(i) { + i += match n { + 128 => return (Some(i + 1), 0), + 0..=127 => 2 + usize::from(n), + _ => 2, + }; + } + Some(raw.len()) + } + "DCTDecode" => Some(find(raw, &[0xFF, 0xD9]).map_or(raw.len(), |e| e + 2)), + _ => None, + }; + (used, decoded) +} + /// Most pixels a DCTDecode JPEG may have: twice the most an image is read with, so every image that /// was read before is still read. const MAX_DCT_PIXELS: u64 = 1 << 27; diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index cca8bb50ea..f5d45449f2 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -1,4 +1,4 @@ -use super::filters::{Filter, Predictor, Stream, decode, fax_settings, io}; +use super::filters::{Filter, Predictor, Stream, decode, decode_into, encoded_len, fax_settings, io}; use super::pixels::{Pixels, Spec, by_rows, by_samples, masked, source}; use super::{ Affine, Color, DictRef, HashMap, ImageBlob, ImageObject, Inks, Interp, Key, Lexer, Node, NodeId, NodeKind, Obj, Op, OpacityMask, Paint, PsError, @@ -18,6 +18,8 @@ const MAX_PIXELS: usize = 1 << 26; /// Why an image is missing. const TOO_LARGE: &str = "images too large to read were left out"; +/// Why an image is at a lower resolution than the file's. +const REDUCED: &str = "images of more than 67 million pixels were read at a lower resolution"; /// Most distinct colours an image converts through a tint transform. const MAX_TINTS: usize = 1 << 16; @@ -479,25 +481,184 @@ impl Interp<'_> { /// their own end without decompressing (`ASCIIHexDecode`, `ASCII85Decode`, `SubFileDecode`) /// read the file up to it, the way the image reading all its data would leave it; the /// filters over them, which would only decode what those pass, aren't run. When the first - /// filter decompresses, it is run alone, and a failure (data too large to hold) leaves the - /// data where it was, as before. - fn skip_data(&mut self, src: &Source) { + /// filter decompresses, it is run alone; when it can't hold what it decompresses, it measures + /// its data instead. Unfiltered data is read past by its `n` bytes. A failure that read + /// nothing leaves the data where it was; one after a filter read its data leaves the file + /// past it, with nothing more to read. + fn skip_data(&mut self, src: &Source, n: usize) { + // A procedure (`{ currentfile buf readhexstring pop }`) reads the data itself: it is + // called, and what it gives dropped, until it has given the image's `n` bytes or ends. + if let Source::Proc(p) = src { + let mut given = 0usize; + while given < n { + let Ok(len) = self.call(p.clone()).and_then(|()| self.pop_str()).map(|s| s.len()) else { return }; + if len == 0 { + return; + } + given = given.saturating_add(len); + } + return; + } let Source::File(f) = src else { return }; - let (chain, from) = match &*f.borrow() { + let (chain, from) = match &mut *f.borrow_mut() { Stream::Pending { chain, from } => (chain.clone(), from.clone()), - _ => return, + // The data unfiltered: its `n` bytes are read past, as reading them would. + Stream::Current => { + let k = n.min(self.lex.data().len()); + self.lex.advance(k); + return; + } + Stream::Buf { data, pos, .. } => { + *pos = pos.saturating_add(n).min(data.len()); + return; + } }; let delimited = chain.iter().take_while(|c| matches!(&*c.name, "ASCIIHexDecode" | "ASCII85Decode" | "SubFileDecode")).count(); let head = chain.get(..delimited.max(1)).unwrap_or_default().to_vec(); *f.borrow_mut() = Stream::Pending { chain: head, from: from.clone() }; - // A failure leaves the file as it was; the import goes on without the image either way. + // How much of the file the filters are over is left. + let left = |me: &mut Self| match &from { + None => Some(me.lex.data().len()), + Some(r) => match &*r.borrow() { + Stream::Buf { data, pos, .. } => Some(data.len().saturating_sub(*pos)), + Stream::Current => Some(me.lex.data().len()), + Stream::Pending { .. } => None, + }, + }; + let before = left(self); if self.materialize(f).is_err() { - *f.borrow_mut() = Stream::Pending { chain, from }; - return; + // A filter that read its data before a later one failed has the file past that data, + // where reading the image would leave it: the file is empty from there. + if left(self) != before { + *f.borrow_mut() = Stream::Buf { data: vec![], pos: 0, rgb: None }; + return; + } + // Decompressed data too large to hold: the first filter only measures it instead, + // and the file is read past it. Data that can't be decoded at all leaves the file as + // it was; the import goes on without the image either way. + let Some(first) = chain.first() else { return }; + // Measuring decompresses the data, which is charged by the bytes decoded (one operation + // per 256, as `spend_bytes` charges) and stops at what the budget still pays for: + // data measured again and again (a reusable stream reset in a loop) runs out of the + // budget instead of being decoded in full on every pass. + let most = usize::try_from(self.ops_left().saturating_mul(256)).unwrap_or(usize::MAX); + let (used, decoded) = match &from { + Some(r) => match &*r.borrow() { + Stream::Buf { data, pos, .. } => encoded_len(first, data.get(*pos..).unwrap_or_default(), most), + _ => (None, 0), + }, + None => encoded_len(first, self.lex.data(), most), + }; + let paid = self.spend_bytes(decoded).is_ok(); + let Some(used) = used.filter(|_| paid) else { + *f.borrow_mut() = Stream::Pending { chain, from }; + return; + }; + match &from { + Some(r) => { + if let Stream::Buf { pos, .. } = &mut *r.borrow_mut() { + *pos = pos.saturating_add(used); + } + } + None => self.lex.advance(used), + } } *f.borrow_mut() = Stream::Buf { data: vec![], pos: 0, rgb: None }; } + /// The rows image `s` reads at `step` (rows of `row` bytes), when its one source is the + /// program's data with Flate or LZW last among its filters (and no predictor): the filters + /// before it are decoded as usual, and it decodes into the rows read alone, dropping the + /// others as it goes. `None` (nothing read) for other data, or rows read that would still be + /// more than the reader holds. + fn read_rows(&mut self, s: &Spec, row: usize, step: usize) -> Res>> { + let ([Source::File(f)], oh) = (s.sources.as_slice(), s.h.div_ceil(step)) else { return Ok(None) }; + let (chain, from) = match &*f.borrow() { + Stream::Pending { chain, from } => (chain.clone(), from.clone()), + _ => return Ok(None), + }; + let Some((last, head)) = chain.split_last() else { return Ok(None) }; + if last.predictor.is_some() || !matches!(&*last.name, "FlateDecode" | "LZWDecode") { + return Ok(None); + } + let Some(kept) = row.checked_mul(oh).filter(|k| *k <= MAX_DATA) else { return Ok(None) }; + self.alloc(kept)?; + // The compressed data: what the filters before the last one decode, or the file itself. + let compressed = if head.is_empty() { + None + } else { + *f.borrow_mut() = Stream::Pending { chain: head.to_vec(), from: from.clone() }; + if let Err(e) = self.materialize(f) { + *f.borrow_mut() = Stream::Pending { chain, from }; + return Err(e); + } + match std::mem::replace(&mut *f.borrow_mut(), Stream::Buf { data: vec![], pos: 0, rgb: None }) { + Stream::Buf { data, pos, .. } => Some(data.get(pos..).unwrap_or_default().to_vec()), + _ => Some(vec![]), + } + }; + let (mut rows, mut seen) = (Vec::with_capacity(kept), 0usize); + // Past the image's data and as much again the data is not an image's: it stops there. + let most = row.saturating_mul(s.h).saturating_add(MAX_DATA); + let mut sink = |mut chunk: &[u8]| -> Res { + while !chunk.is_empty() { + let (r, off) = (seen / row.max(1), seen % row.max(1)); + let take = (row - off).min(chunk.len()); + if r < s.h && picked(r / step, step, s.h) == r { + rows.extend_from_slice(chunk.get(..take).unwrap_or_default()); + } + seen += take; + chunk = chunk.get(take..).unwrap_or_default(); + } + if seen > most { + return Err(PsError::Limit("decoded data is too large")); + } + Ok(()) + }; + let used = match &compressed { + Some(data) => decode_into(last, data, &mut sink), + None => match &from { + Some(r) => { + let b = r.borrow(); + let Stream::Buf { data, pos, .. } = &*b else { return io("filter") }; + let used = decode_into(last, data.get(*pos..).unwrap_or_default(), &mut sink); + drop(b); + if let (Some(Ok(n)), Stream::Buf { pos, .. }) = (&used, &mut *r.borrow_mut()) { + *pos = pos.saturating_add(*n); + } + used + } + None => { + let used = decode_into(last, self.lex.data(), &mut sink); + if let Some(Ok(n)) = &used { + self.lex.advance(*n); + } + used + } + }, + }; + drop(sink); + let Some(used) = used else { return Ok(None) }; + // What was decoded is charged whether or not the data decoded to its end. + self.spend_bytes(seen)?; + used?; + *f.borrow_mut() = Stream::Buf { data: vec![], pos: 0, rgb: None }; + rows.resize(kept, 0); + Ok(Some(rows)) + } + + /// Leave out image `s` (too large to read), skipping its data: `None`, the image it gives. + fn leave_out(&mut self, s: &Spec) -> Option { + self.out.warn(TOO_LARGE); + let n = if s.stencil.is_some() { 1 } else { s.space.n() }; + let per_source = if s.sources.len() > 1 { 1 } else { n }; + let bytes = (s.w.saturating_mul(per_source).saturating_mul(usize::from(s.bpc))).div_ceil(8).saturating_mul(s.h); + for src in &s.sources { + self.skip_data(src, bytes); + } + None + } + /// The bytes a data procedure gives, called until it gives an empty string or `n` bytes. fn gather(&mut self, p: &Obj, n: usize) -> Res> { Ok(self.read_sources(&[Source::Proc(p.clone())], n, n)?.pop().unwrap_or_default()) @@ -640,13 +801,6 @@ impl Interp<'_> { let mut stencil = self.image_dict(&mask, false)?; stencil.space = Space::Gray; let n = image.space.n(); - if image.w.saturating_mul(image.h) > MAX_PIXELS || stencil.w.saturating_mul(stencil.h) > MAX_PIXELS { - self.out.warn(TOO_LARGE); - for src in image.sources.iter().chain(&stencil.sources) { - self.skip_data(src); - } - return Ok(None); - } // Interleaved data is read into this decoder's own buffers, split into the two images' // samples: those stop counting once both are decoded (their pixels still count). let mut charged = 0; @@ -655,18 +809,19 @@ impl Interp<'_> { let (pixels, samples) = if interleave == 2.0 { let (mrow, drow) = (stencil.row_bytes(1), image.row_bytes(n)); let total = mrow.saturating_mul(stencil.h).saturating_add(drow.saturating_mul(image.h)); - self.alloc(total)?; - charged = total; - let raw = self.source_bytes(&src, total.min(MAX_DATA))?; + // What is read: an image past the pixel cap is reduced from the samples read. + charged = total.min(MAX_DATA); + self.alloc(charged)?; + let raw = self.source_bytes(&src, charged)?; by_rows(&raw, (mrow, stencil.h), (drow, image.h)) } else { // Each sample: the mask's value, then the colour's, as many bits each. stencil.bpc = image.bpc; (stencil.w, stencil.h) = (image.w, image.h); let row = (image.w * (n + 1) * usize::from(image.bpc)).div_ceil(8); - charged = row.saturating_mul(image.h); + charged = row.saturating_mul(image.h).min(MAX_DATA); self.alloc(charged)?; - let raw = self.source_bytes(&src, charged.min(MAX_DATA))?; + let raw = self.source_bytes(&src, charged)?; by_samples(&raw, image.w, image.h, n, image.bpc) }; stencil.sources = vec![Source::Str(pixels)]; @@ -674,7 +829,12 @@ impl Interp<'_> { } let decoded = match self.decode_image(image) { Ok(Some(img)) => self.decode_image(stencil).map(|m| Some((img, m))), - other => other.map(|_| None), + Ok(None) => { + // The mask's own data (`InterleaveType` 3) is skipped with the image's. + let _ = self.leave_out(&stencil); + Ok(None) + } + Err(e) => Err(e), }; self.unalloc(charged); let Some((mut img, m)) = decoded? else { return Ok(None) }; @@ -755,25 +915,53 @@ impl Interp<'_> { Ok(Spec { w, h, bpc, space, decode: vec![], matrix, sources, mask_color: None, stencil }) } + /// Decode the filters image source `f` waits to run. `false` when the decoded data is past + /// what the reader holds and the image is `reduced` (read at a lower resolution): a decode that + /// fails leaves the file empty (`materialize`), but such an image is left out with its data + /// still to skip, so its filters are put back for that. + fn decode_source(&mut self, f: &Rc>, reduced: bool) -> Res { + let pending = match &*f.borrow() { + Stream::Pending { chain, from } => Some((chain.clone(), from.clone())), + _ => None, + }; + match self.materialize(f) { + Ok(()) => Ok(true), + Err(PsError::Limit(_)) if reduced => { + if let Some((chain, from)) = pending { + *f.borrow_mut() = Stream::Pending { chain, from }; + } + Ok(false) + } + Err(e) => Err(e), + } + } + /// The image's pixels, straight RGBA, rows from the first one read, and a CMYK image's ink /// amounts. fn decode_image(&mut self, s: Spec) -> Res> { if !matches!(s.bpc, 1 | 2 | 4 | 8 | 12 | 16) { return ps_err("rangecheck", "BitsPerComponent"); } - if s.w.saturating_mul(s.h) > MAX_PIXELS { - self.out.warn(TOO_LARGE); - for src in &s.sources { - self.skip_data(src); - } - return Ok(None); - } - self.alloc(s.w * s.h * 4)?; + // An image of more pixels than the cap is read at a lower resolution: every `step`th + // sample of every `step`th row (the middle one of each `step` × `step` block). + let step = reduction(s.w, s.h); + let (ow, oh) = (s.w.div_ceil(step), s.h.div_ceil(step)); let n = if s.stencil.is_some() { 1 } else { s.space.n() }; let bpc = usize::from(s.bpc); - for src in &s.sources { - if let Source::File(f) = src { - self.materialize(f)?; + // A reduced image compressed last with Flate or LZW keeps only the rows it reads, as they + // are decoded: its whole data can be more than the reader holds. + let streamed = match if step > 1 { self.read_rows(&s, (s.w * n * bpc).div_ceil(8), step) } else { Ok(None) } { + Ok(rows) => rows, + Err(PsError::Limit(_)) => return Ok(self.leave_out(&s)), + Err(e) => return Err(e), + }; + for src in s.sources.iter().filter(|_| streamed.is_none()) { + // Decoded data past the cap: a reduced image is left out (its data skipped) rather + // than failing the file, as an image too large to read at all is. + if let Source::File(f) = src + && !self.decode_source(f, step > 1)? + { + return Ok(self.leave_out(&s)); } } // A decoded JPEG gives 8-bit gray, RGB or CMYK samples whatever the color space says. @@ -798,15 +986,39 @@ impl Interp<'_> { if sources.len() > n { return ps_err("rangecheck", "DataSource"); } - let plane = row.checked_mul(s.h).filter(|p| *p <= MAX_DATA).ok_or(PsError::Limit("decoded data is too large"))?; - // The sample planes are this decoder's own and live only while the image is decoded: they - // stop counting once it is (the pixels made from them still count). What the data source - // procedures allocate is the program's and stays counted. - let plane_bytes = plane.saturating_mul(sources.len()); - self.alloc(plane_bytes)?; - let mut planes = self.read_sources(sources, row * s.h, if multi { row } else { row * s.h })?; - for p in &mut planes { - p.resize(row * s.h, 0); + // With only the rows read kept, row `i` of the plane is the `i`th row read. + let rows_kept = streamed.is_some(); + // The sample planes (or the rows kept) are this decoder's own and live only while the + // image is decoded: they stop counting once it is (the pixels made from them still + // count). What the data source procedures allocate is the program's and stays counted. + let (planes, plane_bytes) = match streamed { + Some(rows) => { + let kept = rows.len(); + (vec![rows], kept) + } + None => { + // More samples than the reader holds: a reduced image is left out (its data + // skipped), while one within the pixel cap whose samples are still too much data + // (16-bit CMYK, say) stops the read with the limit, as before (#3568: such a plane + // is refused). + let Some(plane) = row.checked_mul(s.h).filter(|p| *p <= MAX_DATA) else { + if step > 1 { + return Ok(self.leave_out(&s)); + } + return Err(PsError::Limit("decoded data is too large")); + }; + let plane_bytes = plane.saturating_mul(sources.len()); + self.alloc(plane_bytes)?; + let mut planes = self.read_sources(sources, row * s.h, if multi { row } else { row * s.h })?; + for p in &mut planes { + p.resize(row * s.h, 0); + } + (planes, plane_bytes) + } + }; + self.alloc(ow * oh * 4)?; + if step > 1 { + self.out.warn(REDUCED); } let max = ((1u32 << bpc.min(16)) - 1) as f64; let sample = |plane: &[u8], y: usize, i: usize| -> u32 { @@ -830,19 +1042,19 @@ impl Interp<'_> { // with the default Decode array. let decode = if s.decode.len() >= 2 * n && jpeg.is_none_or(|c| c == 4) { s.decode.clone() } else { default_decode }; let paint = self.g.paint.color().map(|c| c.to_rgba8(1.0)); - let mut rgba = Vec::with_capacity(s.w * s.h * 4); + let mut rgba = Vec::with_capacity(ow * oh * 4); // CMYK samples keep their ink amounts, as the Decode array reads them. let mut inks = if matches!(space, Space::Cmyk) && s.stencil.is_none() { - self.alloc(s.w * s.h * 4)?; - Some(Vec::with_capacity(s.w * s.h * 4)) + self.alloc(ow * oh * 4)?; + Some(Vec::with_capacity(ow * oh * 4)) } else { None }; let mut cache: HashMap, [u8; 3]> = HashMap::new(); let mut raw = vec![0u32; n]; let mut comps = vec![0f64; n]; - for y in 0..s.h { - for x in 0..s.w { + for y in (0..oh).map(|y| if rows_kept { y } else { picked(y, step, s.h) }) { + for x in (0..ow).map(|x| picked(x, step, s.w)) { for (c, slot) in raw.iter_mut().enumerate() { *slot = match planes.as_slice() { [one] => sample(one, y, x * n + c), @@ -882,7 +1094,9 @@ impl Interp<'_> { } drop(planes); self.unalloc(plane_bytes); - Ok(Some(Pixels { w: s.w as u32, h: s.h as u32, rgba, inks, matrix: s.matrix })) + // The reduced samples cover the image's area: image space scaled to them. + let matrix = Affine::scale_non_uniform(ow as f64 / s.w as f64, oh as f64 / s.h as f64) * s.matrix; + Ok(Some(Pixels { w: ow as u32, h: oh as u32, rgba, inks, matrix })) } /// One pixel's colour in `space` as display RGB. @@ -959,3 +1173,19 @@ impl Interp<'_> { Some(OpacityMask::new(Node::new(self.out.doc.alloc_id(), NodeKind::Image(Box::new(im))), true)) } } + +/// The sample (or row) of `len` a reduced image reads as its `i`th at `step`: the middle one of +/// its block of `step`, the last one in a short last block. +fn picked(i: usize, step: usize, len: usize) -> usize { + (i * step + step / 2).min(len.saturating_sub(1)) +} + +/// The step [`Interp::decode_image`] reads a `w` × `h` image at: 1 (every sample) within +/// [`MAX_PIXELS`], else the least that brings the samples it reads within it. +fn reduction(w: usize, h: usize) -> usize { + let mut step = 1; + while w.div_ceil(step).saturating_mul(h.div_ceil(step)) > MAX_PIXELS { + step += 1; + } + step +} diff --git a/crates/eps/src/import/file_fonts.rs b/crates/eps/src/import/file_fonts.rs new file mode 100644 index 0000000000..83e51bb7ee --- /dev/null +++ b/crates/eps/src/import/file_fonts.rs @@ -0,0 +1,192 @@ +//! The fonts an EPS carries (embeds) for type whose fonts aren't available here, kept with the +//! document as PDF import keeps a PDF's (#4568): the glyphs its type is shown in, gathered as the +//! program runs, become one font per family and style ([`vectorcraft_text::build_file_font`]), +//! which draws that type as the file draws it until its text is edited +//! ([`vectorcraft_doc::FileFonts`]). +//! +//! Each glyph comes from the font program the file carries (a Type 1 font's charstrings, a Type 42 +//! font's TrueType glyph): its outline and advance, for the character its code shows. The first +//! glyph of each character is kept; a string that uses a different glyph for a character is drawn +//! as outlines instead. + +use std::collections::{BTreeMap, HashMap}; +use std::sync::Arc; + +use vectorcraft_doc::{FILE_FONT_MIME, FileFont, FileFonts, ImageBlob, Node, NodeKind}; +use vectorcraft_text::{FileFontInfo, FileGlyph, MAX_FILE_GLYPHS, build_file_font}; + +/// The most glyphs gathered from one file, in all its fonts (an outline is some hundreds of bytes). +const MAX_GLYPHS: usize = 200_000; + +/// The glyphs gathered so far. +#[derive(Default)] +pub(crate) struct FileFontGlyphs { + fonts: Vec, + /// Each font (family and style) by its index in `fonts`. + index: HashMap<(String, String), usize>, + /// Glyphs gathered, in all. + count: usize, +} + +/// The glyphs of one family and style. +struct Gathered { + family: String, + style: String, + info: FileFontInfo, + glyphs: Vec, + /// Each character's glyph, by its index in `glyphs`. + chars: HashMap, +} + +impl FileFontGlyphs { + /// The font of `family` and `style` (made with `info` the first time): its index. + pub fn font(&mut self, family: &str, style: &str, info: impl FnOnce() -> FileFontInfo) -> usize { + if let Some(&i) = self.index.get(&(family.to_string(), style.to_string())) { + return i; + } + let i = self.fonts.len(); + self.fonts.push(Gathered { family: family.to_string(), style: style.to_string(), info: info(), glyphs: vec![], chars: HashMap::new() }); + self.index.insert((family.to_string(), style.to_string()), i); + i + } + + /// Can `glyphs` all be drawn in font `font`: no character among them has a glyph there, or + /// earlier in `glyphs`, that differs in outline or advance (a font keeps one glyph per + /// character), and the font has room for the characters it doesn't have yet? Each glyph is + /// compared with the one its character has, once, as PDF import does. + pub fn fits(&self, font: usize, glyphs: &[FileGlyph]) -> bool { + let Some(f) = self.fonts.get(font) else { return false }; + let mut new: HashMap = HashMap::new(); + for g in glyphs { + let kept = f.chars.get(&g.ch).and_then(|&k| f.glyphs.get(k)).or_else(|| new.get(&g.ch).copied()); + match kept { + Some(k) if k.outline != g.outline || k.advance != g.advance => return false, + Some(_) => {} + None => { + new.insert(g.ch, g); + } + } + } + f.glyphs.len().saturating_add(new.len()) <= MAX_FILE_GLYPHS && self.count.saturating_add(new.len()) <= MAX_GLYPHS + } + + /// Gather `glyph` for font `font`, unless it already has one for its character or is full. + pub fn add(&mut self, font: usize, glyph: FileGlyph) { + if self.count >= MAX_GLYPHS { + return; + } + if let Some(f) = self.fonts.get_mut(font) + && f.glyphs.len() < MAX_FILE_GLYPHS + && !f.chars.contains_key(&glyph.ch) + { + f.chars.insert(glyph.ch, f.glyphs.len()); + f.glyphs.push(glyph); + self.count += 1; + } + } + + /// The fonts built from the glyphs gathered, stored in `images` under their content keys: + /// family and style → the font's key. + pub fn keep(self, images: &mut BTreeMap) -> HashMap<(String, String), String> { + let mut kept = HashMap::new(); + for f in self.fonts { + let Some(bytes) = build_file_font(&f.info, &f.glyphs) else { continue }; + let blob = ImageBlob::new(FILE_FONT_MIME, bytes); + let base = blob.content_key(); + let mut key = base.clone(); + let mut suffix = 1; + while images.get(&key).is_some_and(|held| held != &blob) { + key = format!("{base}-{suffix}"); + suffix += 1; + } + images.entry(key.clone()).or_insert(blob); + kept.insert((f.family, f.style), key); + } + kept + } +} + +/// The type among `nodes` (and in their groups) shown in fonts the file carries ([`mark`]), in the +/// families and styles `kept` holds fonts for (family and style → the font's blob in `images`): +/// drawn in them while its text is the file's, and laid out again for its bounds. Type in a font +/// the file only names keeps the fallback font, also where its family and style are the same. +pub(crate) fn keep_file_fonts(nodes: &mut [Arc], kept: &HashMap<(String, String), String>, images: &BTreeMap) { + if kept.is_empty() { + return; + } + let db = vectorcraft_text::FontDb::global(); + for n in nodes.iter_mut() { + if n.children().is_some_and(|c| !c.is_empty()) + && let Some(children) = Arc::make_mut(n).children_mut() + { + keep_file_fonts(children, kept, images); + } + let NodeKind::Text(t) = &n.kind else { continue }; + if t.file_fonts.is_none() { + continue; + } + let mut fonts: Vec = vec![]; + for r in &t.runs { + let (family, style) = (&r.style.font_family, &r.style.font_style); + if let Some(key) = kept.get(&(family.clone(), style.clone())) + && !fonts.iter().any(|f| f.family == *family && f.style == *style) + { + fonts.push(FileFont { family: family.clone(), style: style.clone(), key: key.clone() }); + } + } + if let NodeKind::Text(t) = &mut Arc::make_mut(n).kind { + if fonts.is_empty() { + t.file_fonts = None; + continue; + } + t.file_fonts = Some(Box::new(FileFonts::new(fonts, &t.plain_text()))); + db.bind_file_fonts(t, |key| images.get(key)); + t.cached_bounds = Some(vectorcraft_text::layout(db, t).bounds); + } + } +} + +/// Mark type `t` as shown in a font the file carries, so that [`keep_file_fonts`] gives it the font +/// kept for its family and style (the key is filled in then). +pub(crate) fn mark(t: &mut vectorcraft_doc::TextObject) { + let fonts = t.runs.first().map(|r| FileFont { family: r.style.font_family.clone(), style: r.style.font_style.clone(), key: String::new() }); + t.file_fonts = Some(Box::new(FileFonts::new(fonts.into_iter().collect(), &t.plain_text()))); +} + +#[cfg(test)] +mod tests { + use super::*; + use kurbo::Shape; + + fn glyph(ch: char) -> FileGlyph { + FileGlyph { ch, outline: kurbo::Rect::new(0.0, 0.0, 400.0, 500.0).to_path(0.1), advance: 600.0 } + } + + /// A font full of glyphs takes no new character, so a string that needs one doesn't fit (it + /// comes in as outlines rather than as type the kept font can't draw); its own characters + /// still fit. + #[test] + fn a_full_font_takes_no_new_character() { + let mut g = FileFontGlyphs::default(); + let f = g.font("F", "Regular", FileFontInfo::default); + let chars: Vec = (0x10000u32..).filter_map(char::from_u32).take(MAX_FILE_GLYPHS).collect(); + for &c in &chars { + g.add(f, glyph(c)); + } + assert!(g.fits(f, &[glyph(chars[0]), glyph(chars[1])])); + assert!(!g.fits(f, &[glyph(chars[0]), glyph('A')])); + } + + /// A long string of one character compares each glyph with that character's once, not with + /// every one before it: a quarter of a million of them fit at once. + #[test] + fn a_long_string_of_one_character_fits_in_linear_time() { + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let mut g = FileFontGlyphs::default(); + let f = g.font("F", "Regular", FileFontInfo::default); + tx.send(g.fits(f, &vec![glyph('A'); 250_000])).ok(); + }); + assert_eq!(rx.recv_timeout(std::time::Duration::from_secs(20)), Ok(true)); + } +} diff --git a/crates/eps/src/import/graphics/state.rs b/crates/eps/src/import/graphics/state.rs index 489f675bf4..be6a74392e 100644 --- a/crates/eps/src/import/graphics/state.rs +++ b/crates/eps/src/import/graphics/state.rs @@ -152,6 +152,9 @@ pub(crate) struct Out { pub(super) tilings: HashMap>, /// How deep art drawn apart (a pattern's cell, a Type 3 glyph) is nested. pub apart: u32, + /// The glyphs of fonts the file carries for families that aren't available, gathered for the + /// fonts kept with the document (see `file_fonts`). + pub file_glyphs: super::super::file_fonts::FileFontGlyphs, } fn sane(r: Rect) -> bool { @@ -201,6 +204,7 @@ impl Out { shadings: HashSet::new(), tilings: HashMap::new(), apart: 0, + file_glyphs: Default::default(), } } diff --git a/crates/eps/src/import/tests.rs b/crates/eps/src/import/tests.rs index cf0e890f38..0ba6c600d5 100644 --- a/crates/eps/src/import/tests.rs +++ b/crates/eps/src/import/tests.rs @@ -936,7 +936,7 @@ fn device_settings_are_accepted_and_change_nothing() { /// `warnings` without the note naming fonts that aren't available: which those are depends on the /// fonts installed where the tests run, not on the program. pub(super) fn program_warnings(warnings: &[String]) -> Vec<&String> { - warnings.iter().filter(|w| !w.starts_with(super::MISSING_FONTS_NOTE)).collect() + warnings.iter().filter(|w| !w.starts_with(super::MISSING_FONTS_NOTE) && !w.starts_with(super::CARRIED_FONTS_NOTE)).collect() } fn blue(body: &str) { diff --git a/crates/eps/src/import/tests_images.rs b/crates/eps/src/import/tests_images.rs index ac3b5a369a..a9385f8eff 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -552,29 +552,153 @@ fn tiff_predicted_rows_at_every_depth() { assert!(wrong.is_empty(), "{wrong:#?}"); } -/// An image too large to read is left out, and its data is skipped, as reading it would leave -/// the program: the art after it is read, not the data as PostScript. Here the data ends at its -/// `~>` (an inline image of a content stream run as a file, as PDF-reading prologs write it), at -/// a `SubFileDecode` end string, and at the end of compressed data that is read whole. +/// An image over the reader's pixel cap is read at a lower resolution, or when its data is too +/// large to hold left out with its data skipped; either way the program goes on after the data, +/// as reading the whole image would leave it: the art after it is read, not the data as +/// PostScript. Here the data ends at its `~>` (an inline image of a content stream run as a file, +/// as PDF-reading prologs write it), at a `SubFileDecode` end string, and at the end of +/// compressed data that is read whole. #[test] fn the_data_of_an_image_too_large_to_read_is_skipped() { let after = "0 0 1 setrgbcolor 10 10 80 80 rectfill"; + let packed = crate::ps::ascii85(&crate::ps::deflate(&[0u8; 64])); for program in [ format!( "/ID {{ << /ImageType 1 /Width 10000 /Height 10000 /BitsPerComponent 8 /Decode [0 1 0 1 0 1] /ImageMatrix [1 0 0 1 0 0] \ - /DataSource currentfile 0 (~>) /SubFileDecode filter /ASCII85Decode filter /LZWDecode filter >> \ + /DataSource currentfile 0 (~>) /SubFileDecode filter /ASCII85Decode filter /FlateDecode filter >> \ /DeviceRGB setcolorspace image }} def\n\ - currentfile 0 (endstream) /SubFileDecode filter cvx exec\nID\nJ1_V7fG\"r'\"b]2#:hXAd)~>\n{after}\nendstream\n" + currentfile 0 (endstream) /SubFileDecode filter cvx exec\nID\n{packed}\n{after}\nendstream\n" ), format!("10000 10000 8 [1 0 0 1 0 0] currentfile /ASCIIHexDecode filter false 3 colorimage\n0a1b 2c3d 4e5f>\n{after}"), format!( - "10000 10000 8 [1 0 0 1 0 0] currentfile 0 (%%EndData) /SubFileDecode filter /FlateDecode filter image\n\ - x\u{9c}garbage\n%%EndData\n{after}" + "10000 10000 8 [1 0 0 1 0 0] currentfile 0 (%%EndData) /SubFileDecode filter /ASCII85Decode filter /FlateDecode filter image\n\ + {packed}\n%%EndData\n{after}" ), + format!("10000 10000 true [1 0 0 1 0 0] currentfile /ASCII85Decode filter imagemask\n{packed}\n{after}"), + ] { + let r = read(&program); + assert!(r.warnings.iter().any(|w| w.contains("too large to read") || w.contains("lower resolution")), "{program}: {:?}", r.warnings); + let o = super::tests::objects(&r.document); + let last = o.last().expect("the art after the image"); + assert_eq!(super::tests::fill(last), Some(&vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))), "{program}"); + } +} + +/// An image of more pixels than the reader's cap (2^26) is read at a lower resolution, every +/// second sample of every second row here, over the same area, with a note; not left out. +#[test] +fn an_image_over_the_pixel_cap_is_read_at_a_lower_resolution() { + // 9000 × 8000 one-bit samples, every row the same: its left half ones, painted. + let row = format!("{}{}", "ff".repeat(563), "00".repeat(562)); + let r = read(&format!("0 0 1 setrgbcolor 90 80 scale 9000 8000 true [9000 0 0 -8000 0 8000] <{row}> imagemask")); + assert!(r.warnings.iter().any(|w| w.contains("lower resolution")), "{:?}", r.warnings); + let NodeKind::Image(im) = &all(&r.document).into_iter().find(|n| matches!(n.kind, NodeKind::Image(_))).expect("an image").kind else { + panic!("an image") + }; + assert_eq!((im.width, im.height), (4500, 4000)); + // Its 4500 × 4000 pixels cover the 90 × 80 points the image does. + let corner = im.xf * kurbo::Point::new(4500.0, 4000.0); + let origin = im.xf * kurbo::Point::ZERO; + assert!(((corner - origin).x.abs() - 90.0).abs() < 1e-6 && ((corner - origin).y.abs() - 80.0).abs() < 1e-6, "{:?}", im.xf); + // Left half painted, right half clear. + assert_eq!(pixel(&r.document, 100, 2000)[3], 255); + assert_eq!(pixel(&r.document, 4400, 2000)[3], 0); +} + +/// An image over the pixel cap whose samples are more data than the reader holds (9500 × 9500 +/// RGB is 270 MB) is read at a lower resolution too when Flate or LZW compresses it last: only +/// the rows it reads are kept as they are decoded. +#[test] +fn an_image_of_more_data_than_the_reader_holds_keeps_only_the_rows_it_reads() { + let (w, h) = (9500usize, 9500usize); + let mut samples = Vec::with_capacity(w * h * 3); + for y in 0..h { + let px: [u8; 3] = if y < h / 2 { [255, 0, 0] } else { [0, 0, 255] }; + samples.extend(std::iter::repeat_n(px, w).flatten()); + } + let data = crate::ps::ascii85(&crate::ps::deflate(&samples)); + drop(samples); + let r = read(&format!( + "95 95 scale {w} {h} 8 [{w} 0 0 -{h} 0 {h}] currentfile /ASCII85Decode filter /FlateDecode filter false 3 colorimage\n{data}\n\ + 0 1 0 setrgbcolor 0 0 0.1 0.1 rectfill" + )); + assert!(r.warnings.iter().any(|w| w.contains("lower resolution")), "{:?}", r.warnings); + let NodeKind::Image(im) = &all(&r.document).into_iter().find(|n| matches!(n.kind, NodeKind::Image(_))).expect("an image").kind else { + panic!("an image") + }; + assert_eq!((im.width, im.height), (4750, 4750)); + // The rows read from the top half are red, from the bottom half blue. + assert_eq!(pixel(&r.document, 10, 10), [255, 0, 0, 255]); + assert_eq!(pixel(&r.document, 10, 4740), [0, 0, 255, 255]); + // The art after the data is read. + assert_eq!(super::tests::objects(&r.document).len(), 2); +} + +/// An image too large to read even at a lower resolution (its samples are more data than the +/// reader holds) is left out, and its data is skipped: when a procedure reads it, the procedure +/// is called until the data ends; when its first filter decompresses to more than the reader +/// holds (and can't be read a row at a time), the compressed data is measured without keeping it. +#[test] +fn the_data_of_an_image_too_large_to_hold_is_skipped() { + let after = "0 0 1 setrgbcolor 10 10 80 80 rectfill"; + let zeros = crate::ps::deflate(&vec![0u8; 300 << 20]); + // Predicted rows aren't decoded a row at a time: such an image is left out. + let mut flate = + b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /FlateDecode filter false 3 colorimage\n".to_vec(); + flate.extend(&zeros); + flate.extend(format!("\n{after}").as_bytes()); + for program in [ format!( - "10000 10000 true [1 0 0 1 0 0] currentfile /ASCII85Decode filter imagemask\n{}\n{after}", - crate::ps::ascii85(&crate::ps::deflate(&[0u8; 64])) - ), + "/F currentfile 0 (%%EndData) /SubFileDecode filter def \ + 10000 10000 8 [1 0 0 1 0 0] {{ F 4096 string readstring pop }} false 3 colorimage\n@@@@ not PostScript @@@@\n%%EndData\n{after}" + ) + .into_bytes(), + flate, + ] { + let text = String::from_utf8_lossy(program.get(..120).unwrap_or(&program)).into_owned(); + let mut file = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec(); + file.extend(&program); + file.extend(b"\nshowpage\n%%EOF\n"); + let r = import(&file).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("too large to read")), "{text}: {:?}", r.warnings); + let o = super::tests::objects(&r.document); + assert_eq!(o.len(), 1, "{text}: {:?}", r.warnings); + assert_eq!(super::tests::fill(&o[0]), Some(&vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))), "{text}"); + } +} + +/// Measuring the data of an image too large to hold decompresses it, and that is charged to the +/// operation budget: a program kept in a reusable stream, whose image over 300 MB of compressed +/// zeros is left out and measured again each time a loop runs the stream from its start, runs out +/// of the budget. +#[test] +fn measuring_data_too_large_to_hold_in_a_loop_runs_out_of_the_budget() { + let mut program = + b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /FlateDecode filter false 3 colorimage\n".to_vec(); + program.extend(crate::ps::deflate(&vec![0u8; 300 << 20])); + let hex: String = program.iter().map(|b| format!("{b:02x}")).collect(); + super::tests::runs_out_of_budget(&format!("/P <{hex}> /ReusableStreamDecode filter def {{ P 0 setfileposition P cvx exec }} loop")); +} + +/// When an image too large to read is left out, the data of its mask (`InterleaveType` 3) is +/// skipped too: unfiltered from the program's own file by its byte count, and through a filter +/// shared with later reads, which then find the file past the data (here the second filter fails +/// on what the first decoded) rather than decoding the program after it. +#[test] +fn the_mask_data_of_an_image_left_out_is_skipped() { + let after = "0 0 1 setrgbcolor 10 10 80 80 rectfill"; + let masked = |source: &str| { + format!( + "<< /ImageType 3 /InterleaveType 3 /DataDict << /ImageType 1 /Width 10000 /Height 10000 /BitsPerComponent 8 \ + /Decode [0 1 0 1 0 1] /ImageMatrix [1 0 0 1 0 0] /DataSource (x) >> \ + /MaskDict << /ImageType 1 /Width 10 /Height 10 /BitsPerComponent 1 /Decode [0 1] /ImageMatrix [1 0 0 1 0 0] \ + /DataSource {source} >> >> /DeviceRGB setcolorspace image" + ) + }; + for program in [ + // 10 rows of 2 bytes, not PostScript. + format!("{}\n{}\n{after}", masked("currentfile"), "@".repeat(20)), + format!("/F currentfile /ASCIIHexDecode filter /ASCII85Decode filter def {}\n7676>\nF read {{ pop }} if {after}", masked("F")), ] { let r = read(&program); assert!(r.warnings.iter().any(|w| w.contains("too large to read")), "{program}: {:?}", r.warnings); diff --git a/crates/eps/src/import/tests_type1.rs b/crates/eps/src/import/tests_type1.rs index 5399042908..21ff20abec 100644 --- a/crates/eps/src/import/tests_type1.rs +++ b/crates/eps/src/import/tests_type1.rs @@ -138,8 +138,136 @@ fn type_in_fonts_that_arent_available_is_named_in_a_warning() { /Nowhere-Bold 12 selectfont 10 80 moveto (x) show /Inter-Regular 12 selectfont 10 90 moveto (y) show", ); assert_eq!(texts(&r).iter().map(|t| t.runs[0].style.font_family.as_str()).collect::>(), ["Test One", "Test One", "Nowhere", "Inter"]); - // PDF import's words. - assert_eq!(r.warnings, ["fonts that aren't available show in the fallback font until they are: Test One, Nowhere"]); + // PDF import's words: the font the file carries draws its type, the one it only names doesn't. + assert_eq!( + r.warnings, + [ + "fonts that aren't available show as the file draws them, in the fonts it carries, until their text is edited (then in the fallback font): Test One", + "fonts that aren't available show in the fallback font until they are: Nowhere", + ] + ); + // A font found by name keeps no glyphs of the file's: it shows in the fallback font, as before. + assert!(texts(&r).iter().filter(|t| t.runs[0].style.font_family != "Test One").all(|t| t.file_fonts.is_none())); +} + +/// The glyphs of type laid out in the document's fonts: each one's outline (text space) and origin, +/// and whether a font the file carries draws it. +fn laid_out(t: &TextObject) -> Vec<(vectorcraft_geom::Rect, f64, bool)> { + use kurbo::Shape; + let db = vectorcraft_text::FontDb::global(); + vectorcraft_text::layout(db, t).glyphs.iter().map(|g| (g.outline.bounding_box(), g.origin.x, db.is_file_font(g.font_id))).collect() +} + +/// Type in a Type 1 font the file carries, whose family isn't available, is drawn with the file's +/// glyphs, as PDF import keeps a PDF's fonts (#4568): A the square and B the triangle, at the +/// font's own advances (no tracking makes up for a stand-in's), not in the fallback font. +#[test] +fn embedded_type1_type_draws_with_the_files_glyphs() { + let r = program(OWN, false, "/TestOne findfont 50 scalefont setfont 10 20 moveto (AB) show"); + let t = &texts(&r)[0]; + assert!(t.file_fonts.is_some(), "{:?}", r.warnings); + let glyphs = laid_out(t); + assert_eq!(glyphs.len(), 2); + assert!(glyphs.iter().all(|g| g.2), "every glyph the file's: {glyphs:?}"); + // The square is 400 by 500 units, the triangle 500 by 400, at 50 points an em. + let (a, b) = (glyphs[0].0, glyphs[1].0); + assert!((a.width() - 20.0).abs() < 0.05 && (a.height() - 25.0).abs() < 0.05, "{a:?}"); + assert!((b.width() - 25.0).abs() < 0.05 && (b.height() - 20.0).abs() < 0.05, "{b:?}"); + // B starts where A's 600 units end, with no tracking. + assert!((glyphs[1].1 - glyphs[0].1 - 30.0).abs() < 0.05, "{glyphs:?}"); + assert!(t.runs.iter().all(|r| r.style.tracking == 0.0), "{:?}", t.runs); +} + +/// A family whose regular style the file carries but whose bold it only names: the regular is +/// drawn in the kept font and the bold in the fallback font, and the warning says both. +#[test] +fn a_carried_style_leaves_a_named_style_of_its_family_in_the_fallback_warning() { + let r = program(OWN, false, "/TestOne findfont 50 scalefont setfont 10 20 moveto (A) show /TestOne-Bold 12 selectfont 10 80 moveto (x) show"); + assert_eq!(texts(&r).iter().map(|t| t.runs[0].style.font_style.as_str()).collect::>(), ["Regular", "Bold"]); + assert_eq!( + r.warnings, + [ + "fonts that aren't available show as the file draws them, in the fonts it carries, until their text is edited (then in the fallback font): Test One", + "fonts that aren't available show in the fallback font until they are: Test One", + ] + ); +} + +/// Type in a font the file only names keeps the fallback font, and the spacing set for it, also +/// when its family and style are those of a font the file carries (`TestOne-Roman` beside the +/// embedded `TestOne`): only type shown in the carried font gets the font kept from it. +#[test] +fn a_named_font_in_a_carried_family_and_style_keeps_the_fallback_font() { + let r = program(OWN, false, "/TestOne findfont 50 scalefont setfont 10 20 moveto (A) show /TestOne-Roman 50 selectfont 10 60 moveto (AA) show"); + let t = texts(&r); + assert_eq!(t.len(), 2, "{:?}", all(&r.document)); + assert_eq!((t[1].runs[0].style.font_family.as_str(), t[1].runs[0].style.font_style.as_str()), ("Test One", "Regular")); + assert!(t[0].file_fonts.is_some()); + assert!(t[1].file_fonts.is_none(), "the named font's type isn't drawn in the carried font"); + // The warning says so for each: one drawn as the file draws it, one in the fallback font. + assert_eq!( + r.warnings, + [ + "fonts that aren't available show as the file draws them, in the fonts it carries, until their text is edited (then in the fallback font): Test One", + "fonts that aren't available show in the fallback font until they are: Test One", + ] + ); +} + +/// A character the file draws with a different glyph from the one the kept font already has for +/// it (here a second font of the same name whose A is a narrower square) can't go in that font: +/// that string comes in as outlines, the first stays type in the file's glyphs. +#[test] +fn a_second_glyph_for_a_character_keeps_its_type_as_outlines() { + let narrow = cs(&[(&[0, 600], 13), (&[100, 0], 21), (&[200, 0], 5), (&[0, 500], 5), (&[-200, 0], 5), (&[], 9), (&[], 14)]); + let head = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec(); + let file = [ + head, + font(OWN, false), + b"/TestOne findfont 50 scalefont setfont 10 20 moveto (A) show\n".to_vec(), + font_with(OWN, false, &[], Some(narrow)), + b"/TestOne findfont 50 scalefont setfont 10 60 moveto (A) show\nshowpage\n%%EOF\n".to_vec(), + ] + .concat(); + let r = import(&file).unwrap(); + let t = texts(&r); + assert_eq!(t.len(), 1, "{:?}", all(&r.document)); + assert!(laid_out(&t[0]).iter().all(|g| g.2)); + let paths: Vec<_> = all(&r.document).iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).map(|n| bounds(n)).collect(); + assert!(paths.iter().any(|b| (b.width() - 10.0).abs() < 0.05 && (b.height() - 25.0).abs() < 0.05), "the narrow A as outlines: {paths:?}"); +} + +/// The type opened in the app keeps the file's glyphs through a save and a reopen, takes the +/// fallback font once its text is edited, and gets the file's glyphs back on undo, as PDF type in +/// a font the file carries does. +#[test] +fn kept_type1_glyphs_survive_saving_and_go_when_the_text_is_edited() { + use vectorcraft_testkit::{Session, json}; + let head = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec(); + let file = [head, font(OWN, false), b"/TestOne findfont 50 scalefont setfont 10 20 moveto (AB) show\nshowpage\n%%EOF\n".to_vec()].concat(); + let mut s = Session::new(); + let opened = s.execute("document.open", &json!({"name": "kept.eps", "dataBase64": vectorcraft_testkit::format::base64_encode(&file)})).unwrap(); + assert!(opened["warnings"].to_string().contains("until their text is edited"), "{opened}"); + let carried = |s: &Session| { + let (mut glyphs, mut id) = (vec![], None); + s.doc().unwrap().doc.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + glyphs.extend(laid_out(t).into_iter().map(|g| g.2)); + id = Some(n.id); + } + }); + (glyphs, id) + }; + let (glyphs, id) = carried(&s); + assert_eq!(glyphs, [true, true]); + let native = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].as_str().unwrap().to_string(); + s.execute("document.open", &json!({"name": "kept.vectorcraft", "dataBase64": native})).unwrap(); + assert_eq!(carried(&s).0, [true, true], "saved and opened again"); + let id = carried(&s).1.or(id).unwrap(); + s.execute("text.setText", &json!({"id": id, "text": "ABA"})).unwrap(); + assert!(carried(&s).0.iter().all(|g| !g), "edited: the fallback font"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(carried(&s).0, [true, true], "undone: the file's glyphs again"); } #[test] diff --git a/crates/eps/src/import/tests_type42.rs b/crates/eps/src/import/tests_type42.rs index 21399afe70..c09ae2589e 100644 --- a/crates/eps/src/import/tests_type42.rs +++ b/crates/eps/src/import/tests_type42.rs @@ -111,6 +111,22 @@ fn the_fonts_own_widths_space_its_type_and_move_the_point() { check("newpath 10 20 moveto (\\001) true charpath pathbbox exch pop sub abs 25 gt exch 10 sub abs 8 lt and".into()); } +/// Type in a Type 42 font the file carries, whose family (Plain42) isn't available, is drawn +/// with the file's glyphs kept with the document, spaced by their own widths, as a Type 1 font's +/// is (see `tests_type1`). +#[test] +fn type_in_a_carried_type42_font_draws_with_the_files_glyphs() { + let (h, wh) = glyph('H'); + let (i, _) = glyph('I'); + let r = read(&format!("{} /Plain42 findfont 50 scalefont setfont 10 20 moveto (\\001\\002) show", font(&[h, i]))); + let t = &texts(&r)[0]; + assert!(t.file_fonts.is_some(), "{:?}", r.warnings); + let db = vectorcraft_text::FontDb::global(); + assert!(vectorcraft_text::layout(db, t).glyphs.iter().all(|g| db.is_file_font(g.font_id))); + let o = origins(t); + assert!((o[1] - o[0] - 50.0 * wh).abs() < 0.05, "{o:?}"); +} + /// `xshow` and `ashow` put each character where they say: the type's tracking makes up the /// difference from its font's advances. #[test] diff --git a/crates/eps/src/import/text.rs b/crates/eps/src/import/text.rs index 3de16d7bbf..eff4f8b20e 100644 --- a/crates/eps/src/import/text.rs +++ b/crates/eps/src/import/text.rs @@ -9,7 +9,7 @@ use vectorcraft_color::Paint; use vectorcraft_doc::{CharStyle, Node, NodeId, NodeKind, TextObject}; use vectorcraft_geom::{Affine, Point, Vec2}; -use vectorcraft_text::TextLayout; +use vectorcraft_text::{FileFontInfo, FileGlyph, TextLayout}; use super::cid::Base; use super::graphics::MAX_APART; @@ -675,6 +675,17 @@ impl Interp<'_> { { return self.show_type42_outlines(data, glyphs, s, spacing, at, f1); } + // Type in a font the file carries whose family isn't available is drawn in a font made of + // the file's glyphs (see `file_fonts`), spaced by their own advances. A character whose + // glyph differs from the one that font has for it keeps the string as outlines. + let kept = match &plain { + Some((data, glyphs)) => match self.keep_file_glyphs(data, glyphs)? { + Some(true) => true, + Some(false) => return self.show_type42_outlines(data, glyphs, s, spacing, at, f1), + None => false, + }, + None => false, + }; // Each code's character, if it has one that shows (control codes don't). let chars = match &plain { Some((_, glyphs)) => glyphs.iter().map(|g| g.ch).collect::>(), @@ -685,7 +696,49 @@ impl Interp<'_> { codes.push(u32::from(code), c.filter(|c| !c.is_control())); } let widths: Option> = plain.map(|(_, glyphs)| glyphs.iter().map(|g| g.width).collect()); - self.show_codes(&codes, widths.as_deref(), spacing, false, s, Draw::Fill) + self.show_codes(&codes, widths.as_deref().map(|of| Widths { of, kept }), spacing, false, s, Draw::Fill) + } + + /// The glyphs of codes `glyphs` in font program `data` (the current font's) gathered for the + /// font kept from the file for their family and style, when that family isn't available and + /// the type shows: `Some(true)` gathered, `Some(false)` a character's glyph differs from the + /// one that font has for it, `None` not kept (the family is available, the type draws nothing + /// or is drawn apart, or a glyph can't be read). + fn keep_file_glyphs(&mut self, data: &Embedded, glyphs: &[Plain]) -> Res> { + if self.g.paint.is_none() || self.g.null || self.out.apart > 0 { + return Ok(None); + } + let (name, _) = self.font()?; + let (family, style) = family_style(&name); + if family.is_empty() || vectorcraft_text::FontDb::global().find_family(&family).is_some() { + return Ok(None); + } + let mut file = Vec::with_capacity(glyphs.len()); + for g in glyphs { + let Some(ch) = g.ch.filter(|c| !c.is_control()) else { continue }; + let Some((outline, advance)) = data.glyph(g.gid) else { return Ok(None) }; + self.spend(data.take_work())?; + // Ems, y up, onto thousandths of an em. + file.push(FileGlyph { ch, outline: Affine::scale(1000.0) * outline, advance: advance * 1000.0 }); + } + if file.is_empty() { + return Ok(None); + } + let postscript = match name.split_once('+') { + Some((tag, rest)) if tag.len() == 6 && tag.bytes().all(|b| b.is_ascii_uppercase()) => rest.to_string(), + _ => name.clone(), + }; + let (fs_type, metrics) = data.facts(); + let (ascent, descent) = metrics.unwrap_or_default(); + let info = || FileFontInfo { family: family.clone(), style: style.clone(), postscript, ascent, descent, fs_type }; + let font = self.out.file_glyphs.font(&family, &style, info); + if !self.out.file_glyphs.fits(font, &file) { + return Ok(Some(false)); + } + for g in file { + self.out.file_glyphs.add(font, g); + } + Ok(Some(true)) } /// The codes `codes` (each standing for some of its characters, or none) shown in the current @@ -698,12 +751,14 @@ impl Interp<'_> { fn show_codes>( &mut self, codes: &Decoded, - widths: Option<&[f64]>, + widths: Option, spacing: &Spacing, vertical: bool, kern: &[C], draw: Draw, ) -> Res { + let kept = widths.is_some_and(|w| w.kept); + let widths = widths.map(|w| w.of); let at = self.user_point()?; let (_, f1) = self.font()?; let text = &codes.text; @@ -717,6 +772,17 @@ impl Interp<'_> { *n += g.advance; } } + if kept && let Some(widths) = widths { + let mut k = 0; + for (i, &(_, n)) in codes.codes.iter().enumerate() { + if n == 1 + && let Some(slot) = natural.get_mut(k) + { + *slot = widths.get(i).copied().unwrap_or(0.0) * size; + } + k += n; + } + } // Each code's move (user space) and that move in text space, along the baseline (down the // column) and across. let em = |x: f64| f1 * if vertical { Point::new(0.0, -x) } else { Point::new(x, 0.0) } - f1 * Point::ZERO; @@ -757,10 +823,13 @@ impl Interp<'_> { for ((d, ..), &(_, n)) in moves.iter().zip(&codes.codes) { let c: String = chars.by_ref().take(n).collect(); if painted && !c.trim().is_empty() { - let (t, ..) = self.set_text_in(&c, pen, vertical)?; + let (mut t, ..) = self.set_text_in(&c, pen, vertical)?; if draw == Draw::Path { self.type_path(&t)?; } else { + if kept { + super::file_fonts::mark(&mut t); + } let clips = self.g.clips.clone(); self.out.push(Node::new(NodeId(0), NodeKind::Text(Box::new(t))), &clips); } @@ -814,6 +883,9 @@ impl Interp<'_> { if draw == Draw::Path { self.type_path(&t)?; } else { + if kept { + super::file_fonts::mark(&mut t); + } let clips = self.g.clips.clone(); if self.out.push(Node::new(NodeId(0), NodeKind::Text(Box::new(t))), &clips).is_some() && let Some(after) = self.out.drawn.get_mut(start..) @@ -1328,7 +1400,7 @@ impl Interp<'_> { }; let saved = self.g.font.replace(named.font.clone()); let before = std::mem::replace(&mut self.kshow_font, saved.clone()); - let r = self.show_codes(&named.codes, widths.as_deref(), spacing, named.vertical, &kern, draw); + let r = self.show_codes(&named.codes, widths.as_deref().map(|of| Widths { of, kept: false }), spacing, named.vertical, &kern, draw); self.kshow_font = before; self.g.font = saved; r @@ -1675,6 +1747,15 @@ impl Interp<'_> { } } +/// The widths of the codes [`Interp::show_codes`] shows (glyph space, one unit an em). With +/// `kept`, the type is drawn in a font kept from the file whose glyphs are that wide (see +/// `file_fonts`), so they are its characters' advances, not the layout's. +#[derive(Clone, Copy)] +struct Widths<'a> { + of: &'a [f64], + kept: bool, +} + /// A character code of a font carrying its program: the character it stands for (`None` when /// neither its glyph name nor the font says), its glyph and the glyph's width (ems). struct Plain { diff --git a/crates/eps/src/import/type1.rs b/crates/eps/src/import/type1.rs index 3000077721..7e411d8707 100644 --- a/crates/eps/src/import/type1.rs +++ b/crates/eps/src/import/type1.rs @@ -51,6 +51,21 @@ impl Embedded { } } + /// What the font program says of its licence (OS/2 `fsType`) and its ascent and descent + /// (thousandths of an em, the descent negative): a TrueType font's tables. A Type 1 font + /// says neither. + pub fn facts(&self) -> (Option, Option<(f64, f64)>) { + use skrifa::MetadataProvider; + use skrifa::raw::TableProvider; + let Self::TrueType(f) = self else { return (None, None) }; + let Ok(font) = skrifa::FontRef::new(&f.data) else { return (None, None) }; + let fs_type = font.os2().ok().map(|o| o.fs_type()); + let m = font.metrics(skrifa::instance::Size::unscaled(), skrifa::instance::LocationRef::default()); + let k = 1000.0 / f64::from(m.units_per_em.max(1)); + let (ascent, descent) = (f64::from(m.ascent) * k, f64::from(m.descent) * k); + (fs_type, (ascent.is_finite() && descent.is_finite() && ascent > 0.0 && descent <= 0.0).then_some((ascent, descent))) + } + /// The character glyph `gid` stands for, when the font says (a TrueType font's character /// map or `post` names; a Type 1 glyph's name). pub fn char_of(&self, gid: u32) -> Option { diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index abd72b255e..5916f6fb21 100644 --- a/crates/geom/src/path.rs +++ b/crates/geom/src/path.rs @@ -444,6 +444,59 @@ impl SubPath { } true } + /// Bend segment `seg` as the arrow keys do: its anchors stay and its handles go where + /// [`Self::nudged_handles`] puts them. A handle that keeps its direction leaves a smooth anchor + /// smooth; one that flips or grows out of its anchor makes it a corner, so the segment beside + /// it stays as it is. False, with nothing changed, when the bend changes nothing. + pub fn nudge_segment(&mut self, seg: usize, dv: kurbo::Vec2) -> bool { + let Some((h_out, h_in)) = self.nudged_handles(seg, dv) else { return false }; + let n = self.anchors.len(); + // Turned when the new handle doesn't point the way the old one did. + let turned = |a: &Anchor, old: Point, new: Point| (old - a.p).dot(new - a.p) <= 0.0; + if let Some(a) = self.anchors.get_mut(seg % n) + && h_out != a.h_out + { + let independent = turned(a, a.h_out, h_out); + a.set_handle(true, h_out, independent); + } + if let Some(b) = self.anchors.get_mut((seg + 1) % n) + && h_in != b.h_in + { + let independent = turned(b, b.h_in, h_in); + b.set_handle(false, h_in, independent); + } + true + } + /// The outgoing handle at the start and the incoming one at the end that segment `seg` gets + /// from the arrow keys' step `dv`. Each handle keeps its direction and changes length in + /// proportion to `dv` projected onto that direction, so the curve bulges toward `dv`: the + /// middle of the curve moves by `dv`'s length along `dv`, or less when the handles point + /// mostly across it. A handle can shrink through its anchor and come out the other way. A + /// retracted handle takes the direction from its anchor to the other handle's end. `None` when + /// there is no such segment, it is a straight line, or both handles are at right angles to + /// `dv`, so nothing changes. + pub fn nudged_handles(&self, seg: usize, dv: kurbo::Vec2) -> Option<(Point, Point)> { + if seg >= self.segment_count() || self.segment_is_line(seg) { + return None; + } + let c = self.segment(seg); + let direction = |anchor: Point, handle: Point, other: Point| { + let dir = if handle.distance(anchor) > EPS { handle - anchor } else { other - anchor }; + let len = dir.hypot(); + if len > EPS { dir / len } else { kurbo::Vec2::ZERO } + }; + let (u0, u1) = (direction(c.p0, c.p1, c.p2), direction(c.p3, c.p2, c.p1)); + let (d0, d1) = (dv.dot(u0), dv.dot(u1)); + // Handles that change by k·d0 and k·d1 move the middle B(1/2) by 3/8·k·(d0·u0 + d1·u1), + // whose part along dv is 3/8·k·(d0² + d1²)/|dv|: one |dv| for k = 8/3·|dv|²/(d0² + d1²), + // kept to at most 8/3 so that handles nearly across dv don't grow without bound. + let sum = d0 * d0 + d1 * d1; + if sum <= EPS * EPS { + return None; + } + let k = 8.0 / 3.0 * (dv.hypot2() / sum).min(1.0); + Some((c.p1 + u0 * (k * d0), c.p2 + u1 * (k * d1))) + } /// Split segment `seg` at parameter `t`, inserting a new anchor. Returns the new anchor index. pub fn insert_anchor(&mut self, seg: usize, t: f64) -> usize { diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index e83d33c1a5..8d94e6b968 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -293,7 +293,13 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { let Some(callee) = h0.filter(|s| s.kind == T::Ident) else { return }; let n = callee.text; if is(h1, ".") { - let file = self.file_receiver(h2, h3); + let held = self.held_file(h2, h3); + // A Folder object whatever the path names has no File-only function: the call does not + // reach the file system. + if held == Some(true) && catalog::FILE_ONLY.contains(&n) { + return; + } + let file = held.is_some(); if n == catalog::MENU_COMMAND { self.pending = Pending::Menu(line); } else if n == catalog::OPEN && file { @@ -329,12 +335,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// Whether `receiver`, which `before` comes before, is a variable holding a File or Folder object /// (not a property of the same name), or a File or Folder object made in place or held in - /// grouping parentheses ([`Sig::file`]). - fn file_receiver(&self, receiver: Option>, before: Option>) -> bool { - self.held_file(receiver, before).is_some() - } - - /// What [`Self::file_receiver`] finds: `Some(true)` for a Folder object whatever the path names + /// grouping parentheses ([`Sig::file`]): `Some(true)` for a Folder object whatever the path names /// ([`Sig::folder`], [`Analyzer::folder`]), unless the file gives names values the analysis /// doesn't read ([`Analyzer::unsure`]), `Some(false)` for an object that may be a File object, and /// `None` for anything else. diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index 0045c764f2..82fd61084b 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -38,6 +38,8 @@ pub(crate) const FILE_SETTERS: &[&str] = &["length", "hidden", "readonly"]; pub(crate) const FILE_DIALOGS: &[&str] = &["openDialog", "saveDialog"]; pub(crate) const FOLDER_DIALOGS: &[&str] = &["selectDialog"]; pub(crate) const INSTANCE_DIALOGS: &[&str] = &["openDlg", "saveDlg", "selectDlg"]; +/// The functions of a File object that a Folder object does not have. +pub(crate) const FILE_ONLY: &[&str] = &["open", "read", "readch", "readln", "write", "writeln", "copy", "createAlias", "openDlg", "saveDlg"]; pub(crate) const FOLDER_PLACES: &[&str] = &["appData", "appPackage", "commonFiles", "current", "desktop", "myDocuments", "startup", "system", "temp", "trash", "userData"]; /// The `Folder` place a script can assign. diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 6985791fe1..fec22ed62d 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -593,6 +593,32 @@ fn setting_a_folders_length_or_flags_does_not_write() { assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[7, 9, 11, 13, 14, 15, 16][..])); } +/// A Folder object has none of the File object's `open`, `read`, `readch`, `readln`, `write`, +/// `writeln`, `copy`, `createAlias`, `openDlg` and `saveDlg`, so calling them on `new Folder(…)`, a +/// `Folder` place or a variable holding one reads, writes and asks nothing. On `Folder(…)`, which +/// gives a File object when the path names a file, and on `Folder.current` they still count, and the +/// Folder object's own `create`, `remove`, `getFiles` and `selectDlg` count on any of them. +#[test] +fn file_only_calls_on_a_folder_do_nothing() { + let r = report(concat!( + "var d = new Folder(p);\n", + "d.write(s); d.writeln(s); d.copy(q); d.createAlias(q);\n", + "d.open('w'); d.read(); d.readch(); d.readln();\n", + "Folder.temp.write(s); (new Folder(q)).copy(q);\n", + "d.openDlg(); Folder.desktop.saveDlg();\n", + "Folder(p).write(s);\n", + "Folder.current.copy(q);\n", + "d.create(); d.getFiles(); d.selectDlg();\n", + "var g = Folder(p); g.open('r');\n", + )); + let lines = |id: &str| feature(&r, id).map(|f| f.lines.clone()).unwrap_or_default(); + let outside: Vec<(&str, &[usize])> = r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect(); + assert_eq!(outside, [("filesWritten", &[6, 7, 8][..])]); + assert_eq!(lines("file.write"), [6, 7, 8]); + assert_eq!(lines("file.read"), [8, 9]); + assert_eq!(lines("file.dialog"), [8]); +} + /// A File object assigned to a function's own variable, its parameter or a `catch` block's /// parameter ends with them; one assigned to an outer variable stays. Such a variable or parameter /// starts without what the outer variable of the same name was assigned. diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index 1a37860179..bc0f822c06 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -284,6 +284,9 @@ pub struct ToolContext<'a> { /// General → Double Click To Isolate: a double-click on a group with the Selection tool /// isolates it. pub double_click_isolate: bool, + /// General → Double-Click Adds Anchor Points: a plain double-click on a path segment with Direct + /// Selection adds an anchor there. + pub double_click_adds_anchor: bool, /// Selection & Anchor Display → Command Click to Select Objects Behind: Cmd/Ctrl-click with the /// Selection tool selects the object under the selected one, the next click the one under /// that. diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index b3efac86bb..15c2f354d4 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -863,6 +863,31 @@ fn segment_at(cx: &ToolContext, id: NodeId, p: Point) -> Option { Some(SegmentHit { si, seg, t, curved: a.has_out() || b.has_in() }) } +/// With General › Double-Click Adds Anchor Points on, a plain +/// double-click on a path segment adds an anchor there, the new anchor alone selected. The path is +/// the one whose stroke or outline a press at `p` hits, a clipping path included. An anchor or a +/// center point under the pointer comes first, so nothing is added (the caller has already given +/// way to the handles, mesh points and blend spine points a press takes first). The path's own +/// line must pass within the pick tolerance of `p`: a click on a wide stroke or on the drawn +/// outline of an effect farther from the path adds nothing. +fn add_anchor_at(cx: &ToolContext, ev: &PointerEvent, p: Point) -> Option { + let m = ev.mods; + if !cx.double_click_adds_anchor || m.shift || m.alt || m.cmd || m.ctrl { + return None; + } + let (tol, point) = (cx.pick_tol(), cx.point_tol()); + if hit_anchor(cx, p, point).is_some() || hit_center(cx, p, point).is_some() { + return None; + } + let h = hit_test(cx.doc, p, cx.selection_hit_options()).filter(|h| matches!(h.kind, HitKind::Stroke | HitKind::Outline))?; + let id = cx.doc.node(h.leaf).and_then(|n| compound_part_at(n, p, tol)).unwrap_or(h.leaf); + if !cx.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. })) { + return None; + } + let (id, si, seg, t) = crate::draw2::segment_in(cx, [id], p, tol)?; + Some(Action::Exec("path.insertAnchor".into(), json!({"id": id.0, "subpath": si, "segment": seg, "t": t, "selectAnchor": true}))) +} + impl Tool for DirectSelectionTool { /// The pointer hovers nothing for the tool: no bracket is highlighted. fn hover_ended(&mut self, _cx: &ToolContext) { @@ -1484,6 +1509,9 @@ impl DirectSelectionTool { if crate::rulerguide::guide_at(cx, p).is_some() { return vec![]; } + if let Some(a) = add_anchor_at(cx, ev, p).filter(|_| !self.takes_point(cx, p)) { + return vec![a]; + } // A double-click edits what is drawn: not a clipping path's outline. let hit = hit_test(cx.doc, p, cx.hit_options()); if hit.as_ref().and_then(|h| cx.doc.node(h.leaf)).is_some_and(|n| matches!(n.kind, NodeKind::Text(_))) { diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index 8b0983ba52..a39bf3766f 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -1355,6 +1355,110 @@ fn a_double_click_outside_isolation_leaves_it() { assert!(DirectSelectionTool::new(false).pointer(&cx(&d, &none, &p), &PointerEvent::new(PointerKind::DoubleClick, 700.0, 700.0)).is_empty()); } +/// The anchor a Direct Selection double-click at `at` adds: (path, subpath, segment, t). +fn double_click_adds(cx: &ToolContext, at: (f64, f64), mods: Mods) -> Option<(u64, usize, usize, f64)> { + let a = DirectSelectionTool::new(false).pointer(cx, &PointerEvent::new(PointerKind::DoubleClick, at.0, at.1).with_mods(mods)); + a.iter().find_map(|a| match a { + Action::Exec(c, p) if c == "path.insertAnchor" => { + assert_eq!(p["selectAnchor"], true, "the new anchor is selected: {p}"); + Some((p["id"].as_u64()?, p["subpath"].as_u64()? as usize, p["segment"].as_u64()? as usize, p["t"].as_f64()?)) + } + _ => None, + }) +} + +/// With General › Double-Click Adds Anchor Points on, a plain +/// Direct Selection double-click on a segment of a selected or unselected path adds an anchor at +/// the clicked point. Off, Group Selection, a modifier, an anchor or the fill add none. +#[test] +fn with_the_preference_on_a_double_click_on_a_segment_adds_an_anchor_there() { + let (d, id) = doc_with_rect(); + let p = paint(); + let mut whole = Selection::default(); + whole.add(id); + let none = Selection::default(); + let top = d.node(id).and_then(|n| n.path_data()).map(|pd| pd.subpaths[0].clone()).unwrap_or_else(|| panic!("the rectangle")); + for sel in [&none, &whole] { + let on = ToolContext { double_click_adds_anchor: true, ..cx(&d, sel, &p) }; + let (path, si, seg, t) = double_click_adds(&on, (150.0, 101.0), Mods::default()).unwrap_or_else(|| panic!("an anchor is added")); + assert_eq!((path, si), (id.0, 0)); + let c = top.segment(seg); + assert!(c.p0.y == 100.0 && c.p3.y == 100.0, "on the top edge: {c:?}"); + let at = vectorcraft_geom::ParamCurve::eval(&c, t); + assert!(at.distance(Point::new(150.0, 100.0)) < 1e-6, "at the clicked point: {at:?}"); + assert_eq!(double_click_adds(&on, (100.0, 100.0), Mods::default()), None, "on an anchor"); + assert_eq!(double_click_adds(&on, (150.0, 150.0), Mods::default()), None, "in the middle of the fill"); + for m in [Mods { shift: true, ..Mods::default() }, Mods { alt: true, ..Mods::default() }, Mods { cmd: true, ..Mods::default() }] { + assert_eq!(double_click_adds(&on, (150.0, 101.0), m), None, "with {m:?}"); + } + let group = DirectSelectionTool::new(true).pointer(&on, &PointerEvent::new(PointerKind::DoubleClick, 150.0, 101.0)); + assert!(group.is_empty(), "Group Selection: {group:?}"); + let off = cx(&d, sel, &p); + assert!(DirectSelectionTool::new(false).pointer(&off, &PointerEvent::new(PointerKind::DoubleClick, 150.0, 101.0)).is_empty(), "off"); + } + // On a 40 pt stroke 15 pt above the path, the stroke is hit but the path is out of reach. + let mut wide = d.clone(); + if let Some(s) = wide.node_mut(id).and_then(|n| n.appearance.stroke_mut()) { + s.width = 40.0; + } + let on = ToolContext { double_click_adds_anchor: true, ..cx(&wide, &none, &p) }; + assert!(hit_test(&wide, Point::new(150.0, 85.0), on.selection_hit_options()).is_some_and(|h| matches!(h.kind, HitKind::Stroke))); + assert_eq!(double_click_adds(&on, (150.0, 85.0), Mods::default()), None, "away from the path"); + assert!(double_click_adds(&on, (150.0, 101.0), Mods::default()).is_some(), "on the path"); + // Without a stroke, the edge is taken within the tolerance, and the fill just past it is not. + let mut unstroked = d.clone(); + if let Some(n) = unstroked.node_mut(id) { + n.appearance.set_stroke(vectorcraft_color::Paint::None); + } + let on = ToolContext { double_click_adds_anchor: true, ..cx(&unstroked, &none, &p) }; + assert!(double_click_adds(&on, (150.0, 101.0), Mods::default()).is_some(), "on the edge of the fill"); + assert!(hit_test(&unstroked, Point::new(150.0, 104.0), on.selection_hit_options()).is_some_and(|h| matches!(h.kind, HitKind::Fill))); + assert_eq!(double_click_adds(&on, (150.0, 104.0), Mods::default()), None, "on the fill past the tolerance"); +} + +/// With the preference on, a double-click on a segment of a path in a group adds the anchor to +/// that path; on the group's fill it does what it did before (nothing), and outside isolated art it +/// still leaves isolation mode. +#[test] +fn with_the_preference_on_a_double_click_in_a_group_adds_only_on_a_segment() { + let (d, inside, outside, inner, _) = nested_group_doc(); + let p = paint(); + let none = Selection::default(); + let on = ToolContext { double_click_adds_anchor: true, ..cx(&d, &none, &p) }; + assert_eq!(double_click_adds(&on, (150.0, 101.0), Mods::default()).map(|a| a.0), Some(inside.0)); + assert_eq!(double_click_adds(&on, (350.0, 301.0), Mods::default()).map(|a| a.0), Some(outside.0)); + assert!(DirectSelectionTool::new(false).pointer(&on, &PointerEvent::new(PointerKind::DoubleClick, 150.0, 150.0)).is_empty(), "the fill"); + let isolated = ToolContext { isolation: Some(inner), ..on }; + assert_eq!(double_click_adds(&isolated, (150.0, 101.0), Mods::default()).map(|a| a.0), Some(inside.0), "isolated art"); + let exit = vec![Action::Exec("object.exitIsolation".into(), json!({}))]; + assert_eq!(DirectSelectionTool::new(false).pointer(&isolated, &PointerEvent::new(PointerKind::DoubleClick, 350.0, 301.0)), exit); +} + +/// With the preference on, a double-click on a blend's spine point, which a press takes before the +/// path under it, adds no anchor to that path; on the same path away from the spine point it does. +/// A clipping path's segment, which a press takes over the art it clips, gets the anchor. +#[test] +fn with_the_preference_on_a_double_click_gives_way_to_spine_points_and_reaches_clipping_paths() { + let (mut d, _) = doc_with_rect(); + let l = d.layers[0].id; + let key = |id: NodeId, x: f64| { + let line = vectorcraft_geom::shapes::line(Point::new(x, 310.0), Point::new(x + 40.0, 310.0)); + std::sync::Arc::new(vectorcraft_doc::Node::path(id, line, vectorcraft_doc::Appearance::default_art())) + }; + let (g, k1, k2) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + let b = vectorcraft_doc::Node::new(g, NodeKind::Blend { children: vec![key(k1, 100.0), key(k2, 200.0)], spec: Default::default() }); + d.insert(Some(l), 1, b).unwrap(); + let p = paint(); + let none = Selection::default(); + let on = ToolContext { double_click_adds_anchor: true, ..cx(&d, &none, &p) }; + assert_eq!(double_click_adds(&on, (130.0, 310.0), Mods::default()).map(|a| a.0), Some(k1.0), "on the line"); + assert_eq!(double_click_adds(&on, (120.0, 310.0), Mods::default()), None, "on the spine point at its center"); + + let (d, _, clip, _) = doc_with_masked_square(); + let on = ToolContext { double_click_adds_anchor: true, ..cx(&d, &none, &p) }; + assert_eq!(double_click_adds(&on, (500.0, 450.0), Mods::default()).map(|a| a.0), Some(clip.0), "on the clipping path"); +} + /// With Direct Selection, an Alt-click on a path selected whole adds its group on release, and /// each further Alt-click adds the next group up, as Group Selection's clicks do, on an anchor, /// a segment and the fill alike. The climb stops below the layer and at the isolated group. diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index a34c819761..4f2fb7b463 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -1561,6 +1561,26 @@ impl GestureTool { v } + /// The preview of a stroke being drawn: [`Self::freehand_params`], except that a stroke that + /// redraws a selected path is shown as it is drawn, joined at its start to the point of the + /// path nearest to it, with no fill, and leaves the path and the selection as they are: where + /// the stroke ends is only known at the release, which redraws the path (`finish`). + fn drawing_params(&self, cx: &ToolContext) -> Value { + let mut v = self.freehand_params(cx, false); + let Some((id, _)) = self.redraw else { return v }; + if let Some(o) = v.as_object_mut() { + o.remove("redraw"); + } + v["fill"] = json!(false); + v["keepSelected"] = json!(false); + v["leaveSelection"] = json!(true); + let on = self.points.first().and_then(|&p| cx.doc.node(id)?.path_data()?.nearest(p)).map(|n| n.3); + if let (Some(on), Some(pts)) = (on, v["points"].as_array_mut()) { + pts.insert(0, json!([on.x, on.y])); + } + v + } + fn finish(&mut self, cx: &ToolContext, m: Mods) -> Vec { let pts = &self.points; let has_sel = !cx.selection.is_empty(); @@ -1764,7 +1784,7 @@ impl Tool for GestureTool { } // With the Pencil's Live preview off a thin line shows instead (`overlays`). if self.previews() && crate::previews_at(self.points.len()) { - let mut v = self.freehand_params(cx, false); + let mut v = self.drawing_params(cx); let fidelity = self.fidelity.max(PREVIEW_FIDELITY_PX); v["fidelity"] = json!(fit_tolerance(cx, fidelity)); // A preview fitted coarser than the stroke kept is stale (`deactivate`). @@ -1883,10 +1903,11 @@ impl Tool for GestureTool { fn deactivate(&mut self, cx: &ToolContext) -> Vec { let began = self.began; self.tip_at = None; - // Drags past the last preview are in the stroke kept, too, and with Live curve fitting - // off the stroke kept is fitted. - let stale = (began && (self.previewed != self.points.len() || !self.live_fit) && self.draws_path() && !self.smoothing) - .then(|| Action::Preview("path.freehand".into(), self.freehand_params(cx, false))); + // Drags past the last preview are in the stroke kept, too, with Live curve fitting off the + // stroke kept is fitted, and a stroke that redraws a path redraws it (`drawing_params`). + let stale = + (began && (self.previewed != self.points.len() || !self.live_fit || self.redraw.is_some()) && self.draws_path() && !self.smoothing) + .then(|| Action::Preview("path.freehand".into(), self.freehand_params(cx, false))); self.snap.clear(); self.active = false; self.near_start = false; diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 00f0ebc93e..24a0e1e5e6 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -856,6 +856,44 @@ fn pencil_shows_the_straight_line_cursor_when_a_press_draws_a_line() { assert_eq!(Cursor::PencilStraight.precise(), Cursor::Crosshair, "Use Precise Cursors"); } +/// While a stroke that redraws a selected path is drawn, its previews show the stroke as drawn, +/// joined at its start to the path, unfilled, and leave the path and the selection as they are; +/// the release (or a switch of tool mid-stroke) redraws the path. +#[test] +fn pencil_previews_a_redraw_as_the_stroke_drawn_and_redraws_at_the_release() { + let (mut d, _) = doc_with_rect(); + let l = d.layers[0].id; + let id = d.alloc_id(); + let line = vectorcraft_geom::PathData::from_bezpath(&vectorcraft_geom::BezPath::from_vec(vec![ + vectorcraft_geom::PathEl::MoveTo(Point::new(300.0, 300.0)), + vectorcraft_geom::PathEl::LineTo(Point::new(400.0, 300.0)), + ])); + d.insert(Some(l), 1, vectorcraft_doc::Node::path(id, line, vectorcraft_doc::Appearance::default_art())).unwrap(); + let mut s = Selection::default(); + s.set([id]); + let p = paint(); + let mut cx = cx(&d, &s, &p); + cx.smart_guides = false; + let mut t = GestureTool::new("pencil"); + t.set_option("fill", &json!(true)); + // Out from the path and back onto it: within Edit selected paths within all the way. + let acts = drag(&mut t, &cx, &[(350.0, 304.0), (352.0, 308.0), (356.0, 309.0), (360.0, 303.0)], Mods::default()); + let (release, drawing) = acts.split_last().unwrap(); + let previews: Vec<&Value> = drawing.iter().flatten().filter_map(|a| if let Action::Preview(_, v) = a { Some(v) } else { None }).collect(); + assert!(!previews.is_empty(), "{acts:?}"); + for v in previews { + assert!(v.get("redraw").is_none() && v["fill"] == false && v["keepSelected"] == false && v["leaveSelection"] == true, "{v}"); + assert_eq!(v["points"][0], json!([350.0, 300.0]), "joined to the path where it starts: {v}"); + assert_eq!(v["points"][1], json!([350.0, 304.0]), "{v}"); + } + assert!(matches!(release.as_slice(), [Action::Preview(_, v), Action::Commit] if v["redraw"]["id"] == id.0 && v["fill"] == true), "{release:?}"); + // A switch of tool mid-stroke keeps the redraw too. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 350.0, 304.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 352.0, 320.0)); + let acts = t.deactivate(&cx); + assert!(matches!(acts.as_slice(), [Action::Preview(_, v), Action::Commit] if v["redraw"]["id"] == id.0), "{acts:?}"); +} + /// Before a press, the Pencil shows its new-path cursor (the star) exactly when the press draws /// a new path: over an end of a selected open path, which the stroke continues, and over a /// selected path, which it redraws, it does not. With nothing selected, with Edit Selected Paths diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index ce54f110d9..ca01993a6e 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -653,6 +653,7 @@ pub(crate) mod testutil { path_only: false, type_path_only: false, double_click_isolate: true, + double_click_adds_anchor: false, select_behind: true, highlight_anchors: true, snap_tolerance: 2.0, diff --git a/crates/ui-egui/src/addons/color/nearest.rs b/crates/ui-egui/src/addons/color/nearest.rs index a646ea0000..6db4ec9332 100644 --- a/crates/ui-egui/src/addons/color/nearest.rs +++ b/crates/ui-egui/src/addons/color/nearest.rs @@ -31,6 +31,8 @@ pub const KIND: &str = "nearestSwatch"; /// The query that lists the matches, and how many of each colour's the dialog shows. const FIND: &str = "addon.color.nearestSwatch"; const MATCHES: u64 = 3; +/// The rows the match list shows before it scrolls. +const LIST_ROWS: u16 = 12; /// What the query read: the document and its revision, the library, Fill and Stroke. An answer /// stands while these are what the dialog shows now. @@ -155,7 +157,8 @@ fn body(ui: &mut Ui, fields: &mut Fields, libraries: &[Entry], selected: let lines = lines(found); let keys: Vec = (0..lines.len()).collect(); let source = keyed(&keys, |i| *i); - List::::new(label(tl!("Find Nearest Swatch"))).select(SelectMode::None).show_items(ui, &source, &mut |&i, item| match lines.get(i) { + let list = List::::new(label(tl!("Find Nearest Swatch"))).select(SelectMode::None).max_rows(LIST_ROWS); + list.show_items(ui, &source, &mut |&i, item| match lines.get(i) { Some(line) => { let face = SwatchFace::new(line.color); let row = ListRow::new(line.text.clone()) @@ -267,4 +270,20 @@ mod tests { assert!(!host(&app, |h| h.confirm_by_id(&ctx, id)), "Apply is off"); assert!(host(&app, |h| h.is_open::())); } + + #[test] + fn find_nearest_swatch_draws_its_matches_and_buttons() { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("swatch.new", json!({"name": "Brand", "color": "#ff8000", "global": true})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + app.run("paint.setFill", json!({"color": "#ff8010"})).unwrap(); + let mut p = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs); + menus::invoke(&mut p.app(), COMMAND, serde_json::Value::Null); + p.frame(); + p.frame(); + for name in ["Brand", "Apply", "Cancel"] { + assert!(p.shows(name), "{name} is drawn"); + } + } } diff --git a/crates/ui-egui/src/addons/select.rs b/crates/ui-egui/src/addons/select.rs index 938b114f04..df48a816f5 100644 --- a/crates/ui-egui/src/addons/select.rs +++ b/crates/ui-egui/src/addons/select.rs @@ -33,6 +33,8 @@ pub const COMMAND: &str = "addon.select.byArtboards"; pub const KIND: &str = "selectByArtboards"; /// The relations the dialog offers: (value, label). const RELATIONS: [(&str, &str); 3] = [("overlap", "Overlapping"), ("inside", "Fully Inside"), ("outside", "Fully Outside")]; +/// The rows the artboard list shows before it scrolls. +const LIST_ROWS: u16 = 9; /// Object › Plug-ins › Selection Tools. pub fn menu() -> Vec { @@ -170,6 +172,7 @@ fn body(ui: &mut Ui, fields: &mut Fields, rows: &[(String, String)], go_to: &mut .allow_empty(true) .activate(ActivateOn::DoubleClick) .empty(label(tl!("No artboards match."))) + .max_rows(LIST_ROWS) .selection(Bind::bound(&mut selection)) .show_items(ui, &source, &mut |&i, item| match rows.get(i) { Some((name, size)) => { diff --git a/crates/ui-egui/src/addons/select/link_status.rs b/crates/ui-egui/src/addons/select/link_status.rs index 57628ae07e..e7d9c1a509 100644 --- a/crates/ui-egui/src/addons/select/link_status.rs +++ b/crates/ui-egui/src/addons/select/link_status.rs @@ -46,6 +46,8 @@ pub const STATUSES: [(&str, &str, &str); 4] = [ ]; /// The dialog's Show choices: (value, label). const SHOW: [(&str, &str); 5] = [("all", "All"), ("linked", "Linked"), ("embedded", "Embedded"), ("missing", "Missing"), ("modified", "Modified")]; +/// The rows the image table shows before it scrolls. +const LIST_ROWS: u16 = 9; /// How often the statuses are looked at again while the document stays as it is (s): files /// change on disk without the document knowing. const RECHECK: f64 = 2.0; @@ -317,6 +319,7 @@ fn body(ui: &mut Ui, fields: &mut Fields, rows: &[Value]) { let out = Table::::new(label(tl!("Select by Link Status")), columns) .select(SelectMode::None) .empty(label(tl!("No images match."))) + .max_rows(LIST_ROWS) .show_items(ui, &source, &mut |id, item| match lines.iter().find(|line| line.id == *id) { Some(line) => ListRow::new(line.name.clone()) .cells(item.cells()) diff --git a/crates/ui-egui/src/addons/select/link_status/tests.rs b/crates/ui-egui/src/addons/select/link_status/tests.rs index 62508bfa14..463f1dd53b 100644 --- a/crates/ui-egui/src/addons/select/link_status/tests.rs +++ b/crates/ui-egui/src/addons/select/link_status/tests.rs @@ -197,6 +197,18 @@ fn links_inside_a_symbol_are_left_out_of_selecting_by_status() { assert_eq!(host(&app, |h| h.get::().map(|d| d.rows.len())), Some(0), "the dialog lists no row of the symbol"); } +#[test] +fn the_dialog_draws_its_images_and_buttons() { + let dir = Folder::new("drawn"); + let (app, ..) = app(&dir); + let mut p = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs); + menus::invoke(&mut p.app(), COMMAND, Value::Null); + p.frame(); + for name in ["river.png", "harbour.png", "Select", "Cancel"] { + assert!(p.shows(name), "{name} is drawn"); + } +} + #[test] fn the_dialog_lists_filters_and_selects_with_zoom() { let dir = Folder::new("dialog"); diff --git a/crates/ui-egui/src/addons/select/tests.rs b/crates/ui-egui/src/addons/select/tests.rs index 6e467d02fe..9e2cb85e04 100644 --- a/crates/ui-egui/src/addons/select/tests.rs +++ b/crates/ui-egui/src/addons/select/tests.rs @@ -87,6 +87,17 @@ fn select_by_artboards_opens_on_the_active_artboard_and_selects_on_ok() { assert_eq!(app.session.active().unwrap().selection.objects, vec![vectorcraft_doc::NodeId(inside)]); } +#[test] +fn select_by_artboards_draws_its_artboards_and_buttons() { + let (app, _) = banner(); + let mut p = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs); + menus::invoke(&mut p.app(), COMMAND, Value::Null); + p.frame(); + for name in ["Banner", "Select All", "OK", "Cancel"] { + assert!(p.shows(name), "{name} is drawn"); + } +} + #[test] fn a_search_keeps_the_choice_it_hides_and_a_double_click_fits_its_artboard() { // Boards 0 and 1 chosen, the search shows 0 and 2: picking row 2 leaves hidden board 1 chosen and drops shown board 0. diff --git a/crates/ui-egui/src/dialogs/bullets_numbering.rs b/crates/ui-egui/src/dialogs/bullets_numbering.rs index d7d0a5da25..b371adb13b 100644 --- a/crates/ui-egui/src/dialogs/bullets_numbering.rs +++ b/crates/ui-egui/src/dialogs/bullets_numbering.rs @@ -349,22 +349,19 @@ impl BulletsDialog { fn preset_row(ui: &mut Ui, label: &'static str, presets: &[Preset], current: Option) -> Option { let mut selection = current.map_or_else(Selection::default, Selection::single); let source = keyed(presets, |p: &Preset| p.at); - let _ = TileGrid::new(label).select(SelectMode::Single).caption(CaptionPlace::None).selection(Bind::bound(&mut selection)).show_items( - ui, - &source, - &mut |at, _| { - let Some(preset) = presets.get(*at) else { return Tile::new(String::new()) }; - let face = preset.face.clone(); - Tile::new(preset.name.clone()).thumb(ThumbAspect::SQUARE, move |cx, rect| { - cx.with_draw(|draw| match &face { - Face::Glyph(glyph) => draw.icon(rect, &IconSpec::glyph(*glyph)), - Face::Text(text) => { - let _ = draw.text(rect, &TextRun::new(text.as_str()).align(HAlign::Center)); - } - }) + let grid = TileGrid::new(label).select(SelectMode::Single).caption(CaptionPlace::None).natural_height(true); + let _ = grid.selection(Bind::bound(&mut selection)).show_items(ui, &source, &mut |at, _| { + let Some(preset) = presets.get(*at) else { return Tile::new(String::new()) }; + let face = preset.face.clone(); + Tile::new(preset.name.clone()).thumb(ThumbAspect::SQUARE, move |cx, rect| { + cx.with_draw(|draw| match &face { + Face::Glyph(glyph) => draw.icon(rect, &IconSpec::glyph(*glyph)), + Face::Text(text) => { + let _ = draw.text(rect, &TextRun::new(text.as_str()).align(HAlign::Center)); + } }) - }, - ); + }) + }); selection.lead.filter(|at| Some(*at) != current) } diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index 25c7891020..0cd18ff6e7 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -4,9 +4,11 @@ //! Each field is unset (empty, absent, or a checkbox in its unset state) or set, and an unset field leaves //! its attribute out of the style. A field still as it opened keeps the style's stored value as it is. +use std::ops::RangeInclusive; use std::sync::Arc; use craft::behavior::Mixed; +use craft::text::ui::character::{AKI_PRESETS, DIACRITIC_PRESETS, TSUME_PRESETS}; use craft::ui::choice::Checkbox; use craft::ui::contract::{Bind, Entry, Outcome as _, Props as _, Show as _, ShowContainer as _}; use craft::ui::dialog::{DialogResult, FieldRefusal}; @@ -15,7 +17,8 @@ use craft::ui::patterns::form_dialogs::{ DialogFields, FieldValue, HostedPropertiesDialog, Param, ParamKind, PropertiesDialog, PropertiesTab, PropertyRow, TabLayout, }; use craft::ui::pickers::Select; -use craft::ui::runtime::env::Label; +use craft::ui::runtime::env::{Env, Label}; +use craft::ui::text::{NumberField, NumberPick}; use serde_json::{Map, Value, json}; use vectorcraft_doc::setup::DocSetup; @@ -429,6 +432,23 @@ fn case_from_attrs(attrs: &Map) -> Option<&'static str> { } } +/// The number the text typed into number field `key` reads as, with the arithmetic of the app's number +/// fields (`6x2`, `10+4`, `200/2`) and a decimal comma: a length in points in the length fields (`1 in`), +/// and a final `%` in the percent fields or `°` in Character Rotation. +fn typed_number(key: &str, text: &str) -> Option { + let text = text.trim().replace('\u{2212}', "-"); + let text = vectorcraft_doc::decimal_point(&text); + let mark = match key { + "size" | "leading" | "baseline_shift" | "tcyUpDown" | "tcyLeftRight" | "stroke_width" => { + return vectorcraft_doc::Unit::Points.parse(&text); + } + "h_scale" | "v_scale" | "tsume" | "fill_tint" | "stroke_tint" => Some('%'), + "rotation" => Some('°'), + _ => None, + }; + vectorcraft_doc::parse_number(mark.and_then(|m| text.strip_suffix(m)).unwrap_or(&text)) +} + fn optional_number(d: &Values, key: &str) -> Result, String> { let label = match key { "size" => tl!("Size"), @@ -458,7 +478,7 @@ fn optional_number(d: &Values, key: &str) -> Result, String> { Some(v) => { let n = v .as_f64() - .or_else(|| v.as_str().and_then(|s| s.trim().parse::().ok())) + .or_else(|| v.as_str().and_then(|s| typed_number(key, s))) .filter(|n| n.is_finite()) .ok_or_else(|| format!("{label} must be a number"))?; // Character Style fields use the Character panel's visible ranges. @@ -898,7 +918,39 @@ fn basic_rows() -> Vec { ]) } -// PLAN: the Aki, Tsume and Diacritic rows are plain text rows: `Param::text` has no preset menu to carry the Character panel's presets. +/// A number row over the text field `key` (empty for unset) whose menu offers `presets`, as the Character panel's field +/// of the same name does. A typed value stays within `range`; automation sets the field's text, as for a text row. +fn preset_number(key: &'static str, label: String, range: RangeInclusive, presets: &'static [f32]) -> Param { + let name = label.clone(); + Param::custom(key, label, move |ui, fields, _| { + let value = fields.text(key).and_then(|text| text.trim().parse::().ok()).filter(|n| n.is_finite()); + let units = Env::of(ui).units(); + let rows: Vec> = presets + .iter() + .map(|&p| { + let n = f64::from(p); + Entry::new(NumberPick::Number(n), units.number(n, 0..=2)) + }) + .collect(); + let out = NumberField::new(name.clone(), Bind::given(value)).range(range.clone()).presets(&rows).id_salt(key).show(ui); + if let Some(picked) = out.edit.value() { + let text = picked.map(|n| n.to_string()).unwrap_or_default(); + if fields.text(key) != Some(text.as_str()) { + fields.set(key, FieldValue::Text(text)); + } + } + out.edit.response.clone() + }) + // Set from outside: the field's text, as a text row takes it. + .on_set(|fields, key, value| match value { + Value::String(text) => { + fields.set(key, FieldValue::Text(text)); + Ok(()) + } + other => Err(FieldRefusal::Rejects(&other).message(key)), + }) +} + fn advanced_rows() -> Vec { let mut params: Vec = [ ("h_scale", tl!("Horizontal Scale"), "%"), @@ -907,15 +959,20 @@ fn advanced_rows() -> Vec { ("tcyUpDown", tl!("Tate-chu-yoko Up/Down"), "pt"), ("tcyLeftRight", tl!("Tate-chu-yoko Left/Right"), "pt"), ("rotation", tl!("Character Rotation"), "°"), - ("akiLeft", tl!("Insert Aki Left"), ""), - ("akiRight", tl!("Insert Aki Right"), ""), - ("tsume", tl!("Tsume"), "%"), - ("diacriticHorizontal", tl!("Adjust Horizontal Diacritic Position"), ""), - ("diacriticVertical", tl!("Adjust Vertical Diacritic Position"), ""), ] .into_iter() - .map(|(key, caption, unit)| text(key, if unit.is_empty() { caption.to_string() } else { format!("{caption} ({unit})") })) + .map(|(key, caption, unit)| text(key, format!("{caption} ({unit})"))) .collect(); + let aki = 0.0..=vectorcraft_doc::text::MAX_AKI; + let tsume = 0.0..=vectorcraft_doc::text::MAX_TSUME; + let diacritic = -vectorcraft_doc::text::MAX_DIACRITIC_POSITION..=vectorcraft_doc::text::MAX_DIACRITIC_POSITION; + params.extend([ + preset_number("akiLeft", tl!("Insert Aki Left").to_string(), aki.clone(), &AKI_PRESETS), + preset_number("akiRight", tl!("Insert Aki Right").to_string(), aki, &AKI_PRESETS), + preset_number("tsume", format!("{} (%)", tl!("Tsume")), tsume, &TSUME_PRESETS), + preset_number("diacriticHorizontal", tl!("Adjust Horizontal Diacritic Position").to_string(), diacritic.clone(), &DIACRITIC_PRESETS), + preset_number("diacriticVertical", tl!("Adjust Vertical Diacritic Position").to_string(), diacritic, &DIACRITIC_PRESETS), + ]); let languages: Vec<(&'static str, &'static str)> = vectorcraft_doc::setup::LANGUAGES.iter().map(|(name, _, _)| (*name, *name)).collect(); params.push(select("language", tl!("Language:"), &languages)); rows(params) diff --git a/crates/ui-egui/src/dialogs/char_style_options/tests.rs b/crates/ui-egui/src/dialogs/char_style_options/tests.rs index 79884992c4..44d443b361 100644 --- a/crates/ui-egui/src/dialogs/char_style_options/tests.rs +++ b/crates/ui-egui/src/dialogs/char_style_options/tests.rs @@ -515,6 +515,33 @@ fn diacritic_position_fields_show_set_reset_and_commit() { assert!(t.runs.iter().all(|r| (r.style.diacritic_horizontal, r.style.diacritic_vertical) == (-120.0, 1000.0))); } +/// The number fields read typed text as the app's other number fields do: `6x2`, `10+4`, `200/2%`, +/// `45°`, a decimal comma, and a length with its unit. `%` and `°` only where the field takes them, +/// and an exponent is not read. +#[test] +fn number_fields_take_field_arithmetic() { + let typed = [ + ("size", "6x2", 12.0), + ("tracking", "10+4", 14.0), + ("h_scale", "200/2%", 100.0), + ("rotation", "45°", 45.0), + ("fill_tint", "25*2", 50.0), + ("leading", "1 in", 72.0), + ("baseline_shift", "\u{2212}2", -2.0), + ("kerning", "12,5", 12.5), + ]; + for (key, text, want) in typed { + let (mut d, _) = dialog_for(json!({})); + put(&mut d, key, json!(text)); + assert_eq!(optional_number(&Values::new(&d), key), Ok(Some(json!(want))), "{key} {text}"); + } + for (key, text) in [("size", "12°"), ("leading", "50%"), ("tracking", "10%"), ("rotation", "45%"), ("h_scale", "1%2"), ("size", "1e3")] { + let (mut d, _) = dialog_for(json!({})); + put(&mut d, key, json!(text)); + assert!(optional_number(&Values::new(&d), key).is_err(), "{key} {text}"); + } +} + /// Tsume: empty is unset, an explicit 0 stays set, a typed value stops at 0 and 100, Reset Panel /// unsets it, and it commits to the style and the text set in it. #[test] @@ -523,7 +550,7 @@ fn tsume_field_shows_sets_resets_and_commits() { assert_eq!(val(&d, "tsume"), json!("")); let (mut d, o) = dialog_for(json!({"tsume": 50.0})); assert_eq!(val(&d, "tsume"), json!("50.0")); - for (typed, kept) in [("0", 0.0), ("25.5", 25.5), ("150", 100.0), ("-5", 0.0)] { + for (typed, kept) in [("0", 0.0), ("25.5", 25.5), ("25%", 25.0), ("50/2%", 25.0), ("150", 100.0), ("-5", 0.0)] { put(&mut d, "tsume", json!(typed)); assert_eq!(edited_attrs(&d, &o).unwrap(), attrs(json!({"tsume": kept})), "{typed}"); } @@ -547,6 +574,41 @@ fn tsume_field_shows_sets_resets_and_commits() { assert!(t.runs.iter().all(|r| r.style.tsume == 75.0)); } +/// The Insert Aki, Tsume and diacritic rows each have the Character panel's presets menu beside the field, and a +/// preset picked from it is the field's value and commits to the style, with each frame drawn once. +#[test] +fn aki_tsume_and_diacritic_rows_pick_from_the_character_panel_presets() { + use craft::ui::testing::Fixture; + let mut fx = Fixture::new(|ui| crate::dialogs::host::window_dialogs(ui.ctx()).with(|host| host.run(ui))); + fx.room(egui::vec2(900.0, 900.0)); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.ui_ctx = Some(fx.ctx().clone()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + styled(&mut app, json!({"size": 24.0}), "Text"); + open(&mut app, "Body"); + set::(&app, "tab", json!("advanced")); + fx.settle(); + + let presets_in_row = |fx: &Fixture, label: &str| { + let field = fx.by_label(label).unwrap_or_else(|| panic!("the {label} field")); + let tree = fx.tree(); + tree.keys().into_iter().filter(|key| tree.name_of(*key) == Some("Presets")).filter_map(|key| fx.target(key)).find(|chevron| { + chevron.rect.center().y > field.rect.top() && chevron.rect.center().y < field.rect.bottom() && chevron.rect.left() >= field.rect.left() + }) + }; + for label in ["Insert Aki Left", "Insert Aki Right", "Tsume (%)", "Adjust Horizontal Diacritic Position", "Adjust Vertical Diacritic Position"] { + assert!(presets_in_row(&fx, label).is_some(), "{label} has a presets menu"); + } + + let chevron = presets_in_row(&fx, "Insert Aki Left").unwrap(); + fx.click(&chevron).settle(); + let pick = fx.by_label("500").expect("the 500 preset"); + fx.click(&pick).settle(); + assert_eq!(fields::(&app)["akiLeft"], json!("500")); + assert!(ok::(&mut app)); + assert_eq!(app.session.doc().unwrap().doc.char_styles[0].attrs, attrs(json!({"size": 24.0, "akiLeft": 500.0}))); +} + /// The negated tags of the twenty stylistic sets: an explicit empty Stylistic Sets choice. fn no_sets() -> Vec { vectorcraft_text::EXTRA_FEATURES[..20].iter().map(|s| format!("-{s}")).collect() diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index 0c1f50cbb1..af1b318728 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -6,7 +6,8 @@ //! `artboard.setProps {index, color}`. //! //! A command dialog's colour row raises a `ColorRequest`; [`pump`] opens a picker over that dialog -//! and answers the row with its OK. +//! and answers the row with its OK. The OK for a Save for Web colour table cell shifts the cell's +//! colour in the table instead ([`super::save_for_web::take_palette_pick`]). //! //! Fields agents set with `ui.dialog.set`: the framework picker's (`color`, `mode`, `webColors`, //! `swatches`, `library`). `stroke`, `artboard` and `color` come from the opener. @@ -253,7 +254,11 @@ fn finish( ) { let preview = std::mem::take(&mut open.preview); match (result, &open.target) { - (Some(DialogResult::Ok(r)), Target::Answer { parent, key }) => dialogs.with(|h| h.answer_color(*parent, key, r.picked.color)), + (Some(DialogResult::Ok(r)), Target::Answer { parent, key }) => { + if !super::save_for_web::take_palette_pick(app, *parent, key, open.start, r.picked.color) { + dialogs.with(|h| h.answer_color(*parent, key, r.picked.color)); + } + } (Some(DialogResult::Ok(r)), _) => { if let Err(e) = commit(app, open, preview, &r.picked) { app.status(e); diff --git a/crates/ui-egui/src/dialogs/composite_fonts.rs b/crates/ui-egui/src/dialogs/composite_fonts.rs index a8f096adb5..8580b7085a 100644 --- a/crates/ui-egui/src/dialogs/composite_fonts.rs +++ b/crates/ui-egui/src/dialogs/composite_fonts.rs @@ -76,6 +76,8 @@ const IMPORT: &str = "type.compositeFonts.import"; /// The purpose of the file picks, which keeps their last folder. const PURPOSE: &str = "compositeFonts"; +/// The rows of a custom set's characters shown before they scroll. +const CHAR_ROWS: u16 = 5; /// The table's columns: the class (or the custom set's name) is the row's label. const CLASS: ColumnKey = ColumnKey::new("class"); @@ -656,6 +658,7 @@ impl CompositeFontsDialog { let out = TileGrid::::new(tl!("Characters")) .select(SelectMode::Single) .thumb_size(ThumbSize::Small) + .max_rows(CHAR_ROWS) .selection(Bind::given(selection)) .show_items(ui, &keyed(&keys, |k: &usize| *k), &mut |key, _| { let c = chars.get(*key).copied().unwrap_or_default(); diff --git a/crates/ui-egui/src/dialogs/composite_fonts/tests.rs b/crates/ui-egui/src/dialogs/composite_fonts/tests.rs index 431a1508cb..cbfd379b71 100644 --- a/crates/ui-egui/src/dialogs/composite_fonts/tests.rs +++ b/crates/ui-egui/src/dialogs/composite_fonts/tests.rs @@ -458,3 +458,19 @@ fn the_sample_draws_color_glyphs_in_their_colors() { let (_, tall) = sample::measure(&f, 36.0); assert!(tall.ascender.unwrap() > plain.ascender.unwrap() * 1.5, "{plain:?} {tall:?}"); } + +/// With Custom on, the dialog draws the set's characters and its buttons. +#[test] +fn custom_character_sets_draw_their_characters_and_the_buttons() { + let mut p = crate::tests::panel_harness::Panel::new(app(), crate::tests::picks::dialogs); + open(&mut p.app()).unwrap(); + new_font(&mut p.app()); + dialog(&mut p.app(), |d| d.custom = true); + new_set(&mut p.app()); + dialog(&mut p.app(), |d| d.entry = "AB".into()); + edit(&mut p.app(), SetAction::AddChars).unwrap(); + p.frame(); + for name in ["A", "B", "OK", "Cancel"] { + assert!(p.shows(name), "{name} is drawn"); + } +} diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index 194ec96853..6d8b492104 100644 --- a/crates/ui-egui/src/dialogs/document_setup.rs +++ b/crates/ui-egui/src/dialogs/document_setup.rs @@ -391,7 +391,7 @@ fn grid_colors_row(setup: DocSetup) -> Param { for (i, color) in resolved.iter().enumerate() { let name = format!("{} {}", tl!("Grid Colors:"), i + 1); let [r, g, b, _] = color.to_rgba8(1.0); - let srgb = Srgba::rgb(f32::from(r) / 255.0, f32::from(g) / 255.0, f32::from(b) / 255.0); + let srgb = box_color(color); wells[i] = Swatch::new(name.clone(), srgb).well().show(ui).clicked.then_some(srgb); edits[i] = HexField::hex(name, Bind::given(Rgba::rgb(r, g, b))).show(ui).value().copied(); } @@ -412,16 +412,29 @@ fn grid_colors_row(setup: DocSetup) -> Param { }) } -/// Takes the colors the Color Picker answered into their entries of the pair. +/// Takes the colors the Color Picker answered into their entries of the pair. When the dialog holds +/// two colors and the answer is the color the entry's box showed (the picker's OK left it +/// unchanged), the entry stays as it is: a Lab or CMYK color keeps its own model, and a hex code +/// stays that hex code. fn fold_picked(fields: &mut DialogFields, setup: &DocSetup) { for (i, key) in GRID_KEYS.iter().enumerate() { if let Some([r, g, b]) = fields.color(key) { fields.remove(key); - set_grid_entry(fields, setup, i, &Color::rgb(r, g, b)); + let map = json_map(fields); + let shown = grid_colors(&map, setup).get(i).map(box_color).map(|s| [s.r, s.g, s.b]); + if pending_grid_pair(&map).is_none() || shown != Some([r, g, b]) { + set_grid_entry(fields, setup, i, &Color::rgb(r, g, b)); + } } } } +/// The color grid color `c`'s box shows, which the Color Picker it opens starts on. +fn box_color(c: &Color) -> Srgba { + let [r, g, b, _] = c.to_rgba8(1.0); + Srgba::rgb(f32::from(r) / 255.0, f32::from(g) / 255.0, f32::from(b) / 255.0) +} + /// Sets entry `i` of the dialog's `gridColors` to `c`, the other entry staying as it is. A field /// that is not two colors becomes the pair the boxes show first. fn set_grid_entry(fields: &mut DialogFields, setup: &DocSetup, i: usize, c: &Color) { @@ -997,6 +1010,31 @@ mod tests { assert_eq!(super::json_map(&fields(&app))["gridColors"], json!(["lab 55 60 40", "#123456"])); } + /// The Color Picker's OK on a grid color it opened on, unchanged, keeps that color in its own + /// model: a Lab or CMYK color stays Lab or CMYK through Document Setup's OK, and a hex color + /// stays that hex color. The other color stays as it was. + #[test] + fn an_unchanged_grid_color_picker_ok_keeps_the_colors_own_model() { + for (index, grid) in + [(0, json!(["lab 55 60 40", "#cccccc"])), (1, json!(["#ffffff", "cmyk 0 50 100 0"])), (1, json!(["lab 55 60 40", "#123456"]))] + { + let (mut app, ctx) = new_app(); + app.run("document.setup", json!({ "gridColors": grid })).unwrap(); + app.run("file.documentSetup", json!({})).unwrap(); + set(&app, &ctx, "tab", json!("Transparency")); + settle(&app, &ctx); + let before = app.session.active().unwrap().doc.setup.grid_colors; + let entries = super::json_map(&fields(&app))["gridColors"].clone(); + // The picker opens on the color the box shows, and an unchanged OK answers that color. + let shown = super::box_color(&before[index]); + app.dialogs().unwrap().with(|h| h.answer_color(id(), super::GRID_KEYS[index], shown)); + settle(&app, &ctx); + assert_eq!(super::json_map(&fields(&app))["gridColors"], entries, "{grid}"); + assert!(press_ok(&mut app, &ctx)); + assert_eq!(app.session.active().unwrap().doc.setup.grid_colors, before, "{grid}"); + } + } + /// The Grid Colors menu names a preset only when the pair is that preset's colors, as /// `document.setup` names it: a color that rounds to the preset's hex code makes it Custom. #[test] diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index c6c9f72d3d..9d2ca82832 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -2092,9 +2092,6 @@ fn assign_tab( } }); } - if rows.is_empty() { - Text::new(tl!("No colors to recolor (preserved colors are left out).")).shade(Shade::Muted).show(ui); - } let columns = vec![ ColumnSpec::new( CURRENT, @@ -2122,10 +2119,12 @@ fn assign_tab( let source = keyed(&keys, |k| *k).with_text(|k| Cow::Owned(names.get(*k).cloned().unwrap_or_default())); let edits: RefCell> = RefCell::new(Vec::new()); let shown_rows: &[Value] = rows; - let out = Table::::new(tl!("Colors"), columns).min_rows(5).max_rows(8).selection(Bind::bound(&mut sel)).show_items( - ui, - &source, - &mut |key, icx| { + let out = Table::::new(tl!("Colors"), columns) + .min_rows(5) + .max_rows(8) + .empty(tl!("No colors to recolor (preserved colors are left out).")) + .selection(Bind::bound(&mut sel)) + .show_items(ui, &source, &mut |key, icx| { let i = *key; let edits = &edits; let row = shown_rows.get(i).cloned().unwrap_or_default(); @@ -2159,8 +2158,7 @@ fn assign_tab( edits.borrow_mut().push(RowEdit::Hex(i, *c)); } }) - }, - ); + }); let mut items = sel.items.clone(); items.sort_unstable(); items.dedup(); diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index b338d45611..aaaf3d4e1c 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -19,10 +19,12 @@ use vectorcraft_render::encode::quantize::Reduction; use craft::behavior::PixelSize; use craft::host::PickRequest; +use craft::theme::Srgba; use craft::ui::dialog::{DialogId, DialogResult, StackDialog}; use craft::ui::patterns::form_dialogs::{ BrowserPreview, ColorTable, ColorTableEdit, ColorTableEvent, HostedSaveForWeb, OptimizeAnswer, OptimizeRequest, OptimizeScope, OptimizeStart, - SaveForWebOptions, SaveForWebResult, WantedVariant, WebDocument, WebFormat, WebPreset, WebPresetEvent, WebSlice, WebSlices, WebVariant, + PALETTE_COLOR_KEY, SaveForWebOptions, SaveForWebResult, WantedVariant, WebDocument, WebFormat, WebPreset, WebPresetEvent, WebSlice, WebSlices, + WebVariant, }; use craft::ui::primitives::{Revision, TextureStore, TextureStoreOptions}; use craft::ui::runtime::requests::PathRequest; @@ -432,7 +434,7 @@ fn on_dialog(host: &craft::ui::shell::WindowDialogs, f: impl FnOnce(&mut Host /// Answers the open dialog once per frame: its result when it closed, else its requests. /// Colour requests (the matte, a palette cell) are routed by the host-wide colour picker routing; -/// a palette answer comes back as a `Shift` table event. +/// a palette cell's pick is applied to the table by [`take_palette_pick`]. pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(host) = app.dialogs() else { return }; match host.with(|h| h.take::()) { @@ -511,12 +513,7 @@ fn answer_variants(app: &mut VectorcraftApp, ctx: &egui::Context, host: &craft:: /// Applies the colour table edits the dialog filed. A Delete clears the dialog's colour selection. fn edit_table(app: &mut VectorcraftApp, ctx: &egui::Context, host: &craft::ui::shell::WindowDialogs, asked: &Asked) { - let shown = app - .session - .web_settings(&settings_of(&asked.options, &app.web_export.table, None)) - .and_then(|s| encoded(app, &s)) - .map(|o| o.colors.iter().map(|c| c.source).collect::>()); - let shown = match shown { + let shown = match shown_colors(app, &asked.options) { Ok(shown) => shown, Err(e) => return app.status(e), }; @@ -533,6 +530,36 @@ fn edit_table(app: &mut VectorcraftApp, ctx: &egui::Context, host: &craft::ui::s } } +/// The source colours of the palette the dialog's settings `options` show, with the table as it stands. +fn shown_colors(app: &mut VectorcraftApp, options: &SaveForWebOptions) -> Result, String> { + let settings = app.session.web_settings(&settings_of(options, &app.web_export.table, None))?; + Ok(encoded(app, &settings)?.colors.iter().map(|c| c.source).collect()) +} + +/// The Color Picker's OK for the colour table cell `key` of the open dialog `parent`: the cell's colour `from` +/// is shifted to `to` in the table at once, so Done or Save in the dialog's next pass keeps the shift. A colour +/// the palette no longer shows is not shifted, and a refused shift shows in the status line. `false` when +/// `parent` is not Save for Web or `key` is not its palette, and the picker answers the row instead. +pub(crate) fn take_palette_pick(app: &mut VectorcraftApp, parent: DialogId, key: &str, from: Srgba, to: Srgba) -> bool { + let Some(host) = app.dialogs() else { return false }; + if key != PALETTE_COLOR_KEY { + return false; + } + let Some(options) = host.with(|h| h.get_mut_by_id::(parent).map(|d| d.current().clone())) else { + return false; + }; + let rgb = |c: Srgba| { + let [r, g, b, _] = c.to_rgba().0; + [r, g, b] + }; + let edit = ColorTableEdit::Shift(rgb(to)); + let shifted = shown_colors(app, &options).and_then(|shown| color_table::apply(&mut app.web_export.table, &edit, &[rgb(from)], &shown)); + if let Err(e) = shifted { + app.status(e); + } + true +} + /// Runs what the preset list asked for and shows a failure in the status line. fn store_presets(app: &mut VectorcraftApp, events: Vec) { for event in events { diff --git a/crates/ui-egui/src/dialogs/save_for_web/color_table.rs b/crates/ui-egui/src/dialogs/save_for_web/color_table.rs index f80c488fef..cbeedbe224 100644 --- a/crates/ui-egui/src/dialogs/save_for_web/color_table.rs +++ b/crates/ui-egui/src/dialogs/save_for_web/color_table.rs @@ -1,8 +1,9 @@ //! The Save for Web colour table model: the edits the table's buttons and menu make, applied to the //! engine's `colorTable` value (`webexport::ColorTable`), and the marks the table shows from it. //! -//! The value is user input (automation sets it), so every read skips what is not a `#rrggbb` -//! string. Lists hold lowercase `#rrggbb` and colours compare case-insensitively. +//! The value is user input (automation sets it), so every read skips what is not a colour. +//! Entries compare as the colours they name, however each is written (`#F00`, `#ff0000`), as the +//! engine reads them; the edits write lowercase `#rrggbb`. use serde_json::{Map, Value, json}; use vectorcraft_engine::cmd::webexport; @@ -15,14 +16,30 @@ fn hex(c: [u8; 3]) -> String { format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2]) } -/// The colour a `#rrggbb` string names. +/// The colour `s` names, read as the engine reads the table's colours: `None` for text that is not +/// a colour and for a spelling with alpha (four or eight hex digits). fn parse(s: &str) -> Option<[u8; 3]> { - let digits = s.strip_prefix('#')?; - if digits.len() != 6 || !digits.bytes().all(|b| b.is_ascii_hexdigit()) { + let t = s.trim(); + let digits = t.strip_prefix('#').unwrap_or(t); + if matches!(digits.len(), 4 | 8) && digits.bytes().all(|b| b.is_ascii_hexdigit()) { return None; } - let channel = |i: usize| u8::from_str_radix(digits.get(i..i + 2)?, 16).ok(); - Some([channel(0)?, channel(2)?, channel(4)?]) + let [r, g, b, _] = vectorcraft_color::Color::from_hex(t)?.to_rgba8(1.0); + Some([r, g, b]) +} + +/// Whether `a` and `b` name one colour, however each is written; text that names no colour matches +/// only the same text in any case. +fn same(a: &str, b: &str) -> bool { + match (parse(a), parse(b)) { + (Some(a), Some(b)) => a == b, + _ => a.eq_ignore_ascii_case(b), + } +} + +/// Whether `list` holds an entry that names `color`. +fn holds(list: &[String], color: &str) -> bool { + list.iter().any(|c| same(c, color)) } /// The strings of the table's list `key`, lowercase. @@ -50,30 +67,31 @@ fn toggle(table: &mut Value, key: &str, colors: &[String]) { return; } let mut v = list(table, key); - if colors.iter().all(|c| v.contains(c)) { - v.retain(|c| !colors.contains(c)); + if colors.iter().all(|c| holds(&v, c)) { + v.retain(|c| !holds(colors, c)); } else { - let missing: Vec = colors.iter().filter(|c| !v.contains(c)).cloned().collect(); + let missing: Vec = colors.iter().filter(|c| !holds(&v, c)).cloned().collect(); v.extend(missing); } set_table(table, key, json!(v)); } -/// Take `colors` out of the table's list `key`; the list is left alone when none is in it. +/// Take `colors` out of the table's list `key` (every entry that names one of them); the list is +/// left alone when none is in it. fn remove(table: &mut Value, key: &str, colors: &[String]) { let mut v = list(table, key); let before = v.len(); - v.retain(|c| !colors.contains(c)); + v.retain(|c| !holds(colors, c)); if v.len() != before { set_table(table, key, json!(v)); } } -/// Take the shift by hand of the source colour `source` away. +/// Take the shift by hand of the source colour `source` away: every key that names that colour. fn unshift(table: &mut Value, source: &str) { let mut map = shifts(table); let before = map.len(); - map.retain(|k, _| !k.eq_ignore_ascii_case(source)); + map.retain(|k, _| !same(k, source)); if map.len() != before { set_table(table, "shifted", Value::Object(map)); } @@ -111,7 +129,7 @@ pub(crate) fn apply(table: &mut Value, edit: &ColorTableEdit, colors: &[[u8; 3]] // first selected colour is shifted to. ColorTableEdit::Shift(to) => { if let Some(&from) = colors.first().filter(|c| shown.contains(c)) { - shift(table, from, *to); + return shift(table, from, *to); } return Ok(()); } @@ -130,12 +148,13 @@ pub(crate) fn apply(table: &mut Value, edit: &ColorTableEdit, colors: &[[u8; 3]] match edit { ColorTableEdit::Lock => { let by_hand = shifts(table); - let free: Vec = picked.into_iter().filter(|c| !by_hand.keys().any(|k| k.eq_ignore_ascii_case(c))).collect(); + let free: Vec = picked.into_iter().filter(|c| !by_hand.keys().any(|k| same(k, c))).collect(); toggle(table, "locked", &free); } ColorTableEdit::Transparent => toggle(table, "transparent", &picked), ColorTableEdit::WebShift => { - let adds = !picked.iter().all(|c| list(table, "webShift").contains(c)); + let web = list(table, "webShift"); + let adds = !picked.iter().all(|c| holds(&web, c)); toggle(table, "webShift", &picked); if adds { picked.iter().for_each(|c| unshift(table, c)); @@ -157,12 +176,12 @@ fn delete(table: &mut Value, picked: &[String], shown: &[[u8; 3]]) -> Result<(), } let mut deleted = list(table, "deleted"); for c in picked { - if !deleted.contains(c) { + if !holds(&deleted, c) { deleted.push(c.clone()); } } - let clear: Vec = list(table, "transparent").into_iter().filter(|c| !picked.contains(c)).collect(); - if custom.iter().all(|c| deleted.contains(c) || clear.contains(c)) { + let clear: Vec = list(table, "transparent").into_iter().filter(|c| !holds(picked, c)).collect(); + if custom.iter().all(|c| holds(&deleted, c) || holds(&clear, c)) { return Err(webexport::KEEP_ONE.into()); } for key in ["locked", "transparent", "webShift"] { @@ -177,16 +196,44 @@ fn delete(table: &mut Value, picked: &[String], shown: &[[u8; 3]]) -> Result<(), } /// Shift the source colour `from` to `to`, wherever it is in the image; it is no longer -/// web-shifted. Shifting a colour to itself takes its shift away. -pub(crate) fn shift(table: &mut Value, from: [u8; 3], to: [u8; 3]) { +/// web-shifted. Shifting a colour to itself takes its shift away. A shift that would leave more +/// than 256 colours shifted is refused with the engine's limit error, and nothing changes. Entries the +/// engine drops (a colour shifted to itself, a deleted colour) do not count, and a new shift writes +/// the map without them. +pub(crate) fn shift(table: &mut Value, from: [u8; 3], to: [u8; 3]) -> Result<(), String> { let (source, to) = (hex(from), hex(to)); + let deleted: Vec<[u8; 3]> = list(table, "deleted").iter().filter_map(|c| parse(c)).collect(); + let map = shifts(table); + // Entries are dropped only from a map the engine accepts (at most 256 entries, every key and + // value a colour, no two keys naming one colour); any other map is kept whole for the engine to + // refuse. + let mut keys: Vec<[u8; 3]> = Vec::new(); + let valid = map.len() <= webexport::MAX_TABLE + && map.iter().all(|(k, v)| match (parse(k), v.as_str().and_then(parse)) { + (Some(k), Some(_)) if !keys.contains(&k) => { + keys.push(k); + true + } + _ => false, + }); + let live = |k: &str, v: &Value| { + let (true, Some(key), Some(to)) = (valid, parse(k), v.as_str().and_then(parse)) else { return true }; + to != key && !deleted.contains(&key) + }; + let count = map.iter().filter(|(k, v)| live(k, v)).count(); + let held = usize::from(map.iter().any(|(k, v)| live(k, v) && same(k, &source))); + if to != source && count - held >= webexport::MAX_TABLE { + return Err(webexport::too_many("shifted")); + } unshift(table, &source); if to != source { let mut map = shifts(table); + map.retain(|k, v| live(k, v)); map.insert(source.clone(), json!(to)); set_table(table, "shifted", Value::Object(map)); } remove(table, "webShift", &[source]); + Ok(()) } /// Restore Generated Table: no deleted colours and no fixed palette; the reduction makes the @@ -197,9 +244,17 @@ pub(crate) fn restore(table: &mut Value) { } /// What the table shows of `table`: its locked, transparent and shifted colours. An entry that is -/// not a colour is skipped. +/// not a colour is skipped, and a colour written more than once in a list is listed once. pub(crate) fn marks(table: &Value) -> TableMarks { - let colors = |key: &str| list(table, key).iter().filter_map(|c| parse(c)).collect(); + let colors = |key: &str| { + let mut out: Vec<[u8; 3]> = Vec::new(); + for c in list(table, key).iter().filter_map(|c| parse(c)) { + if !out.contains(&c) { + out.push(c); + } + } + out + }; let shifted = shifts(table).iter().filter_map(|(k, v)| Some((parse(k)?, parse(v.as_str()?)?))).collect(); // PLAN: TableMarks lacks `web_shifted` (ex.W9 request); the Web Shift/Unshift label needs it. let mut marks = TableMarks::default(); diff --git a/crates/ui-egui/src/dialogs/save_for_web/tests_table.rs b/crates/ui-egui/src/dialogs/save_for_web/tests_table.rs index 5b684406ed..6f8d414185 100644 --- a/crates/ui-egui/src/dialogs/save_for_web/tests_table.rs +++ b/crates/ui-egui/src/dialogs/save_for_web/tests_table.rs @@ -31,7 +31,7 @@ fn every_table_edit_changes_the_lists_it_names() { run(&mut t, ColorTableEdit::Transparent, &[D], &shown).unwrap(); assert_eq!(t["transparent"], json!(["#333333"])); // A hand-shifted colour stays locked: Lock does nothing to it. - shift(&mut t, B, [255, 136, 0]); + shift(&mut t, B, [255, 136, 0]).unwrap(); run(&mut t, ColorTableEdit::Lock, &[B], &shown).unwrap(); assert_eq!(t["locked"], json!([])); // Web Shift takes the hand shift away; Unshift takes colours out of webShift only. @@ -40,9 +40,9 @@ fn every_table_edit_changes_the_lists_it_names() { run(&mut t, ColorTableEdit::Unshift, &[B], &shown).unwrap(); assert_eq!(t["webShift"], json!(["#222222"])); // A shift takes the colour out of webShift; one to the source colour takes it away. - shift(&mut t, C, [0, 255, 0]); + shift(&mut t, C, [0, 255, 0]).unwrap(); assert_eq!((&t["webShift"], &t["shifted"]), (&json!([]), &json!({"#222222": "#00ff00"}))); - shift(&mut t, C, C); + shift(&mut t, C, C).unwrap(); assert_eq!(t["shifted"], json!({})); // The Shift edit is a shift of the first selected colour. run(&mut t, ColorTableEdit::Shift([1, 2, 3]), &[A], &shown).unwrap(); @@ -110,6 +110,113 @@ fn an_edit_skips_selected_colors_the_table_does_not_show() { assert_eq!((&t["customPalette"], &t["deleted"]), (&json!(["#000000", "#111111"]), &json!(["#111111"]))); } +/// With 256 colours shifted, shifting another colour is refused with the engine's limit error and +/// changes nothing; a shifted colour can still be shifted again or have its shift taken away. +#[test] +fn a_shift_holds_at_most_256_colors() { + let full: serde_json::Map = (0..256).map(|i| (format!("#{i:06x}"), json!("#ffffff"))).collect(); + let mut t = json!({"shifted": full}); + let before = t.clone(); + let e = shift(&mut t, [0x12, 0x34, 0x56], A).unwrap_err(); + assert_eq!((e, &t), (webexport::too_many("shifted"), &before)); + // The Shift edit reports the same error. + let new = [0x12, 0x34, 0x56]; + assert_eq!(run(&mut t, ColorTableEdit::Shift(A), &[new], &[new]), Err(webexport::too_many("shifted"))); + assert_eq!(t, before); + shift(&mut t, [0, 0, 5], A).unwrap(); + assert_eq!((t["shifted"]["#000005"].as_str(), t["shifted"].as_object().map(|m| m.len())), (Some("#000000"), Some(256))); + shift(&mut t, [0, 0, 5], [0, 0, 5]).unwrap(); + shift(&mut t, new, A).unwrap(); + assert_eq!(t["shifted"]["#123456"], "#000000"); +} + +/// Entries the engine drops (a colour shifted to itself, a deleted colour) do not count toward the +/// 256 shifts, and a new shift writes the map without them. A map the engine refuses is kept whole. +#[test] +fn a_shift_skips_entries_the_engine_drops() { + let mut full: serde_json::Map = (0..255).map(|i| (format!("#{i:06x}"), json!(format!("#{i:06x}")))).collect(); + full.insert("#abcdef".into(), json!("#000000")); + let mut t = json!({"shifted": full, "deleted": ["#ABCDEF"]}); + shift(&mut t, [0x12, 0x34, 0x56], A).unwrap(); + assert_eq!(t["shifted"], json!({"#123456": "#000000"})); + for shifted in [json!({"nope": "NOPE"}), json!({"#abcdef": "nope"}), json!({"#f00": "#f00", "#FF0000": "#00ff00"})] { + let mut t = json!({"shifted": shifted.clone(), "deleted": ["#abcdef"]}); + shift(&mut t, [0x12, 0x34, 0x56], A).unwrap(); + let mut want = shifted.as_object().cloned().unwrap_or_default(); + want.insert("#123456".into(), json!("#000000")); + assert_eq!(t["shifted"], Value::Object(want), "{shifted}"); + } +} + +/// A map with more than 256 entries is one the engine refuses, so none of its entries are dropped: +/// with 257 colours shifted to themselves, a new shift and a new target for a shifted colour are +/// refused with the limit error and nothing changes. Taking a shift away still works. +#[test] +fn a_shift_keeps_a_map_over_the_limit_whole() { + let over: serde_json::Map = (0..257).map(|i| (format!("#{i:06x}"), json!(format!("#{i:06x}")))).collect(); + let mut t = json!({"shifted": over}); + let before = t.clone(); + let e = shift(&mut t, [0x12, 0x34, 0x56], A).unwrap_err(); + assert_eq!((e, &t), (webexport::too_many("shifted"), &before)); + let e = shift(&mut t, [0, 0, 5], [0x12, 0x34, 0x56]).unwrap_err(); + assert_eq!((e, &t), (webexport::too_many("shifted"), &before)); + shift(&mut t, [0, 0, 5], [0, 0, 5]).unwrap(); + assert_eq!(t["shifted"].as_object().map(|m| m.len()), Some(256)); +} + +/// A key or list entry written another way (`#F00`, upper case, `blue`) still names its colour: +/// a new shift replaces it, Unshift and the buttons take it out, the marks show it, and a +/// spelling with alpha names no colour. +#[test] +fn table_edits_match_a_color_written_another_way() { + let (red, blue) = ([0xff, 0, 0], [0, 0, 0xff]); + let shown = [red, blue]; + let mut t = json!({"shifted": {"#F00": "#00ff00", "nope": "#000000"}, "webShift": ["#0000FF"]}); + shift(&mut t, red, [0x12, 0x34, 0x56]).unwrap(); + assert_eq!(t["shifted"], json!({"#ff0000": "#123456", "nope": "#000000"})); + shift(&mut t, blue, [0x65, 0x43, 0x21]).unwrap(); + assert_eq!(t["webShift"], json!([])); + // Lock leaves a colour shifted under another spelling alone. + let mut t = json!({"shifted": {"#F00": "#00ff00"}}); + run(&mut t, ColorTableEdit::Lock, &[red], &shown).unwrap(); + assert_eq!(t.get("locked"), None); + // Each list's button takes out an entry written another way, as Unlock, Restore and Unshift do. + for (list, edit) in [("locked", ColorTableEdit::Lock), ("transparent", ColorTableEdit::Transparent), ("webShift", ColorTableEdit::Unshift)] { + let mut t = json!({ list: ["#00F", " #0000FF "] }); + let m = marks(&t); + if list != "webShift" { + assert_eq!(if list == "locked" { m.locked } else { m.transparent }, vec![blue], "{list}"); + } + run(&mut t, edit, &[blue], &shown).unwrap(); + assert_eq!(t[list], json!([]), "{list}"); + } + // Web Shift of a colour in the list under another spelling takes it out. + let mut t = json!({"webShift": ["#00f"]}); + run(&mut t, ColorTableEdit::WebShift, &[blue], &shown).unwrap(); + assert_eq!(t["webShift"], json!([])); + // A spelling with alpha names no colour. + let mut t = json!({"locked": ["#0000ff80"]}); + assert_eq!(marks(&t).locked, Vec::<[u8; 3]>::new()); + run(&mut t, ColorTableEdit::Lock, &[blue], &shown).unwrap(); + assert_eq!(t["locked"], json!(["#0000ff80", "#0000ff"])); +} + +/// Delete Color compares the lists as colours: with blue mapped to transparent as `#00f`, deleting +/// red, the only other colour, is refused with nothing changed, and a deleted colour written +/// another way in `locked` (`blue`, ` #0000FF `) is taken out of the list. +#[test] +fn delete_color_compares_lists_written_another_way() { + let (red, blue) = ([0xff, 0, 0], [0, 0, 0xff]); + let shown = [blue, red]; + let mut t = json!({"transparent": ["#00f"]}); + let before = t.clone(); + assert_eq!(run(&mut t, ColorTableEdit::Delete, &[red], &shown), Err(webexport::KEEP_ONE.to_string())); + assert_eq!(t, before); + let mut t = json!({"locked": ["blue", " #0000FF ", "#ff0000"], "deleted": ["#00F"]}); + run(&mut t, ColorTableEdit::Delete, &[blue], &shown).unwrap(); + assert_eq!((&t["locked"], &t["deleted"]), (&json!(["#ff0000"]), &json!(["#00f"]))); +} + /// One app frame with `events`, a moment after the last. fn app_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) { let time = ctx.input(|i| i.time) + 0.05; @@ -188,6 +295,35 @@ fn a_picked_color_becomes_a_shift_and_cancel_shifts_nothing() { assert_eq!(app.web_export.table["shifted"], json!({"#0000ff": "#00ff00"})); } +/// Done right after the Color Picker's OK, before the dialog draws again, remembers the picked shift. +#[test] +fn done_right_after_the_color_picker_remembers_the_shift() { + let dir = vectorcraft_testkit::temp_dir("sfw-shift-done"); + let (mut app, _) = app(&dir, false); + app.run("shape.rectangle", json!({"x": 40, "y": 0, "width": 20, "height": 40})).unwrap(); + app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap(); + app.run("file.saveForWeb", json!({})).unwrap(); + for (k, v) in [("format", json!("gif")), ("antiAlias", json!("none")), ("dither", json!("none"))] { + set(&mut app, k, v); + } + let ctx = app.ui_ctx.clone().expect("the app has a window"); + crate::dialogs::host::pump(&mut app, &ctx); + let picker = open_cell(&mut app, &ctx, "#0000ff"); + host(&app).with(|h| h.set_json_field(&ctx, picker, "color", json!("#00ff00"))).unwrap(); + host(&app).with(|h| h.confirm_by_id(&ctx, picker)); + // The frame that settles the picker, then Done before the dialog's next pass. + app_frame(&mut app, &ctx, vec![]); + set(&mut app, "choice", json!("done")); + let dialog = id(&app); + host(&app).with(|h| h.confirm_by_id(&ctx, dialog)); + for _ in 0..3 { + app_frame(&mut app, &ctx, vec![]); + } + assert!(host(&app).with(|h| h.get::().is_none()), "Done closes the dialog"); + let remembered = app.session.last_web_settings().color_table.shifted; + assert_eq!(remembered.get("#0000ff").map(String::as_str), Some("#00ff00")); +} + #[test] fn restore_brings_back_a_preview_that_failed() { let dir = vectorcraft_testkit::temp_dir("sfw-restore-table"); diff --git a/crates/ui-egui/src/dialogs/screen_formats.rs b/crates/ui-egui/src/dialogs/screen_formats.rs index 4c85d09837..f01bc521ee 100644 --- a/crates/ui-egui/src/dialogs/screen_formats.rs +++ b/crates/ui-egui/src/dialogs/screen_formats.rs @@ -73,8 +73,9 @@ pub(crate) const SIZES: [&str; 12] = ["0.5x", "0.75x", "1x", "1.5x", "2x", "3x", /// The iOS and Android rows (the engine's `mobile` and `density` presets) and their labels. pub(crate) const PLATFORMS: [(&str, &str); 2] = [("mobile", "iOS"), ("density", "Android")]; -/// The columns of the format rows: scale, suffix, format and the remove button. -const COLUMNS: &[ColumnWidth] = &[ColumnWidth::Content; 4]; +/// The columns of the format rows: scale, suffix and format share the room the remove button leaves. When the +/// fields cannot narrow that far, the grid stacks the cells. +const COLUMNS: &[ColumnWidth] = &[ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::Content]; /// The text of `key` in `fields`, "" when it has none. fn text<'a>(fields: &'a Map, key: &str) -> &'a str { diff --git a/crates/ui-egui/src/dialogs/svg_filter.rs b/crates/ui-egui/src/dialogs/svg_filter.rs index 2185e7ef09..c916cc46d0 100644 --- a/crates/ui-egui/src/dialogs/svg_filter.rs +++ b/crates/ui-egui/src/dialogs/svg_filter.rs @@ -44,6 +44,8 @@ const EDITING: &str = "editing"; const MISSING: &str = "missing"; const ACTION: &str = "__action"; const LISTING: &str = "__list"; +/// The rows the filter list shows before it scrolls. +const LIST_ROWS: u16 = 7; /// The dialog's heading. fn heading() -> String { @@ -169,6 +171,7 @@ fn list_row(ui: &mut egui::Ui, fields: &mut DialogFields, _cx: &mut craft::ui::p let out = List::::new(heading()) .select(SelectMode::Single) .activate(ActivateOn::DoubleClick) + .max_rows(LIST_ROWS) .selection(Bind::bound(&mut selection)) .show_items(ui, &rows, &mut |key, icx| match rows.0.get(icx.at) { Some((_, Kind::Missing)) => ListRow::new(key.clone()).ink(RowInk::Dimmed), @@ -490,6 +493,18 @@ mod tests { assert!(open_dialogs(&app).is_empty()); } + #[test] + fn the_dialog_draws_its_filters_and_buttons() { + let mut app = app(); + rect(&mut app); + let mut p = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs); + crate::menus::invoke(&mut p.app(), "ui.svgFilterDialog", json!({})); + p.frame(); + for name in [DEFAULT_FILTERS[0].name, "New", "OK", "Cancel"] { + assert!(p.shows(name), "{name} is drawn"); + } + } + #[test] fn opened_for_an_applied_filter_ok_replaces_it() { let mut app = app(); diff --git a/crates/ui-egui/src/menus/model.rs b/crates/ui-egui/src/menus/model.rs index 1ff1ce27e0..f812f1c784 100644 --- a/crates/ui-egui/src/menus/model.rs +++ b/crates/ui-egui/src/menus/model.rs @@ -86,6 +86,9 @@ pub(crate) fn state_key(app: &VectorcraftApp, input: Option) -> u64 { let mut h = DefaultHasher::new(); input.hash(&mut h); app.run_count.hash(&mut h); + // The window's keymap, which the panel rows read their shortcuts from (`Build::decorate`): the framework builds it + // after the first frame's menus, and builds a new one when the bindings or the catalog change. + app.ui_ctx.as_ref().and_then(craft::ui::runtime::commands::keymap).map(|k| std::sync::Arc::as_ptr(&k).addr()).hash(&mut h); let s = &app.session; (s.journal.len(), s.active_index(), s.clipboard.is_empty(), s.tool_composing()).hash(&mut h); if let Some(d) = s.active() { @@ -473,11 +476,18 @@ impl Build<'_> { item_title(self.app, self.lang, id, params, label) } - /// The alternates (a modifier held as the row is chosen) and the font sample of a row. + /// The alternates (a modifier held as the row is chosen), the font sample and the shortcut of a row. fn decorate(&self, item: Item, id: &str, params: &Value) -> Item { let run_with = |mods: Mods, p: Value| Alternate::new(mods, CommandRef::with_params(id, p)); let held = |shift: bool, alt: bool| Mods { cmd: false, ctrl: false, alt, shift }; match id { + // A panel row shows the chord of the panel's shortcut (`panel:`), which binds `window.panel {panel}`; + // a Window row runs it with `toggle: true`, so the framework finds no chord for the row's own command. + "window.panel" => { + let mut item = item; + item.shortcut = super::labels::item_shortcut(self.app, id, params); + item + } "ui.expandDialog" => item.alternate(run_with(held(false, true), json!({ "immediate": true }))), crate::addons::select::link_status::COMMAND => { item.alternate(run_with(held(true, false), crate::addons::select::link_status::with_shift(params.clone()))) diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index d9edd18bb2..1071d14108 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -1007,6 +1007,8 @@ mod tests_effectedit; #[cfg(test)] mod tests_freeform; #[cfg(test)] +mod tests_icon_buttons; +#[cfg(test)] mod tests_links; #[cfg(test)] mod tests_maskview; diff --git a/crates/ui-egui/src/panels/layers/cells.rs b/crates/ui-egui/src/panels/layers/cells.rs index db6e0c342d..c557023bcf 100644 --- a/crates/ui-egui/src/panels/layers/cells.rs +++ b/crates/ui-egui/src/panels/layers/cells.rs @@ -24,7 +24,7 @@ use egui::{Color32, CornerRadius, Pos2, Rect, Response, Vec2, vec2}; use super::model::{DocLayers, RowId}; use super::rows::{TARGET_RADIUS, has_styled_target, shows_targeted, target_marks}; -use super::{NodeId, Value, json}; +use super::{Node, NodeId, Value, json}; use crate::panel_drag::PanelDrag; /// The side of the square of a row whose art is selected. @@ -193,8 +193,9 @@ impl Component for TargetCircle { } } -/// A row's selection square: filled in its layer's colour while the row's art is selected, a small -/// square while the row holds selected art. Without `id` it is only a mark (a ruler guide's row, a +/// A row's selection square: filled in its layer's colour while the row's art is selected (for a +/// layer or sublayer, all of its visible, unlocked art), a small square while the row holds +/// selected art. Without `id` it is only a mark (a ruler guide's row, a /// spine's row) and takes no press. #[derive(Component, Props)] #[component(sample = SelectionSquare::sample)] @@ -346,6 +347,19 @@ impl Component for Cells { } } +/// The marks of node row `n`'s selection square in the panel over `tree`: whether it shows the +/// full-sized square (the row is selected, or it is a layer or sublayer whose visible, unlocked art +/// is all selected), and whether it shows the small one (it holds selected art otherwise). +pub(super) fn square_marks(tree: &DocLayers<'_>, n: &Node) -> (bool, bool) { + let full = tree.is_selected(n.id) || tree.is_full(n.id); + let holds = !full && { + let mut any = false; + n.walk(&mut |c| any |= c.id != n.id && tree.is_selected(c.id)); + any + }; + (full, holds) +} + /// The cells of row `row` (shown as `info`) of the panel over `tree`. pub(super) fn build(tree: &DocLayers<'_>, row: &RowId, info: &LayerInfo) -> Cells { let st = tree.state(); @@ -355,15 +369,11 @@ pub(super) fn build(tree: &DocLayers<'_>, row: &RowId, info: &LayerInfo) -> Cell RowId::Node(id) => { let Some(n) = tree.doc().node(id) else { return Cells::new(None, SelectionSquare::new(None, false, false, color, vec![])) }; let is_sel = selected(id); - let holds = !is_sel && { - let mut any = false; - n.walk(&mut |c| any |= c.id != id && selected(c.id)); - any - }; - let art = if is_sel || holds { st.selection.objects.clone() } else { vec![] }; + let (full, holds) = square_marks(tree, n); + let art = if full || holds { st.selection.objects.clone() } else { vec![] }; let circle = TargetCircle::new(id, shows_targeted(tree, n, is_sel), has_styled_target(n)) .label(crate::i18n::fmt(tl!("Target {row}"), &[("row", info.name.as_str())])); - let square = SelectionSquare::new(Some(id), is_sel, holds, color, art) + let square = SelectionSquare::new(Some(id), full, holds, color, art) .label(crate::i18n::fmt(tl!("Select art of {row}"), &[("row", info.name.as_str())])); Cells::new(Some(circle), square) } diff --git a/crates/ui-egui/src/panels/layers/model.rs b/crates/ui-egui/src/panels/layers/model.rs index 46d24e0806..619fcd6559 100644 --- a/crates/ui-egui/src/panels/layers/model.rs +++ b/crates/ui-egui/src/panels/layers/model.rs @@ -182,6 +182,10 @@ pub(super) struct LayerRows { /// The selected objects. #[plain_data(assume = "node ids are integers")] selected: HashSet, + /// The layers and sublayers whose visible, unlocked art ([`Node::layer_art`]) is all selected + /// and not empty. + #[plain_data(assume = "node ids are integers")] + full: HashSet, /// The selected blends, in selection order. #[plain_data(assume = "node ids are integers")] blends: Vec, @@ -228,6 +232,7 @@ impl LayerRows { let ruler = doc.ruler_guides(); let guide_rows = ruler.iter().enumerate().filter_map(|(i, g)| Some((g.id?, i))).collect(); let blends = st.selection.objects.iter().copied().filter(|id| doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Blend { .. }))); + let selected: HashSet = st.selection.objects.iter().copied().collect(); Self { doc: doc.clone(), opts: app.ui.layers_panel.clone(), @@ -239,7 +244,8 @@ impl LayerRows { guides: vectorcraft_engine::cmd::guide_indexes(doc, &st.selection.guides), ruler, guide_rows, - selected: st.selection.objects.iter().copied().collect(), + full: super::rows::full_layers(doc, &selected), + selected, blends: blends.collect(), root: st.isolation.and_then(|i| isolated_root(doc, i)).map(|(n, ..)| n.id), } @@ -291,6 +297,12 @@ impl LayerRows { self.selected.contains(&id) } + /// Whether `id` is a layer or sublayer whose visible, unlocked art is all selected and not + /// empty. + pub(super) fn is_full(&self, id: NodeId) -> bool { + self.full.contains(&id) + } + /// The node ids a row menu's command acts on: every highlighted row when the menu's row is one of /// them, else the row's own node. pub(super) fn targets(&self, target: &MenuTarget) -> Vec { diff --git a/crates/ui-egui/src/panels/layers/rows.rs b/crates/ui-egui/src/panels/layers/rows.rs index 5359ba672e..20c81d8f91 100644 --- a/crates/ui-egui/src/panels/layers/rows.rs +++ b/crates/ui-egui/src/panels/layers/rows.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use craft::behavior::{EditEvent, SelectionChange}; use craft::keymap::{CommandRef, Mods}; use craft::layers::ui::panel::{ActivateOn, LayerColumn, LayerDrop, LayerMove, LayerPosition, LayerSelect, LayerToggle, LayersEvent}; @@ -110,17 +112,44 @@ pub(super) fn locate_layer_listed(doc: &Document, root: Option) -> bool pub(super) fn shows_targeted(tree: &DocLayers<'_>, n: &Node, is_sel: bool) -> bool { match tree.state().selection.target { Some(id) => id == n.id, - None if n.is_layer() => { - if tree.state().selection.objects.is_empty() { - return false; - } - let art = n.layer_art(true); - !art.is_empty() && art.iter().all(|id| tree.is_selected(*id)) - } + None if n.is_layer() => tree.is_full(n.id), None => is_sel, } } +/// The layers and sublayers of `doc` whose [`Node::layer_art`] with `editable` is not empty and +/// all in `sel`, found in one pass over the layers and their direct children. +pub(super) fn full_layers(doc: &Document, sel: &HashSet) -> HashSet { + /// Adds `layer` to `out` when it is full, and returns its art's count and selected count. + fn visit(layer: &Node, sel: &HashSet, out: &mut HashSet) -> (usize, usize) { + let (mut art, mut selected) = (0, 0); + for c in layer.children().into_iter().flatten() { + let counts = !(c.is_ruler_guide() || !c.visible || c.locked || c.is_template()); + if c.is_layer() { + let (a, s) = visit(c, sel, out); + if counts { + art += a; + selected += s; + } + } else if counts { + art += 1; + selected += usize::from(sel.contains(&c.id)); + } + } + if art > 0 && selected == art { + out.insert(layer.id); + } + (art, selected) + } + let mut out = HashSet::new(); + if !sel.is_empty() { + for layer in doc.layers.iter().filter(|l| l.is_layer()) { + visit(layer, sel, &mut out); + } + } + out +} + /// The `layer.target` of a click with `mods` on the target circle of `id`, by the rules of a row click (#8639): plain /// targets it, Ctrl/Cmd adds it to the selection or takes it out, Shift selects the art of every row `filter` lists /// from `anchor` (the last circle clicked, else the targeted row) to it, and Shift+Ctrl/Cmd adds that art. With it, diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index 2ac1b0af3f..172bf59860 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -561,3 +561,98 @@ fn the_target_circle_anchor_does_not_carry_over_to_another_document() { panel.click_with("Target B", egui::Modifiers::SHIFT); assert_eq!(targeted(&panel.app()), (Some(b2), vec![b2])); } + +/// The rows among `rows` whose selection square is full-sized, then those whose square is the +/// small one, in the order given. +fn squares(app: &VectorcraftApp, rows: &[NodeId]) -> (Vec, Vec) { + let st = app.session.active().unwrap(); + let tree = DocLayers::new(app, st); + let (mut full, mut small) = (vec![], vec![]); + for &id in rows { + match cells::square_marks(&tree, st.doc.node(id).unwrap()) { + (true, _) => full.push(id), + (false, true) => small.push(id), + (false, false) => {} + } + } + (full, small) +} + +/// A layer or sublayer whose selectable art is all selected shows the full-sized square; one +/// holding some of its art, or a group's member instead of the group, shows the small one. +#[test] +fn a_layer_with_all_its_art_selected_shows_the_full_square() { + use crate::tests::panel_harness::Panel; + use egui::Modifiers; + let (mut app, [layer, sub, g, b, a, c]) = nested(); + let rows = [layer, sub, g, b, a, c]; + name_row(&mut app, layer, "Top"); + name_row(&mut app, sub, "Sub"); + name_row(&mut app, a, "A"); + app.session.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + assert_eq!(squares(&app, &rows), (vec![a], vec![layer, sub]), "the rectangle's square, small ones on the sublayer and the layer"); + app.session.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + assert_eq!(squares(&app, &rows), (vec![b, a], vec![layer, sub, g]), "a group's member is not the group: the sublayer's square stays small"); + let mut panel = Panel::new(app, show); + panel.click_with("Select art of Sub", Modifiers::NONE); + assert_eq!(squares(&panel.app(), &rows), (vec![sub, g, a], vec![layer]), "the sublayer, its group and rectangle full, the layer small"); + panel.click_with("Select art of Top", Modifiers::NONE); + assert_eq!(squares(&panel.app(), &rows), (vec![layer, sub, g, a, c], vec![]), "the layer and the sublayer full, with each row's art"); + panel.click_with("Select art of A", Modifiers::SHIFT); + assert_eq!(squares(&panel.app(), &rows), (vec![g, c], vec![layer, sub]), "one rectangle let go: the layer and the sublayer small again"); + // Locked art cannot be selected, so it does not keep the layer's square small. + panel.app().session.execute("layer.setProps", &json!({"ids": [c.0], "locked": true})).unwrap(); + panel.click_with("Select art of Sub", Modifiers::NONE); + assert_eq!(squares(&panel.app(), &rows), (vec![layer, sub, g, a], vec![]), "the layer, the sublayer, the group and the rectangle"); + // Hidden art neither. + panel.app().session.execute("layer.setProps", &json!({"ids": [c.0], "locked": false, "visible": false})).unwrap(); + panel.app().session.execute("select.set", &json!({"ids": [a.0, g.0]})).unwrap(); + assert_eq!(squares(&panel.app(), &rows), (vec![layer, sub, g, a], vec![]), "hidden art is left out"); + // With nothing targeted, the full layers' target circles show as targeted too. + let app = panel.app(); + let st = app.session.active().unwrap(); + let tree = DocLayers::new(&app, st); + assert!(rows::shows_targeted(&tree, st.doc.node(layer).unwrap(), false), "the layer shows as targeted"); +} + +/// A layer with no selectable art shows no square, whatever else is selected. +#[test] +fn a_layer_without_art_shows_no_square() { + let (mut app, [layer, sub, g, b, a, c]) = nested(); + let empty = NodeId(app.session.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + app.session.execute("select.set", &json!({"ids": [c.0, a.0, g.0]})).unwrap(); + let rows = [empty, layer, sub, g, b, a, c]; + assert_eq!(squares(&app, &rows), (vec![layer, sub, g, a, c], vec![]), "the first layer's rows; the new, empty layer's none"); +} + +/// The panel's set of full layers is the layers and sublayers whose `layer_art(true)` is not empty +/// and all selected, for every selection of the document's objects, hidden and locked ones included. +#[test] +fn full_layers_are_the_layers_with_all_their_art_selected() { + let (mut app, [_, _, _, _, _, c]) = nested(); + let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap(); + let id = |v: serde_json::Value| NodeId(v["id"].as_u64().unwrap()); + let hidden = id(run(&mut app, "layer.newSublayer", json!({"name": "Hidden"}))); + run(&mut app, "shape.rectangle", json!({"x": 200, "y": 0, "width": 20, "height": 20})); + run(&mut app, "layer.setProps", json!({"ids": [hidden.0], "visible": false})); + run(&mut app, "layer.setProps", json!({"ids": [c.0], "locked": true})); + run(&mut app, "layer.new", json!({})); + let doc = app.session.active().unwrap().doc.clone(); + let (mut layers, mut objects) = (vec![], vec![]); + for l in &doc.layers { + l.walk(&mut |n| if n.is_layer() { layers.push(n) } else { objects.push(n.id) }); + } + assert_eq!((layers.len(), objects.len()), (4, 5), "the layers, the sublayers and the objects"); + for bits in 0u32..(1 << objects.len()) { + let sel: HashSet = objects.iter().enumerate().filter(|(i, _)| (bits >> i) & 1 == 1).map(|(_, id)| *id).collect(); + let want: HashSet = layers + .iter() + .filter(|l| { + let art = l.layer_art(true); + !art.is_empty() && art.iter().all(|i| sel.contains(i)) + }) + .map(|l| l.id) + .collect(); + assert_eq!(rows::full_layers(&doc, &sel), want, "selection {bits:b}"); + } +} diff --git a/crates/ui-egui/src/panels/paragraph/tests.rs b/crates/ui-egui/src/panels/paragraph/tests.rs index 6522c5af4e..48b324ccf4 100644 --- a/crates/ui-egui/src/panels/paragraph/tests.rs +++ b/crates/ui-egui/src/panels/paragraph/tests.rs @@ -558,6 +558,24 @@ fn more_options_opens_bullets_and_numbering_on_its_tab() { assert!(shown_tab(&app).is_some()); } +/// Bullets and Numbering draws every preset of each tab, and its buttons. +#[test] +fn bullets_and_numbering_draws_every_preset_and_its_buttons() { + use vectorcraft_doc::text::NumberStyle; + crate::i18n::set_current(crate::i18n::Lang::EN); + let (app, _) = editing_text("One\nTwo"); + let mut p = crate::tests::panel_harness::Panel::new(crate::testing::windowed(app), crate::tests::picks::dialogs); + select_range(&mut p.app(), 0, 0); + let last_number = NumberStyle::ALL.last().map(|&style| crate::panels::paragraph::number_sample(style, 3)).unwrap_or_default(); + for (tab, last) in [("bullets", "Filled Square".to_owned()), ("numbers", last_number)] { + p.app().run("ui.bulletsAndNumbering", json!({ "tab": tab })).unwrap(); + p.frame(); + for name in ["None", last.as_str(), "OK", "Cancel"] { + assert!(p.shows(name), "{name} is drawn on {tab}"); + } + } +} + /// Type › Bullets and Numbering › Convert to Text (`type.convertListToText`) acts on the /// paragraphs the Type tool's selection touches: their numbers become characters of the text /// and their list goes, while the other paragraphs stay in the list, and the Type tool's caret diff --git a/crates/ui-egui/src/panels/swatches/dnd.rs b/crates/ui-egui/src/panels/swatches/dnd.rs index 07db27100c..dd3aff50f9 100644 --- a/crates/ui-egui/src/panels/swatches/dnd.rs +++ b/crates/ui-egui/src/panels/swatches/dnd.rs @@ -112,16 +112,17 @@ pub(super) enum FooterTarget { /// the button does. Other drags are left to their own targets. pub(super) fn on_footer_drop(app: &mut VectorcraftApp, target: FooterTarget, drag: &PanelDrag) { let PanelDrag::Paint { rows: Some(r), .. } = drag else { return }; + let rows = footer_rows(app, r); match target { FooterTarget::Delete => { - let names = super::actions::deletable(app, &r.names); + let names = super::actions::deletable(app, &rows); if !names.is_empty() { super::actions::delete(app, names, false); } } FooterTarget::New => { let Some(st) = app.session.active() else { return }; - let names: Vec = r.names.iter().filter(|n| st.doc.swatch(n).is_some_and(|w| !w.is_reserved())).cloned().collect(); + let names: Vec = rows.iter().filter(|n| st.doc.swatch(n).is_some_and(|w| !w.is_reserved())).cloned().collect(); if !names.is_empty() { super::actions::duplicate(app, &names); } @@ -129,6 +130,22 @@ pub(super) fn on_footer_drop(app: &mut VectorcraftApp, target: FooterTarget, dra } } +/// The rows a drop on a footer button takes. A grabbed row that is part of the panel's selection +/// carries every selected row of its kind (swatches or color groups), also those that the find +/// field or the kind filter hides, in panel order, as a click on the button takes the whole +/// selection. Any other grabbed row carries the rows `r` holds. +fn footer_rows(app: &VectorcraftApp, r: &SwatchRows) -> Vec { + let sel = super::selected(app); + if !sel.contains(&r.grabbed) { + return r.names.clone(); + } + super::shown_keys(&super::groups(app, super::Kind::All, "")) + .iter() + .filter(|k| matches!(k, SwatchKey::Group(_)) == r.groups && sel.iter().any(|s| s == name_of(k))) + .map(|k| name_of(k).to_string()) + .collect() +} + /// The colour group `name` is, or the one swatch `name` belongs to. pub(super) fn group_of(d: &Document, name: &str) -> Option { if d.swatch_groups.iter().any(|g| g.name == name) { diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index 2653fd5b8c..b638b289f5 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -551,6 +551,44 @@ fn drops_on_the_buttons_and_the_panel_run_their_commands() { } } +/// A selected swatch dragged onto New Swatch or Delete Swatch carries the selected swatches that +/// the find field hides, which the browser leaves out of the drag, as a click on Delete Swatch +/// takes them too. The copies are selected in panel order. A grabbed swatch outside the selection +/// carries only itself. +#[test] +fn footer_drops_carry_selected_swatches_that_find_hides() { + let mut app = app(); + let key = crate::dialogs::confirm::KIND; + app.ui.swatches_panel.show_find = true; + app.ui.swatches_panel.state.browser.filter = "Orange".into(); + let order = names_of(&app, None); + let at = |n: &str| order.iter().position(|x| x == n).unwrap_or_else(|| panic!("no swatch {n}")); + let mut copies = vec![("Lime", "Lime copy"), ("Orange", "Orange copy")]; + copies.sort_by_key(|(n, _)| at(n)); + let copies: Vec = copies.into_iter().map(|(_, c)| c.to_string()).collect(); + // With Find set to Orange, the browser's drag holds only the selected row it shows. + let drag = rows_drag(&app, "Orange", &["Orange"]); + select_rows(&mut app, &["Lime", "Orange"]); + let undo = undo_steps(&app); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::New, &drag); + let d = doc(&app); + assert!(d.swatch("Orange copy").is_some() && d.swatch("Lime copy").is_some(), "the hidden selected swatch is duplicated too"); + assert_eq!(selected(&app), copies, "both copies are selected, in panel order"); + assert_eq!(undo_steps(&app), undo + 1, "one undo step for both"); + select_rows(&mut app, &["Lime", "Orange"]); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::Delete, &drag); + assert!(dialog_open(&app, key), "Delete asks first"); + confirm(&mut app, key); + let d = doc(&app); + assert!(d.swatch("Orange").is_none() && d.swatch("Lime").is_none(), "the hidden selected swatch is deleted too"); + // A grabbed swatch outside the selection carries only itself. + let drag = rows_drag(&app, "Orange copy", &["Orange copy"]); + select_rows(&mut app, &["Lime copy"]); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::New, &drag); + let d = doc(&app); + assert!(d.swatch("Orange copy copy").is_some() && d.swatch("Lime copy copy").is_none(), "only the grabbed swatch is duplicated"); +} + #[test] fn art_dropped_on_the_panel_becomes_a_pattern_swatch() { let mut app = app(); diff --git a/crates/ui-egui/src/panels/tabs.rs b/crates/ui-egui/src/panels/tabs.rs index aea3b477f0..47a0508f5d 100644 --- a/crates/ui-egui/src/panels/tabs.rs +++ b/crates/ui-egui/src/panels/tabs.rs @@ -1,4 +1,5 @@ -//! Tabs panel: tab-stop alignment, X position (Y in vertical type), leader and "align on", and the +//! Tabs panel: tab-stop alignment, X position (Y in vertical type; a position typed there for a +//! paragraph with no stops adds a stop at it), leader and "align on", and the //! framework's text ruler numbered in the General unit, on which a click adds a stop, dragging moves //! one and dragging it off the ruler deletes it. Ctrl-dragging a stop (Command on macOS) moves all the //! stops by the same distance. A stop lands on the ruler's step, or free with Alt held. While a stop is @@ -677,8 +678,10 @@ pub(crate) fn apply_ruler_edit(app: &mut VectorcraftApp, node: &Node, para: &Par } /// The X (Y in vertical type) field's `value`: a picked marker moves to it, else the picked stop -/// does and stays picked after the stops are sorted. A position past [`MAX_STOP`] is refused by -/// `text.tabs.set` and nothing changes. `picked`: the stop and the marker of [`TabsPanel`]. +/// does and stays picked after the stops are sorted. A paragraph with no stops and no picked marker +/// gets a stop there with the panel's alignment, which is then picked, as a click on the ruler adds +/// one. A position past [`MAX_STOP`] is refused by `text.tabs.set` and nothing changes. `picked`: +/// the stop and the marker of [`TabsPanel`]. pub(crate) fn set_position(app: &mut VectorcraftApp, node: &Node, para: &ParaStyle, span: f64, picked: (usize, Option), value: f64) { let (stop, marker) = picked; match marker { @@ -692,6 +695,13 @@ pub(crate) fn set_position(app: &mut VectorcraftApp, node: &Node, para: &ParaSty set_marker(app, marker, value, para, span, &targets, false); } } + None if para.tabs.is_empty() => { + let align = app.ui.tabs_panel.align; + let added = TabStop { position: value.max(0.0), align, leader: String::new(), align_on: '.' }; + if apply(app, std::slice::from_ref(&added)) { + app.ui.tabs_panel.stop = 0; + } + } None => { let mut stops = para.tabs.clone(); if let Some(i) = apply_moved(app, &mut stops, stop, value.max(0.0)) { diff --git a/crates/ui-egui/src/panels/tabs/tests.rs b/crates/ui-egui/src/panels/tabs/tests.rs index 28d614a928..7aacaaf1f8 100644 --- a/crates/ui-egui/src/panels/tabs/tests.rs +++ b/crates/ui-egui/src/panels/tabs/tests.rs @@ -759,6 +759,80 @@ fn an_x_typed_past_the_next_stop_keeps_the_stop_selected() { assert_eq!(app.ui.tabs_panel.stop, 0); } +/// The undo steps of the active document. +fn undo_steps(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() +} + +/// A position typed in the X field of a paragraph with no stops adds a stop there with the chosen +/// alignment, keeps its hundredths of a point, picks it, and is one undo step. +#[test] +fn typing_x_into_a_paragraph_without_stops_adds_and_selects_a_stop() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({})).unwrap(); + app.run("text.create", json!({"x": 10, "y": 20, "text": "a\tb", "area": {"width": 300, "height": 100}})).unwrap(); + assert!(current(&app).unwrap().1.is_empty()); + app.ui.tabs_panel.align = TabAlign::Right; + app.ui.tabs_panel.stop = 3; + let before = undo_steps(&app); + type_position(&mut app, 36.47); + let stops = current(&app).unwrap().1; + assert_eq!(stops.iter().map(|s| (s.position, s.align)).collect::>(), [(36.47, TabAlign::Right)]); + assert_eq!(app.ui.tabs_panel.stop, 0); + assert_eq!(undo_steps(&app), before + 1); + app.run("edit.undo", json!({})).unwrap(); + assert!(current(&app).unwrap().1.is_empty()); +} + +/// In vertical type the position field is Y, and a position typed there for a paragraph with no +/// stops adds a stop. +#[test] +fn typing_y_into_vertical_type_without_stops_adds_a_stop() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({})).unwrap(); + app.run("text.create", json!({"x": 10, "y": 20, "text": "a\tb", "vertical": true})).unwrap(); + type_position(&mut app, 48.0); + let stops = current(&app).unwrap().1; + assert_eq!(stops.iter().map(|s| (s.position, s.align)).collect::>(), [(48.0, TabAlign::Left)]); +} + +/// A first stop past 100,000 pt adds no stop and records no undo step. A negative position adds +/// the stop at 0 pt. +#[test] +fn a_refused_first_stop_adds_nothing_and_records_no_undo() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({})).unwrap(); + app.run("text.create", json!({"x": 10, "y": 20, "text": "a\tb", "area": {"width": 300, "height": 100}})).unwrap(); + let before = undo_steps(&app); + type_position(&mut app, 200000.0); + assert!(current(&app).unwrap().1.is_empty()); + assert_eq!(undo_steps(&app), before); + type_position(&mut app, -5.0); + assert_eq!(stop_positions(&app), [0.0]); + assert_eq!(undo_steps(&app), before + 1); +} + +/// With the Selection tool on two texts, a first stop typed for the shown text, which has no +/// stops, becomes every selected text's stops in one undo step, replacing the other text's stop. +#[test] +fn typing_the_first_stop_over_mixed_paragraphs_uses_the_displayed_list() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({})).unwrap(); + let id = |v: serde_json::Value| v["id"].as_u64().unwrap(); + let a = id(app.run("text.create", json!({"x": 10, "y": 20, "text": "a\tb", "area": {"width": 300, "height": 60}})).unwrap()); + let b = id(app.run("text.create", json!({"x": 10, "y": 100, "text": "c\td", "area": {"width": 250, "height": 60}})).unwrap()); + app.run("select.set", json!({"ids": [b]})).unwrap(); + app.run("text.tabs.set", json!({"stops": [{"position": 90}]})).unwrap(); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + assert_eq!(current(&app).unwrap().0.id.0, a); + let before = undo_steps(&app); + type_position(&mut app, 25.0); + for text in [a, b] { + assert_eq!(text_of(&app, text).para_at(0).tabs.iter().map(|s| s.position).collect::>(), [25.0], "text {text}"); + } + assert_eq!(undo_steps(&app), before + 1); +} + /// The panel menu's Repeat Tab, Delete Tab and Clear All Tabs can be chosen while the text has /// tab stops and show no check mark. Repeat Tab and Delete Tab act on the stop selected on the /// ruler, and Clear All Tabs removes every stop. diff --git a/crates/ui-egui/src/panels/tests_asset_export.rs b/crates/ui-egui/src/panels/tests_asset_export.rs index af4efb3e09..bde196ffd2 100644 --- a/crates/ui-egui/src/panels/tests_asset_export.rs +++ b/crates/ui-egui/src/panels/tests_asset_export.rs @@ -937,6 +937,35 @@ fn tile_menu_rename_opens_the_clicked_assets_inline_field() { assert_eq!(assets(&mut p.app())[0]["name"], "Renamed"); } +/// In a panel narrower than the scale row's fields at their full length, the row's Scale, Suffix, Format and Remove +/// share the panel's width, and the Save As Preset row under them stays inside it too. +#[test] +fn the_scale_row_fits_the_panel_width() { + use craft::ui::contract::Role; + for width in [300.0, 440.0] { + let (mut app, _, [a, b]) = app(true); + app.run("assets.add", json!({"ids": [a, b]})).unwrap(); + let mut p = panel(app); + p.room(egui::vec2(width, 1600.0)); + p.frame(); + run(&p, "ui.assetExport.savePresetAs", json!({})); + p.frame(); + let controls = [ + ("Scale", p.rect_role("Scale", Role::COMBO_BOX)), + ("Suffix", p.rect("Suffix")), + ("Format", p.rect_role("Format", Role::COMBO_BOX)), + ("Remove", p.rect("Remove")), + ("Name:", p.rect_role("Name:", Role::TEXT_INPUT)), + ("Cancel", p.rect("Cancel")), + ]; + // The four controls of the scale row are on one line. + assert_eq!(controls[0].1.center().y, controls[3].1.center().y, "one row at {width}"); + for (name, rect) in controls { + assert!(rect.left() >= -0.5 && rect.right() <= width + 0.5, "{name} at {rect:?} is outside a {width} pt panel"); + } + } +} + /// The menu adds the selected artwork as one asset or one per object (an object that is an asset already keeps its /// asset), and is off with no artwork selected. #[test] diff --git a/crates/ui-egui/src/panels/tests_icon_buttons.rs b/crates/ui-egui/src/panels/tests_icon_buttons.rs new file mode 100644 index 0000000000..b7a1ee607e --- /dev/null +++ b/crates/ui-egui/src/panels/tests_icon_buttons.rs @@ -0,0 +1,61 @@ +//! Headless frames of the Align and Pathfinder panels' icon buttons: each icon fills its glyph square as the app's +//! Lucide icons do. + +use egui::{ImageData, Rect, Shape, TextureId}; +use serde_json::json; + +use super::tests_appearance::{app_with_rect, run}; +use super::*; +use crate::tests::panel_harness::Panel; + +/// The share of its square a Lucide icon's art may span: the Lucide grid keeps 2 of its 24 units clear on each side. +const LUCIDE_ART: f32 = 20.0 / 24.0; + +/// The longer side of the inked pixels of the icon drawn inside `rect`, as a share of the icon's image side. +fn ink_share(shapes: &[Shape], images: &[(TextureId, ImageData)], rect: Rect) -> f32 { + let mut shares = shapes.iter().filter_map(|shape| match shape { + Shape::Mesh(mesh) if mesh.texture_id != TextureId::default() && rect.contains_rect(mesh.calc_bounds()) => { + let image = images.iter().find(|(id, _)| *id == mesh.texture_id).map(|(_, image)| image); + let Some(ImageData::Color(image)) = image else { panic!("no image for the icon's texture in this frame") }; + let [w, h] = image.size; + let inked = |x: usize, y: usize| image.pixels[y * w + x].a() > 0; + let cols: Vec = (0..w).filter(|&x| (0..h).any(|y| inked(x, y))).collect(); + let rows: Vec = (0..h).filter(|&y| (0..w).any(|x| inked(x, y))).collect(); + let span = |v: &[usize]| v.first().zip(v.last()).map_or(0, |(a, b)| b - a + 1); + Some(span(&cols).max(span(&rows)) as f32 / w.max(h) as f32) + } + _ => None, + }); + shares.next().unwrap_or_else(|| panic!("no icon drawn in {rect:?}")) +} + +/// Two selected rectangles, so every button is on. +fn two_rects() -> VectorcraftApp { + let mut app = app_with_rect(); + run(&mut app, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})); + run(&mut app, "select.all", json!({})); + app +} + +fn assert_full_size(draw: fn(&mut VectorcraftApp, &mut egui::Ui), names: &[&str]) { + let mut panel = Panel::new(two_rects(), draw); + // A new pixel density draws every icon again, so the frame carries their images. + let (shapes, images) = panel.paint_at(2.0); + for name in names { + let share = ink_share(&shapes, &images, panel.rect(name)); + assert!(share >= LUCIDE_ART, "{name}: the icon spans {share} of its square, less than a Lucide icon's {LUCIDE_ART}"); + } +} + +#[test] +fn the_align_panel_icons_fill_their_square() { + let mut names: Vec<&str> = align::ALIGN.iter().chain(&align::DISTRIBUTE).map(|r| r.1).collect(); + names.extend(["Vertical Distribute Space", "Horizontal Distribute Space"]); + assert_full_size(align::show, &names); +} + +#[test] +fn the_pathfinder_panel_icons_fill_their_square() { + let names: Vec<&str> = pathfinder::SHAPE_MODES.iter().chain(&pathfinder::PATHFINDERS).map(|r| r.1).collect(); + assert_full_size(pathfinder::show, &names); +} diff --git a/crates/ui-egui/src/prefs_dialog/descriptions.rs b/crates/ui-egui/src/prefs_dialog/descriptions.rs index ad3b05db4a..94015ffd6a 100644 --- a/crates/ui-egui/src/prefs_dialog/descriptions.rs +++ b/crates/ui-egui/src/prefs_dialog/descriptions.rs @@ -42,6 +42,7 @@ pub(crate) const DESCRIPTIONS: &[(&str, &str)] = &[ ("trackpadRotateView", "A two-finger rotate gesture on a trackpad rotates the canvas view."), ("interpolateControlPoints", "When you move anchor points, each curve with one moved end keeps its shape relative to its ends."), ("deleteKeepsPathsJoined", "Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there."), + ("doubleClickAddsAnchorPoints", "Double-clicking a path segment with the Direct Selection tool adds an anchor point there."), ("holdToolKeys", "Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again."), ("holdShortcuts", "Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut."), ("keyHoldDelay", "How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut."), diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index 5ccce9988c..453dc2f391 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -991,11 +991,13 @@ fn is_tool(def: &CommandDef) -> bool { matches!(def.kind, CommandKind::Tool { .. }) } -/// The app's rule for the keys a command takes: a tool's shortcut is one key, alone or with Shift. +/// The app's rule for the keys a command takes: a tool's shortcut is one key, alone or with Shift, +/// or the tool's own default (the Quick Pen's Alt+P). fn accept(def: &CommandDef, binding: &Binding) -> Result<(), String> { let t = binding.trigger; let one_key = matches!(t.press, PressKind::Single) && !(t.chord.mods.cmd || t.chord.mods.ctrl || t.chord.mods.alt); - if is_tool(def) && !t.is_hold() && !one_key { + let own_default = def.defaults.iter().any(|d| d.trigger == t); + if is_tool(def) && !t.is_hold() && !one_key && !own_default { Err(tl!("tool shortcuts must be a single key (optionally with Shift)").to_string()) } else { Ok(()) @@ -1685,6 +1687,22 @@ mod tests { } } + /// A tool whose default has a modifier takes that default back after it was cleared; other + /// modifier shortcuts for it, and its default for another tool, are still refused. + #[test] + fn a_tool_takes_back_its_own_default_with_alt() { + let (mut app, _ctx) = app(); + app.run("shortcuts.set", json!({"id": "tool:quickPen", "shortcut": ""})).unwrap(); + assert_eq!(row(&mut app, "tool:quickPen").unwrap()["shortcut"], Value::Null); + app.run("shortcuts.set", json!({"id": "tool:quickPen", "shortcut": "Alt+P"})).unwrap(); + assert_eq!(row(&mut app, "tool:quickPen").unwrap()["shortcut"], spelled("Alt+P")); + for text in ["Alt+Q", "Cmd+P"] { + assert!(app.run("shortcuts.set", json!({"id": "tool:quickPen", "shortcut": text})).is_err(), "{text}"); + } + assert!(app.run("shortcuts.set", json!({"id": "tool:pen", "shortcut": "Alt+P", "force": true})).is_err()); + assert_eq!(row(&mut app, "tool:quickPen").unwrap()["shortcut"], spelled("Alt+P")); + } + /// `shortcuts.export` writes the set in use as craft-keymap JSON, which `shortcuts.import` /// reads back to the same shortcuts; a set in the form earlier versions wrote imports too, and a /// file in neither form changes nothing. diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index 2bbaea516e..cabde4b445 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -246,6 +246,79 @@ fn named_panel_default_chords_toggle_their_panels() { } } +/// Each Window menu row that shows a panel shows the chord of that panel's shortcut, as production's did, and the +/// rows of the panels with a default key show one. The first frame builds the keymap after its menus, so the menus of +/// the next frame show the chords. +#[test] +fn window_menu_panel_rows_show_their_panels_shortcuts() { + let mut app = new_app(); + let ctx = ready(&mut app); + key_frame(&mut app, &ctx, vec![]); + let rows: Vec<(craft::keymap::CommandRef, Option)> = app + .menus + .bar + .items() + .into_iter() + .filter(|it| it.command.id == "window.panel" && it.command.params["toggle"] == true) + .map(|it| (it.command.clone(), it.shortcut)) + .collect(); + assert!(!rows.is_empty(), "the Window menu lists panels"); + let mut with_keys = 0; + for (row, chord) in rows { + let panel = row.params["panel"].as_str().expect("a panel row names its panel"); + let entry = crate::keymap::command_of(&format!("panel:{panel}")); + assert_eq!(chord, craft::ui::runtime::commands::chord(&ctx, &entry), "{panel}: the row shows its shortcut's chord"); + if crate::shortcut_editor::PANEL_SHORTCUTS.iter().any(|(p, _)| *p == panel) { + assert!(chord.is_some(), "{panel} has a default key, and its row shows it"); + with_keys += 1; + } + } + assert!(with_keys > 0, "some listed panels have a default key"); +} + +/// A click on a Window menu row toggles its panel: it puts a showing panel away and shows it again. Libraries is +/// docked in front with no function key, so neither its flyout nor its shortcut toggles it. +#[test] +fn a_window_menu_click_toggles_its_panel() { + use craft::ui::runtime::commands::{FirePhase, FireSource, Fired}; + let mut app = new_app(); + let ctx = ready(&mut app); + let row = app + .menus + .bar + .items() + .into_iter() + .find(|it| it.command.id == "window.panel" && it.command.params["panel"] == "libraries") + .map(|it| it.command.clone()); + let row = row.expect("a Window › Libraries row"); + let before = crate::panel_docking::showing(&app.ui, "libraries"); + let click = |app: &mut VectorcraftApp| { + crate::shortcuts::run_fired(app, &ctx, &Fired::new(row.clone(), FireSource::Menu, FirePhase::Press, 0.0)); + key_frame(app, &ctx, vec![]); + crate::panel_docking::showing(&app.ui, "libraries") + }; + let once = click(&mut app); + assert_ne!(once, before, "the first click toggles Libraries"); + assert_eq!(click(&mut app), before, "the second click toggles it back"); +} + +/// A click on the task bar's More Options › Show Properties Panel, a menu row that runs `window.panel {panel: +/// "properties"}`, leaves a showing docked Properties panel showing: it does not take the toggle of Window › Properties. +#[test] +fn the_task_bar_show_properties_row_keeps_properties_showing() { + use craft::ui::runtime::commands::{FirePhase, FireSource, Fired}; + let mut app = new_app(); + let ctx = ready(&mut app); + let row = craft::keymap::CommandRef::with_params("window.panel", json!({ "panel": "properties" })); + let click = |app: &mut VectorcraftApp| { + crate::shortcuts::run_fired(app, &ctx, &Fired::new(row.clone(), FireSource::Menu, FirePhase::Press, 0.0)); + key_frame(app, &ctx, vec![]); + crate::panel_docking::showing(&app.ui, "properties") + }; + assert!(click(&mut app), "the first click shows Properties"); + assert!(click(&mut app), "a second click leaves Properties showing"); +} + /// A shortcut on a panel without a function key of its own runs `window.panel` with the params it has: no toggle is /// added, as production checked. #[test] diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index dbb5a87b32..ee47a2cf26 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -7,6 +7,7 @@ mod contextmenu; mod cut; mod distortkeys; mod document_drag; +mod drag_commands; pub(super) mod folder; mod font_menu; mod fonts; diff --git a/crates/ui-egui/src/tests/automation.rs b/crates/ui-egui/src/tests/automation.rs index f3640869de..d8cc9f9d04 100644 --- a/crates/ui-egui/src/tests/automation.rs +++ b/crates/ui-egui/src/tests/automation.rs @@ -1121,8 +1121,9 @@ fn a_screenshot_is_issued_by_the_apps_frames_and_written() { let path = base.join("out/shot.png"); let (req, reply) = ControlRequest::new("ui.screenshot", json!({"path": s(path.clone()), "focus": false})); tx.send(req).unwrap(); - // The settle delay runs on the wall clock: frames come until it is over, as an idle window's do. - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + // The settle delay runs on the wall clock: frames come until it is over, as an idle window's do. The + // request's own deadline (`craft::automation::screenshot::DEADLINE`) answers it with an error when no + // frame issues it in time, so the loop ends on the reply. let callback = loop { let out = crate::testing::app_frame(&mut app, &ctx, raw()); let sent = out.viewport_output.get(&egui::ViewportId::ROOT).and_then(|root| { @@ -1131,8 +1132,9 @@ fn a_screenshot_is_issued_by_the_apps_frames_and_written() { if let Some(callback) = sent { break callback; } - assert!(reply.try_recv().is_err(), "the screenshot was answered before it was taken"); - assert!(std::time::Instant::now() < deadline, "no frame issued the screenshot"); + if let Ok(r) = reply.try_recv() { + panic!("the screenshot was answered before it was taken: {r}"); + } }; callback.complete(std::sync::Arc::new(egui::ColorImage::filled([800, 600], egui::Color32::WHITE))); crate::testing::app_frame(&mut app, &ctx, raw()); diff --git a/crates/ui-egui/src/tests/drag_commands.rs b/crates/ui-egui/src/tests/drag_commands.rs new file mode 100644 index 0000000000..1c087bb5ec --- /dev/null +++ b/crates/ui-egui/src/tests/drag_commands.rs @@ -0,0 +1,48 @@ +//! A command sent through the control channel (`engine.execute`, which MCP's `run_command` sends) +//! or run as a menu item while a tool's drag is in progress is a step of its own, before the drag's. + +use serde_json::{Value, json}; +use vectorcraft_engine::Session; + +use crate::VectorcraftApp; + +/// Send a control request → its reply. +fn control(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, params: Value) -> Value { + let (request, _) = craft::automation::ControlRequest::new(method, params); + let craft::automation::Reply::Done(reply) = crate::control::handle(app, ctx, &request) else { panic!("{method}: not done") }; + reply +} + +#[test] +fn a_command_from_the_control_channel_or_a_menu_during_a_drag_is_a_step_of_its_own() { + for through_control in [true, false] { + let at = format!("control channel {through_control}"); + let mut app = VectorcraftApp::new(Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let other = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("select.none", json!({})).unwrap(); + app.select_tool("rectangle"); + let ctx = egui::Context::default(); + let objects = |app: &VectorcraftApp| app.session.doc().unwrap().doc.layers[0].children().map_or(0, Vec::len); + let hidden = |app: &VectorcraftApp| !app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(other)).unwrap().visible; + let steps = app.session.doc().unwrap().history.undo.len(); + let down = json!({"events": [{"kind": "down", "x": 100, "y": 100}, {"kind": "drag", "x": 150, "y": 150}]}); + assert_eq!(control(&mut app, &ctx, "ui.pointer", down)["ok"], true, "{at}"); + if through_control { + let r = control(&mut app, &ctx, "engine.execute", json!({"command": "object.hide", "params": {"ids": [other]}})); + assert_eq!(r["ok"], true, "{at}: {r}"); + } else { + app.run("object.hide", json!({"ids": [other]})).unwrap(); + } + let up = json!({"events": [{"kind": "drag", "x": 200, "y": 180}, {"kind": "up", "x": 200, "y": 180}]}); + assert_eq!(control(&mut app, &ctx, "ui.pointer", up)["ok"], true, "{at}"); + assert!(hidden(&app), "{at}: the drag keeps the command's edit"); + assert_eq!(objects(&app), 2, "{at}: the drag draws its rectangle"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), steps + 2, "{at}: a step each"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(objects(&app), 1, "{at}: Undo takes back the drag first"); + assert!(hidden(&app), "{at}"); + app.run("edit.undo", json!({})).unwrap(); + assert!(!hidden(&app), "{at}: then the command"); + } +} diff --git a/crates/ui-egui/src/tests/panel_harness.rs b/crates/ui-egui/src/tests/panel_harness.rs index 574da463f5..c48710edc3 100644 --- a/crates/ui-egui/src/tests/panel_harness.rs +++ b/crates/ui-egui/src/tests/panel_harness.rs @@ -291,6 +291,27 @@ impl Panel { self.look(name).rect } + /// One frame with no input at `pixels_per_point`; the shapes it painted, nested shapes flattened, and the images of + /// the textures it made. + pub(crate) fn paint_at(&mut self, pixels_per_point: f32) -> (Vec, Vec<(egui::TextureId, egui::ImageData)>) { + self.fixture.pixels_per_point(pixels_per_point).record_paint(); + self.take_input(); + self.fixture.frame(Vec::new()); + let Some(mut paint) = self.fixture.take_paint() else { return (Vec::new(), Vec::new()) }; + let images = paint.textures_delta.set.iter().flat_map(|(id, deltas)| deltas.iter().map(move |delta| (*id, delta.image.clone()))).collect(); + // The test reads the images; no renderer applies them. + paint.textures_delta.clear(); + let mut shapes = Vec::new(); + let mut open: Vec = paint.shapes.into_iter().map(|clipped| clipped.shape).collect(); + while let Some(shape) = open.pop() { + match shape { + egui::Shape::Vec(nested) => open.extend(nested), + shape => shapes.push(shape), + } + } + (shapes, images) + } + /// Where the control of `role` named `name` is, where nodes of other roles share the name. pub(crate) fn rect_role(&self, name: &str, role: craft::ui::contract::Role) -> Rect { self.look_role(name, role).rect diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index 224bdc989c..6ab2abd049 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -677,6 +677,19 @@ fn the_preserve_checkboxes_open_as_they_were_last_confirmed() { assert_eq!(preserve(&r), [json!(false), json!(false), json!(true)], "Cancel keeps what OK left"); } +#[test] +fn with_every_color_preserved_the_colors_table_says_so_in_its_body() { + let mut app = app(); + art(&mut app, &["#ffffff", "#000000"]); + let mut r = assign(app, json!({})); + assert!(r.rows().is_empty(), "White and Black are preserved"); + let note = "No colors to recolor (preserved colors are left out)."; + let inside = |r: &Recolor| rect(r, "Colors").contains_rect(rect(r, note)); + assert!(inside(&r), "the note is drawn inside the Colors table, not above its empty rows"); + r.frame(); + assert!(inside(&r), "and stays there on the next frame"); +} + fn new_hsb(r: &Recolor) -> Vec<[f32; 3]> { field(r, "rows").as_array().unwrap().iter().map(|row| vectorcraft_engine::cmd::color_value(&row["to"]).unwrap().to_hsb()).collect() } diff --git a/crates/ui-egui/tests/image_trace_ignore_sampler.rs b/crates/ui-egui/tests/image_trace_ignore_sampler.rs index 75a3241ec6..9d8aefd246 100644 --- a/crates/ui-egui/tests/image_trace_ignore_sampler.rs +++ b/crates/ui-egui/tests/image_trace_ignore_sampler.rs @@ -1470,6 +1470,8 @@ fn review_597048_coalesced_pair(sampler_prefix: bool) { ); assert!(frame_event(&ctx, |i| i.pointer.button_double_clicked(PointerButton::Primary))); assert_eq!(frame_event(&ctx, |i| i.pointer.button_triple_clicked(PointerButton::Primary)), sampler_prefix); + // The canvas gets the second release in the frame after the second press, which the framework asks for. + frame_at(&mut app, &ctx, start + 3.0 * step, vec![]); assert_eq!(app.session.active().unwrap().isolation, Some(group), "two ordinary clicks isolate after an earlier-frame prefix"); app.run("object.exitIsolation", json!({"all": true})).unwrap(); review_gesture_press(&mut app, &ctx, at, start + 5.0 * step); diff --git a/crates/ui-egui/tests/safe_mode.rs b/crates/ui-egui/tests/safe_mode.rs index c07d96463f..70aaf2db85 100644 --- a/crates/ui-egui/tests/safe_mode.rs +++ b/crates/ui-egui/tests/safe_mode.rs @@ -113,6 +113,14 @@ fn frame(app: &mut VectorcraftApp, ctx: &egui::Context) { out.textures_delta.clear(); } +/// The first frames of a launch that asks about a stopped plug-in: the first frame puts the choice on the dialog host +/// after its pass and asks for another frame, which opens it. +fn asking_frames(app: &mut VectorcraftApp, ctx: &egui::Context) { + frame(app, ctx); + assert!(ui::choosing(app) && ctx.has_requested_repaint(), "the choice asks for the frame that opens it"); + frame(app, ctx); +} + /// A control request, then one frame; the reply says whether it was done. fn control(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, params: Value) -> Value { let (req, _rx) = ControlRequest::new(method, params); @@ -143,7 +151,7 @@ fn disable_and_continue_loads_every_plug_in_but_the_one_that_was_loading() { stopped_while_loading_x(&launch_dir, &dir); let mut app = launch(&dir, &launch_dir, false); let ctx = window(); - frame(&mut app, &ctx); + asking_frames(&mut app, &ctx); assert!(ui::choosing(&app)); assert!(safe_mode::active() && registry::list().is_empty(), "nothing loads until the user chooses"); assert!(chrome::window_title(&app).ends_with("(Safe Mode)")); @@ -172,7 +180,7 @@ fn start_normally_loads_everything_and_start_in_safe_mode_loads_nothing() { stopped_while_loading_x(&launch_dir, &dir); let mut app = launch(&dir, &launch_dir, false); let ctx = window(); - frame(&mut app, &ctx); + asking_frames(&mut app, &ctx); let reply = control(&mut app, &ctx, "ui.dialog.set", json!({"field": "choice", "value": "alternate"})); assert_eq!(reply["ok"], true, "{reply}"); confirm(&mut app, &ctx); @@ -184,7 +192,7 @@ fn start_normally_loads_everything_and_start_in_safe_mode_loads_nothing() { stopped_while_loading_x(&launch_dir, &dir); let mut app = launch(&dir, &launch_dir, false); let ctx = window(); - frame(&mut app, &ctx); + asking_frames(&mut app, &ctx); assert!(ui::choosing(&app) && !ui::staying_on(&app), "Safe Mode until the user chooses"); let reply = control(&mut app, &ctx, "ui.dialog.cancel", json!({})); assert_eq!(reply["ok"], true, "{reply}"); @@ -214,7 +222,7 @@ fn a_disabled_list_that_cannot_be_saved_says_so() { let unsaved = "Couldn't save the disabled plug-ins for the next launch"; let mut app = launch(&dir, &launch_dir, false); let ctx = window(); - frame(&mut app, &ctx); + asking_frames(&mut app, &ctx); confirm(&mut app, &ctx); assert_eq!(app.ui.status, unsaved, "Disable and Continue"); assert!(safe_mode::previous().is_some(), "the next launch asks again"); @@ -299,7 +307,7 @@ fn a_safe_mode_flag_launch_leaves_the_stopped_plug_in_to_the_next_launch() { // The next launch, without the flag, asks about it before anything loads. let mut app = launch(&dir, &launch_dir, false); let ctx = window(); - frame(&mut app, &ctx); + asking_frames(&mut app, &ctx); assert!(ui::choosing(&app)); assert!(registry::list().is_empty()); confirm(&mut app, &ctx); diff --git a/docs/effects-parity.md b/docs/effects-parity.md index f5f0dea3e1..7b4b1428c6 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -1,6 +1,6 @@ # Effects parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: Extrude & Bevel, Inflate and Rotate seams have round joins under a white light and in the 3D (Classic) effects too, no longer reaching past the solid as thorns; previously: Effect Gallery: a thumbnail for each filter and an in-dialog preview on an original drawing; the 1–2 h for those is done; Extrude & Bevel, Inflate and Rotate merge contours that cross, touch or overlap, as type often draws a glyph, before building a solid; previously: Extrude & Bevel, Inflate and Rotate apply to groups and layers, their objects turning about one shared axis (#4506); the Transform effect's copies of a path with a fill and a stroke (or several fills and strokes, an even-odd fill, or a partly transparent one) are drawn each above the one before, as Expand Appearance makes them (#5920); Expand Appearance makes each copy of a path's Transform effect an object of its own (#5612); previously: Pixelate › Color Halftone: Max Radius in pixels of the Document Raster Effects resolution, 4–127 px, with older documents converted on opening and radii written back in points for older app versions (#3260); Effect dialogs clamp bounded length inputs immediately on commit and flash rejection on invalid input (#4638); previously: Drop Shadow Darkness uses fixed RGB subtraction and CMYK black addition; scores unchanged; Pathfinder › Trap: the Pathfinder panel's Trap… and Effect › Pathfinder › Trap… add an overprinting strip of the lighter colour where two solid colours meet; recounted with Hard Mix (#3061) and Soft Mix already in the catalogue: Pathfinder 13/13, Illustrator effects 49/50) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (3D summary: what's left names base and Substance materials and shadows from lights after the first, and no longer lists angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: Extrude & Bevel, Inflate and Rotate seams have round joins under a white light and in the 3D (Classic) effects too, no longer reaching past the solid as thorns; previously: Effect Gallery: a thumbnail for each filter and an in-dialog preview on an original drawing; the 1–2 h for those is done; Extrude & Bevel, Inflate and Rotate merge contours that cross, touch or overlap, as type often draws a glyph, before building a solid; previously: Extrude & Bevel, Inflate and Rotate apply to groups and layers, their objects turning about one shared axis (#4506); the Transform effect's copies of a path with a fill and a stroke (or several fills and strokes, an even-odd fill, or a partly transparent one) are drawn each above the one before, as Expand Appearance makes them (#5920); Expand Appearance makes each copy of a path's Transform effect an object of its own (#5612); previously: Pixelate › Color Halftone: Max Radius in pixels of the Document Raster Effects resolution, 4–127 px, with older documents converted on opening and radii written back in points for older app versions (#3260); Effect dialogs clamp bounded length inputs immediately on commit and flash rejection on invalid input (#4638); previously: Drop Shadow Darkness uses fixed RGB subtraction and CMYK black addition; scores unchanged; Pathfinder › Trap: the Pathfinder panel's Trap… and Effect › Pathfinder › Trap… add an overprinting strip of the lighter colour where two solid colours meet; recounted with Hard Mix (#3061) and Soft Mix already in the catalogue: Pathfinder 13/13, Illustrator effects 49/50) · **Target:** Adobe Illustrator 2026 (30.x) Every entry of Illustrator's Effect menu, by its public feature name, against VectorCraft's effects catalogue (`effect_catalog()` in `crates/effects/src/lib.rs`) and the Effect menu built from it @@ -186,13 +186,14 @@ VectorCraft choices; an original approximation, never compared with another appl | Export 3D objects (OBJ, USDA, glTF) | initial: Asset Export's Export 3D Object, and the 3D and Materials panel's Export 3D Object button (which then shows Asset Export with the new assets selected, [three-d.md](three-d.md#3d-and-materials-panel)), collect an object with Extrude & Bevel, Revolve, Inflate or Rotate as a 3D asset, and Export writes its solids as a USDA (the default), USDZ, glTF or OBJ mesh with a material in each solid's paint color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`); graphics mapped onto a plane or Extrude & Bevel's caps are exported as PNG textures of those faces, flat and unlit, and the graphics on Revolve's side as a texture of the side unrolled; every corner carries texture coordinates and a normal, smoothed across a curved bevel and over Inflate's puff ([three-d.md](three-d.md#3d-meshes)); no materials and no lighting ([3D export help](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)) | The `three-d` crate (depends on `geom` and `pathops`, with no UI or GPU dependencies) builds, rotates, projects, shades and depth-sorts the surfaces; -the effects crate turns them into art. What's left (materials and shadows, ray-traced rendering, -angular cut caps, exact visibility, Turntable) is 25–45 h. +the effects crate turns them into art. What's left (base and Substance materials, shadows from lights after the first, +ray-traced rendering, exact visibility, Turntable) is 25–45 h. ## Revision history | Date | Change | Summary | |---|---|---| +| 2026-11-20 | minor | 3D summary: what's left names base and Substance materials and shadows from lights after the first, as three-d.md documents, and no longer lists angular cut caps, which Revolve's Cap closes ([revolve.md](revolve.md)) (#8312); scores and estimates unchanged | | 2026-11-17 | minor | Distort & Transform › Twist: handles follow the rotation's derivative, so a strongly twisted path is a smooth spiral instead of pieces meeting at kinks (#7069; `twist_joins_its_pieces_smoothly` in `crates/effects/src/tests.rs`). Scores and estimates unchanged. | | 2026-11-12 | minor | The seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins (the seams of Revolve and of colored lights, and 3D (Classic) Wireframe edges, were already round): no thorns on edge-on facets, and facets with no neighbor now have rounded convex corners ([three-d.md](three-d.md#seams)); scores and estimates unchanged | | 2026-11-10 | minor | Effect Gallery: each filter has a thumbnail, and the dialog has a preview of the visible stack (or the browsed filter when the stack is empty). Both are an original landscape drawing passed through the filter ([Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html)). The canvas preview and one-undo OK are unchanged. Remaining hours for the gallery's thumbnails and in-dialog preview: 1–2 → none. Counts unchanged (57/57). | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 932138e226..2af1064315 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (`.ai` import: a stroke's arrowheads, the symbols its style names, come in as custom arrowheads with their tip on, or past, the path's end, as the drawn art places it, and the line stopping where the symbol's sample of it ends, #8188; PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group instead of reading as nested clipping groups that clip nothing or stop the editing data from being read; previously: PDF import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF export writes the document language as the catalog's `/Lang`, #3644; PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; scores and estimates unchanged; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, not butt caps and miter joins, #7741; `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; `.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art, #6570; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (EPS import: images over 67 million pixels are read at a lower resolution; `.ai` import: a stroke's arrowheads, the symbols its style names, come in as custom arrowheads with their tip on, or past, the path's end, as the drawn art places it, and the line stopping where the symbol's sample of it ends, #8188; PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group instead of reading as nested clipping groups that clip nothing or stop the editing data from being read; previously: PDF import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF export writes the document language as the catalog's `/Lang`, #3644; PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; scores and estimates unchanged; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, not butt caps and miter joins, #7741; `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; `.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art, #6570; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) > > **File-font integration status (2026-11-19, #4569):** 56 focused PDF/native-reopen, file-font, stroked-text and font-binding tests passed on the current-main integration candidate. Full workspace CI and hardening paths outside those suites remain pending. Scores and estimates unchanged. > @@ -354,7 +354,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's | Illustrator template `.ait` | open, save | yes | PDF-compatible only, from Save as Template (`.vctemplate` stays its default) | New from Template opens a saved `.ait` untitled with its layers and art (`tests_pdfedit.rs`) | | Illustrator `.ai` | open, save | yes (PDF-compatible + editing-data structure with template layers and ruler guides, File Info) | PDF-compatible, or legacy version 7 (layers and groups) | see above; no real-file corpus | | PDF | open, place, save | yes (authored ActualText in editable import, #6165; layers, masks, editable text, security, overprint, File Info from the XMP packet and the document information dictionary; Crop To › Trim takes the bleed box as the document's bleed; Import PDF pages as links opens each page as a placed document linked to it, on its own artboard, `tests/placed_document.rs`, and is checked when All is picked and cleared when Range is picked) | yes (presets, PDF/X-1a/3/4, layers, marks and bleed, ICC, fast web view, 1.3+; objects' URLs as link annotations, not in PDF/X; the document language as the catalog's `/Lang` and XMP `dc:language`, #3644) | fuzzed import; shared guarded writer and windowed reader ([pdf-backend.md](pdf-backend.md)), metadata, incomplete-content and dependency-source regressions; PDF text opens where the file draws it, glyph by glyph (#722: kerning or none, spacing per character, text rise as baseline shift, vertical writing, justified text boxes); alpha soft masks drawn as images import with the mask (#1551); a clip only counts as covering the page when its shape does (#1542); a PDF another app copied pastes as editable vector art (#1499); letter-spaced type on a path keeps its length and its glyph-by-glyph stroke comes in as one text object (#1586, #1585); a crafted name tree with shared nodes no longer takes exponential time on open (#1781); fonts named with hyphens (`Noto-Sans-Bold`) or with a composite font's CMap (`Name-Identity-H`) find the installed family; invisible text (rendering mode 3: a scanned page's recognized text) opens as type with no fill or stroke and saves back as invisible, searchable text (#2675); PDF/X-1a and X-3 flattening in a CMYK document keeps CMYK inks where it rasterizes (#2160); an image mask (`/ImageMask true`) painted in a solid color opens as a grayscale image colorized by that color, a spot color keeping its swatch and tint, so Fill and Recolor Artwork reach it, and the same mask painted again in another color keeps that color (#6313); an image in a Separation space opens as a grayscale image of its tints colorized by its ink at 100 % (a spot swatch, a process plate or Registration), its soft mask as its opacity mask (#6314); a DeviceN image of one colorant opens the same way, and one of process plates only (the ink `None` may be among them) opens in CMYK with each colorant's tint in its plate (#6348) PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. | -| EPS | open, place, save | yes (own PostScript L3 interpreter, Illustrator EPS editing data structure) | yes (L2/L3, TIFF previews) | CIDFonts the file doesn't carry not drawn, but for those over a predefined CMap (`UniJIS-UCS2-H`, `90ms-RKSJ-H`, `GBK-EUC-H`, `KSCms-UHC-H`, `ETen-B5-H`), set as type in the font of the CIDFont's name, vertical over a `-V` CMap; a name that ends in the row-and-cell CMap `H` or `V` splits off the CMap only when the file defines the CIDFont of that name, the CIDFont is `Ryumin-Light` or `GothicBBB-Medium` (the Japanese CIDFonts a printer carries), or the name has a hyphen and an installed face that covers Japanese has it; name-keyed fonts in a FontSet set as type by name; #505; images encoded with `CCITTFaxDecode` (ITU-T T.4 Group 3 and T.6 Group 4, with `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1`) draw, and damaged data keeps the rows decoded before its first damaged row; Type 42 (TrueType) fonts set type at its size (#1553); an embedded Type 1 font's encrypted part is read for its glyphs, which space its type, outline it and draw glyphs without a character, in plain and composite fonts; a Type 42 font that carries its TrueType font gives each code its character by its glyph name or, for names that say nothing (`/g12`), by the glyph's entry in the font's own character map, spaces its type by its own widths and draws glyphs that stand for no character from its outlines; the show operators' spacing along the baseline (`ashow`, `widthshow`, `xshow`, `yshow`, `xyshow`, and the moves of `kshow`'s procedure, run between each two characters) is kept on live type as tracking, so type in a font that isn't installed keeps the file's line lengths (spacing that moves characters off the baseline, as `yshow`, `xyshow` or a `kshow` procedure can, places each character as its own text object); composite (Type 0) fonts with the 8/8 mapping, as PDF-to-PostScript converters write two-byte fonts, draw a Type 42 descendant's glyphs from the TrueType outlines it carries and an embedded Type 1 descendant's from its charstrings, and set other descendants' characters as type at the composite font's size (other mappings are still set as type in the font of their name); CID-keyed fonts (`composefont`, `FMapType` 9 over a CMap built with the CIDInit operators or `Identity-H`/`Identity-V`; `bfchar` and `bfrange` mappings give a base-font descendant its codes or glyph names) draw the glyphs of the Type 0 CIDFonts (Type 1 charstrings in their `StartData` binary data or `GlyphDirectory`) and Type 2 CIDFonts (TrueType glyphs through `CIDMap`) they carry, and the CID-keyed fonts of a FontSet's Compact Font Format data (Type 2 charstrings); a clip only counts as covering the page when its shape does (#1542); an EPS another app copied pastes as editable vector art (`clipboard.importEps`, #1499); a stitched shading keeps its hard colour changes on import (#1654); sampled functions (type 0) interpolate between their samples, multilinearly or by cubics with `Order 3`, and a sampled axial or radial gradient has a stop at each sample; a gradient the page paints as a row of abutting one-colour strips (as Level 2 writers draw smooth shades) imports as one linear gradient, without the seams the strips leave when each is drawn alone; CMYK images, CMYK JPEGs included, keep their ink amounts on import, as from PDF, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask; ruzstd 0.9.1 for compressed editing data (#1807, RUSTSEC-2026-0344) | +| EPS | open, place, save | yes (own PostScript L3 interpreter, Illustrator EPS editing data structure) | yes (L2/L3, TIFF previews) | CIDFonts the file doesn't carry not drawn, but for those over a predefined CMap (`UniJIS-UCS2-H`, `90ms-RKSJ-H`, `GBK-EUC-H`, `KSCms-UHC-H`, `ETen-B5-H`), set as type in the font of the CIDFont's name, vertical over a `-V` CMap; a name that ends in the row-and-cell CMap `H` or `V` splits off the CMap only when the file defines the CIDFont of that name, the CIDFont is `Ryumin-Light` or `GothicBBB-Medium` (the Japanese CIDFonts a printer carries), or the name has a hyphen and an installed face that covers Japanese has it; name-keyed fonts in a FontSet set as type by name; #505; images encoded with `CCITTFaxDecode` (ITU-T T.4 Group 3 and T.6 Group 4, with `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1`) draw, and damaged data keeps the rows decoded before its first damaged row; Type 42 (TrueType) fonts set type at its size (#1553); an embedded Type 1 font's encrypted part is read for its glyphs, which space its type, outline it and draw glyphs without a character, in plain and composite fonts; a Type 42 font that carries its TrueType font gives each code its character by its glyph name or, for names that say nothing (`/g12`), by the glyph's entry in the font's own character map, spaces its type by its own widths and draws glyphs that stand for no character from its outlines; the show operators' spacing along the baseline (`ashow`, `widthshow`, `xshow`, `yshow`, `xyshow`, and the moves of `kshow`'s procedure, run between each two characters) is kept on live type as tracking, so type in a font that isn't installed keeps the file's line lengths (spacing that moves characters off the baseline, as `yshow`, `xyshow` or a `kshow` procedure can, places each character as its own text object); composite (Type 0) fonts with the 8/8 mapping, as PDF-to-PostScript converters write two-byte fonts, draw a Type 42 descendant's glyphs from the TrueType outlines it carries and an embedded Type 1 descendant's from its charstrings, and set other descendants' characters as type at the composite font's size (other mappings are still set as type in the font of their name); CID-keyed fonts (`composefont`, `FMapType` 9 over a CMap built with the CIDInit operators or `Identity-H`/`Identity-V`; `bfchar` and `bfrange` mappings give a base-font descendant its codes or glyph names) draw the glyphs of the Type 0 CIDFonts (Type 1 charstrings in their `StartData` binary data or `GlyphDirectory`) and Type 2 CIDFonts (TrueType glyphs through `CIDMap`) they carry, and the CID-keyed fonts of a FontSet's Compact Font Format data (Type 2 charstrings); a clip only counts as covering the page when its shape does (#1542); an EPS another app copied pastes as editable vector art (`clipboard.importEps`, #1499); a stitched shading keeps its hard colour changes on import (#1654); an image of more than 2^26 pixels is read at a lower resolution (every second, third… sample of every second, third… row), not left out, with a note; when its data is more than the reader holds, Flate or LZW compressing it last (without a predictor) is decoded keeping only the rows read; sampled functions (type 0) interpolate between their samples, multilinearly or by cubics with `Order 3`, and a sampled axial or radial gradient has a stop at each sample; a gradient the page paints as a row of abutting one-colour strips (as Level 2 writers draw smooth shades) imports as one linear gradient, without the seams the strips leave when each is drawn alone; CMYK images, CMYK JPEGs included, keep their ink amounts on import, as from PDF, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask; ruzstd 0.9.1 for compressed editing data (#1807, RUSTSEC-2026-0344) | | PostScript `.ps` | open, place | yes (the EPS reader reads its first page; `.epsf` files open and place as EPS) | via Print to PostScript | `tests_epsimport.rs` | | DCS 1.0 / 2.0 | place linked | place linked only (one image of the plates; spot plates as spot swatches; the composite's clipping path; each plate on its own ink in Separations Preview and print separations) | no | `crates/eps/src/dcs/tests.rs`, `crates/engine/src/tests/dcs.rs` | | SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598); an artboard exported on its own (Export As with Use Artboards, Export for Screens, Asset Export) has the artboard's name as ``, Save the document's (#3544); attributes in other applications' XML namespaces (`plotter:pen="2"`) kept on their objects from import to export, as `data-*` attributes are (`crates/svg/tests/it/foreign_attributes.rs`); simple shapes export as `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>` and `<polyline>` where they draw the same as the path (#4652, `crates/svg/tests/it/basic_shapes.rs`); the regions of exported masks and filters (opacity masks, inverted masks, knockout groups) cover the art they apply to, and over type keep a region that covers any artwork (#6401, `crates/svg/tests/it/blend_export.rs`); a masked group, or a knockout group's masked group, whose content has a shadow, glow, blur or feather starts with a hidden, unpainted rectangle over the mask's region, so readers that draw a masked group only inside the box of its shapes draw those effects too (`crates/svg/tests/it/blend_export.rs`); SVG Options › Include Variable Data writes the text variables, data sets and bound type objects, and opening the SVG reads them back (`tests::variables::an_svg_with_variable_data_opens_with_its_variables_data_sets_and_bindings`) | @@ -422,6 +422,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| +| 2026-11-22 | minor | EPS import: type in a Type 1 or Type 42 font the file carries, whose family isn't available, is drawn in a TrueType font built from the glyphs the file shows (outlines and advances from the font program), kept with the document as PDF import keeps a PDF's (#4569), and spaced by those glyphs' own advances; once its text is edited it takes the fallback font. A string that draws a character with another glyph than the one kept for it comes in as outlines. The warning names those families with PDF import's words ("show as the file draws them, in the fonts it carries, until their text is edited"). Fonts the file only names, Type 3 fonts and type from an Illustrator editing copy are unchanged. Tests `embedded_type1_type_draws_with_the_files_glyphs`, `a_second_glyph_for_a_character_keeps_its_type_as_outlines`, `kept_type1_glyphs_survive_saving_and_go_when_the_text_is_edited`, `type_in_fonts_that_arent_available_is_named_in_a_warning` in `crates/eps/src/import/tests_type1.rs`, `type_in_a_carried_type42_font_draws_with_the_files_glyphs` in `crates/eps/src/import/tests_type42.rs`; scores unchanged | | 2026-11-19 | minor | `.ai` import: a stroke's arrowheads were left out, so lines came in without their heads (#8188). A Stroke Style filter's stroke dictionary names each end's head as a symbol of the file (`/GObjRef : (name) /SymbolArt ; (BSArrowBeginSymbol)` or `(BSArrowEndSymbol)`), with its scale in percent (`BSArrowEndScale`, and `BSArrowBeginScale` read the same way; 100 without one). As the files have it, such a symbol's art (y down, as symbols are read) points right along a straight, level sample of the line: an open stroked path with no fill, which ends where the line stops under the head. The rest of the art that paints is the head, its tip its rightmost point, at one symbol unit a head weight (the stroke's weight at the scale). The head comes in as a custom arrowhead with that outline and that stop (a custom head now carries an optional stop, else its line ends halfway along it, as before). Its placement is the one of the two (tip on the end of the path, or Extend, the tip past it by the line's length under the head) that gives the object its drawn art's bounds; the user's file has every tip on its path's end. A stroke keeps its drawn look when neither placement gives those bounds (heads on other subpaths, say) or both do while a head moves 0.2 pt or more between them (a line whose end lies inside the bounds of its other segments), when its symbol isn't read whole or isn't read as a head (no sample or more than one, a sample that isn't 1 pt wide, as in art stored at a Large Canvas scale, art other than paths, compound paths and groups such as a clip group, a group with fills or strokes of its own, effects, brushes, partial opacity or an opacity mask), when its dictionary holds another `BSArrow` entry beside heads, when a scale is outside 1–1000 %, or when the head's weight would be under the 0.25 pt least one VectorCraft draws; a graphic style with such a stroke isn't read rather than read without its heads, and one with heads takes them on the end of the path, so an object whose heads are read past its ends isn't linked to its listed style. Measured on a user's file of ten arrows (used locally, never committed): every line gets its heads, and drawn at 4× its pixels match the file's own page but for 3 of 9,825 inked ones (0.24.1: 1,232 differ). Tests `a_strokes_arrowhead_symbols_are_its_arrowheads`, `a_strokes_start_arrowhead_points_back_and_keeps_its_side`, `a_stroke_takes_both_heads_at_their_own_scales`, `heads_drawn_past_the_path_extend_it`, `arrowheads_this_does_not_read_keep_the_drawn_look`, `an_arrowhead_entry_without_heads_leaves_the_stroke_read` in `crates/eps/src/import/ai/tests.rs`, `heads_whose_placement_the_drawn_bounds_leave_open_keep_the_drawn_look`, `a_head_that_stays_put_leaves_a_moving_heads_placement_open`, `a_style_library_reads_the_heads_of_symbols_defined_after_its_styles` in it, `a_symbol_entry_cut_short_leaves_the_next_style_read` and `a_comment_inside_a_symbol_entry_is_skipped` in `crates/eps/src/import/ai/style/tests.rs`, `partly_transparent_or_masked_art_makes_no_head` in `crates/eps/src/import/ai/arrowhead.rs`, fuzzed by `ai_arrowhead_strokes_never_panic`; scores unchanged | | 2026-11-19 | minor | PDF import (#8549 follow-up): type filled and stroked after a page of type filled only came in as a filled object and a stroked one: since #8549 lines filled only are kept for a stroke pass too, and the glyphs of the lines finished past the 64 kept were remembered until the next stroke, so `2 Tr (Title) Tj` after more than 64 lines of type filled only took its first stroke for the start of a stroke pass over them, always once more than 4,096 glyphs had been finished so. Those glyphs are now forgotten when anything else is drawn (a path, an image, a Type 3 glyph's art, a change of blend mode or soft mask: nothing is drawn between an operator's fill pass and its stroke pass), and past the first 4,096 glyphs none are remembered instead of every stroke matching. A `TJ` over more lines than are kept still comes in as a filled object and a stroked one for each part, also when it ends where it began, and when a glyph kept as an outline comes before that (the line it starts keeps the glyphs of the lines finished). Remaining: with nothing drawn between them, type filled and stroked at exactly the place, font, size and text of a glyph filled only on a line finished so still comes in as a filled object and a stroked one, as the device can't tell its stroke pass from the start of one over that glyph. Tests: `type_filled_and_stroked_after_a_dense_page_of_filled_type_is_filled_and_stroked`, `type_filled_and_stroked_over_a_finished_glyph_after_a_path_is_filled_and_stroked`, `an_outline_glyph_in_a_tj_over_more_lines_than_are_kept_leaves_fill_and_stroke_apart`; scores and estimates unchanged. | | 2026-11-12 | minor | #4569: document-owned file-font bindings, exact-byte identity checks and reclaimable live-face allowance; preserve referenced fallback bindings through installed-font removal, transfer placement leases/resources, relink older-save font keys, and restore recovery blobs before binding/diagnostics. Regression sources cover native/clipboard/export, Place/Break Link/older saves/recovery and isolated text/renderer ownership. Format-only verification; compilation and runtime proof pending. Scores and estimates unchanged. | @@ -447,6 +448,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | 2026-11-12 | minor | Save refusal follow-up (#6146): changed format opens its Save options; unchanged format retains original options. Focused UI regressions passed, including the format-change case that failed before the fix; native panel acceptance pending. Scores and estimates unchanged. | | 2026-11-11 | minor | Newly imported SVG/SVGZ titles use the imported-text rules: generated Untitled names and control-only titles give the filename fallback, other control characters are removed, and titles are limited to 65,536 characters. Native and Preserve Editing titles remain unchanged (#3626). | | 2026-11-11 | minor | Native and Preserve Editing restores keep an existing File Info title exactly, including repeated spaces; imported-text fallback titles alone are normalized (#3626). | +| 2026-11-07 | minor | EPS import: an image of more than 2^26 pixels (the reader's cap) was left out, so a page that is one large scan or photo came in empty. It is now read at a lower resolution: the least whole step that brings it within the cap, the middle sample of each step × step block, over the image's whole area, with the note *images of more than 67 million pixels were read at a lower resolution*. When its samples are more data than the reader holds (256 MB), an image whose last filter is Flate or LZW without a predictor is decoded a row at a time, keeping only the rows read (an 11903 × 8423 RGB page, 300 MB, comes in at 5952 × 4212). An image left out still has its data skipped (#6003), now also when a procedure reads it (called until it has given the image's data or ends) and when its first filter decompresses to more than the reader holds (the compressed data is measured without keeping it). Tests `an_image_over_the_pixel_cap_is_read_at_a_lower_resolution`, `an_image_of_more_data_than_the_reader_holds_keeps_only_the_rows_it_reads`, `the_data_of_an_image_too_large_to_hold_is_skipped`; scores unchanged | | 2026-11-03 | minor | An imported document's own title goes into File Info only (#3626): an SVG's root `<title>`, a PDF's, `.ai`'s or `.ait`'s XMP `dc:title` else its Info `Title` is File Info's title (`metadata.title` in the native format, left out when unset so other documents save unchanged and older versions ignore it; written by exports); the document's name, which the tab, Save As and the default export names use, stays the file's name. | | 2026-11-11 | minor | `.ai` and EPS import, and what the canvas, every export and `.ai` save draw: type's strokes in an envelope (its characters' and those on its own appearance) paint along the bent glyph outlines at their own weight, Distort Appearance on or off, as the drawn art of users' `.ai` files strokes them (used locally, never committed: there the drawn art keeps those strokes as stroked paths at the type's own weights, and its ring is as wide wherever the grid squeezes or stretches the type). With Distort Appearance, VectorCraft bent them with the art, as their filled outlines, so an envelope of stroked type in a squeezed or stretched grid didn't draw as its drawn art and kept it. The same holds in an envelope inside an envelope. Paths' strokes, geometry effects, opacity masks, linear gradients and pattern fills bend as before. On 224 of our own files: envelopes of type that open live go from 135 in 37 files to 154 in 45, and no file loses one; no file changes whether it opens from its layers or its PDF part; renders at 40 ppi change in 31 files, by at most 2.3% of their pixels, 19 closer to the file's own page and 12 further, 11 of those where an envelope of type now opens live in place of its drawn art (the page's own art) and one by 4 pixels. Tests `envelope_distort::type_strokes_paint_at_their_own_weight_in_a_squeezed_envelope`, `a_stroke_on_types_appearance_paints_at_its_own_weight_in_a_squeezed_envelope`, `a_paths_stroke_still_bends_in_a_squeezed_envelope`, `tests_native::an_envelope_of_stroked_type_whose_drawn_art_strokes_the_bent_outlines_at_the_weight_opens_live` (#6644) | | 2026-11-11 | minor | Ordinary Save to a location refusing writes offers Save As (#6146); cancellation preserves the original path and modified state; automation receives READ_ONLY_LOCATION. Scores and estimates unchanged. Validation pending. | diff --git a/docs/gaps.md b/docs/gaps.md index 2554f85b7a..b502f9e146 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: G12: Properties panel Quick Actions include contextual text actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups <g>, or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: G12: Properties panel Quick Actions include contextual text actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups <g>, or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > Scissors snapping update (2026-11-11): with Alt released, hover and cuts use the Pen's path, alignment, intersection and anchor snaps (#6470). Scores and estimates unchanged. @@ -778,9 +778,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G3 3D and Materials - **Done:** an initial live Revolve in the `three-d` crate (#846, from the contributor who offered in #605), with automatic smooth vector shading, default-on circular caps and spike-free continuous rims; - Extrude & Bevel, Inflate and Rotate with Position presets ([three-d.md](three-d.md), #1407). Colored Inflate has automatic smooth vector lighting from shared membrane normals. White-light Inflate keeps its polygon shading. Every 3D facet's seam has round joins ([three-d.md](three-d.md#seams)). All four take one to ten colored directional lights, with neutral ambient applied once, a light list and independent previewing controls. Standard, Diffuse, Top Left and Right select original rigs, shared with commands; manual settings show Custom. -- **Missing:** materials (base, Substance, graphics), shadows, - ray-traced rendering, angular cut caps, exact visibility for intersecting and concave surfaces, Turntable, and in + Extrude & Bevel, Inflate and Rotate with Position presets ([three-d.md](three-d.md), #1407). Colored Inflate has automatic smooth vector lighting from shared membrane normals. White-light Inflate keeps its polygon shading. Every 3D facet's seam has round joins ([three-d.md](three-d.md#seams)). All four take one to ten colored directional lights, with neutral ambient applied once, a light list and independent previewing controls. Standard, Diffuse, Top Left and Right select original rigs, shared with commands; manual settings show Custom. The first light casts a shadow ([three-d.md](three-d.md#shadows)), and graphics map onto 3D surfaces ([three-d.md](three-d.md#graphics)). +- **Missing:** base and Substance materials, shadows from lights after the first, + ray-traced rendering, exact visibility for intersecting and concave surfaces, Turntable, and in 3D export the graphics on Revolve's side, materials and shading (graphics on planes and Extrude & Bevel's caps are exported as textures). - **Impact:** specialist; Materials is the one menu stub left. @@ -988,6 +988,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-20 | minor | G3: shadows from the first light and graphics on 3D surfaces moved from Missing to Done, as three-d.md documents them, and angular cut caps dropped from Missing, as Revolve's Cap closes a partial sweep's cut sides ([revolve.md](revolve.md)) (#8312); estimate unchanged | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Appearance panel: right-click item context menus for rows (Duplicate Stroke/Fill, Delete Stroke/Fill, Hide/Show Stroke/Fill, Edit Effect…, Duplicate Effect, Delete Effect, Hide/Show Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling; headless tests in `crates/ui-egui/src/panels/tests_appearance.rs`; scores and estimates unchanged. | | 2026-11-19 | minor | Scissors previews its actual anchor or curve cut point with a native point marker while hovering, retaining existing snapping, Alt Add Anchor and cut behavior (#8655). Scores and estimates unchanged. | diff --git a/docs/mcp.md b/docs/mcp.md index 41ccf37e2f..68355c78f6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -763,7 +763,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions | `transform` | `{ids?, dx?, dy?, rotate?, scale?, scaleX?, scaleY?, reflect?, shear?, origin?, copy?}` | Runs move, rotate, scale, reflect, shear in that order. `rotate` is in degrees counter-clockwise; a positive `shear` moves the top to the right. With `copy`, the first step duplicates. A `scale`, `reflect` or `shear` that its command would refuse returns that error before any step runs; nothing changes and no undo step is recorded. The same holds for a step that is neither a number nor null, a `reflect` that is not a string, a `copy` that is not true or false, and an `origin` that is not two numbers. A null `rotate`, `scale`, `scaleX`, `scaleY`, `shear`, `reflect`, `copy` or `origin` is left out; a null `dx` or `dy` counts as 0, so it still runs the move. | | `create_graph` | `{type?, x, y, width, height, csv? \| series?, categories?, rows?}` | The nine Illustrator graph types: column, stacked column, bar, stacked bar, line, area, scatter, pie and radar. An empty CSV cell or a `null` in `rows` is a blank value; a number in straight quotes is a label. Edit later with `graph.setData` / `graph.setType` via `run_command`. `graph.column {design, columnType: vertical\|uniform\|repeating\|sliding, each, fractions: chop\|scale}` draws the columns or bars of the series picked with Group Selection (or `seriesIndexes`, or all of them) with a graph design saved by `graph.design`; with no `design` it returns the series' current design and options. Type in the design that holds a `%` followed by two digits shows each column's value, with at least the first digit's places before the decimal point and the second digit's places after it. | | `text_wrap` | `{ids?, offset?, invert?, release?}` | Area type below the objects (same layer) flows around them. `offset` is in points, from -1000 to 1000 (default 6). An offset outside that range or not a number, or an `invert` or `release` that is not true or false, is an error and changes nothing; `object.textWrap.make` and `object.textWrap.options` refuse the same values. | -| `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy` and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. Settings that change without an undo step stay as they are when `undo` or `redo` brings back a step that did not change them: the perspective grid's view options and active plane, the grid preferences (`gridlineEvery`, `gridSubdivisions`), the export settings (`assets.settings.set`), and the current brush and symbol. A step that changed one of them, such as a perspective grid preset that shows the grid, takes that change back. The point Automatic Plane Positioning holds comes back with the step, and is let go when the active plane kept is another one. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. | +| `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy` and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. Settings that change without an undo step stay as they are when `undo` or `redo` brings back a step that did not change them: the perspective grid's view options and active plane, the grid preferences (`gridlineEvery`, `gridSubdivisions`), the export settings (`assets.settings.set`), and the current brush and symbol. A step that changed one of them, such as a perspective grid preset that shows the grid, takes that change back. The point Automatic Plane Positioning holds comes back with the step, and is let go when the active plane kept is another one. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. Any other command that changes the document during a tool's drag, from `run_command`, a panel or a menu, records its own undo step before the drag's. The command acts on the document without the drag's preview, and the drag then continues from the command's result: with Real-time Drawing on, the drag's preview is applied again at once, and with it off, the release applies it as before. The release records the drag's step after the command's, `undo` takes back the drag first and the command next, and Escape cancels only the drag. The drag acts on the objects it started with, so a selection the command makes (`select.all`, `edit.duplicate`) does not change what the drag moves, and the drag's release and Escape set the selection as they do without the command (with Real-time Drawing on, so does each move of the drag); a command that records no undo step, such as `select.none`, adds no step. When the command deletes or changes the art being dragged, the drag continues with the art the command left, and a drag left with nothing to change records no step. A warning or an error from the drag's preview applied again after the command is in the command's result as `previewWarning`. Typing in progress is kept as a step of its own before the command. Two cases run the command inside the drag, which then keeps the command's edit as part of its own step: a press of the Quick Pen (an edit to its path ends the path), and `object.transform` with `copy` during an Alt-drag, which copies the art as the drag's move left it. A command run while a dialog's or a panel's preview is open runs inside that preview. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. | For example, create editable Japanese area type with the engine's vertical writing mode: @@ -2589,7 +2589,9 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, while 4,096 other `[` are open, assign a property in brackets whose name is a string literal of more than 256 characters, assign properties of more than 1,000 different names on members (`o.d = …`, `o['d'] = …`), or assign or declare `Folder`; a variable whose name a member assignment writes counts as one that may hold a File - object), `filesOpened` (files opened in other apps), `network`, + object; the same objects left out are not counted for the File-only functions `open`, `read`, `readch`, + `readln`, `write`, `writeln`, `copy`, `createAlias`, `openDlg` and `saveDlg`, which a Folder object does not + have), `filesOpened` (files opened in other apps), `network`, `nativeCode`, `otherApps` (messages to other apps), `environment` (environment variables), `unseenCode` (`eval`, `new Function` and `$.evalFile`) and `preferences` (the reference app's preferences changed). - `problems` lists what would stop the script loading as written (strings, comments, regular expressions, @@ -7126,7 +7128,8 @@ same way for a blend's spine point; without `handle` it is refused. These rules `path.insertAnchor` keeps the direct-selected anchors and selected segments of the path on the same points: those after the new anchor on its subpath are numbered one higher, and a selected segment that the new anchor splits stays selected as its two halves, with the new anchor as an end of both that moves with them. Undo restores the path and -the selection in one step. +the selection in one step. With `selectAnchor: true` the path becomes the selection with only the new anchor +direct-selected, also when the path was selected; a `selectAnchor` value that is not a boolean is an error. `path.close {id, subpath?, at?, in?, out?, independent?}` closes an open subpath (by default the last open one). `at` moves the first anchor to `[x, y]`, its handles with it, before `in` and `out` are placed. `in` places the first anchor's incoming handle as `path.setHandle` places a handle: a smooth anchor turns its outgoing handle to @@ -8517,9 +8520,18 @@ The Selection & Anchor Display and General preferences apply to `pointer_gesture - `deleteKeepsPathsJoined` (General › Delete Removes Anchor Points and Keeps Paths Joined, off by default): the default of the `keepJoined` param of `edit.clear` (Delete, Backspace, Edit › Clear, and the Layers panel's Delete button while no row is highlighted). On, Delete removes the direct-selected anchors of a path as `path.removeAnchors` does, refitting the curve - around each one, so a closed path stays closed and an open path stays in one piece; a path left with fewer than two - anchors is deleted. The next anchor along (the one before at an open path's end) is then selected, so the next - Delete goes on along the path. Off, Delete deletes the anchors with their segments and opens the path there. + around each one, so a closed path stays closed and an open path stays in one piece. The next anchor along (the one + before at an open path's end) is then selected, so the next Delete goes on along the path. When no subpath that lost + an anchor keeps two anchors, the path stays selected whole, and the next Delete removes it. Off, Delete deletes the anchors with their segments and opens the path there. +- `doubleClickAddsAnchorPoints` (General › Double-Click Adds Anchor Points, off by default): on, a double-click + without modifier keys on a path segment with Direct Selection adds an anchor at the + clicked point (`path.insertAnchor` with `selectAnchor: true`): the curve keeps its shape, the new anchor alone is + selected, and the change is one undo step. The double-click takes the path whose stroke or outline is under the + pointer, selected or not, in a group or in isolation mode, a clipping path included, and the path's own line must + pass within the Selection & Anchor Display tolerance of the pointer. A double-click on an anchor, a direction + handle, a center point, a mesh point or a blend's spine point, on a fill, or on a wide stroke or an effect's outline + farther from the path, adds nothing and does what it did before. Group Selection is unchanged. Off, a Direct + Selection double-click on a segment adds nothing. - `hideCornerWidgetAbove` (177° by default): corners wider than this show no Live Corners widget (a rectangle's right angles hide below 90°). - `transformPatternTiles` (off by default): the default of the transforms' `patterns` param (`object.transform`, @@ -10910,7 +10922,11 @@ of a color shifted by hand. More than 256 entries, a key or value that is not a included), and two keys that name one color are errors. Presets and `webExport.settings` keep the map. In the dialog a double-click on an opaque swatch opens the Color Picker on the color shown (on the source color for a color already shifted; an agent sets `__editColor: "#source"`). Its OK shifts the color (picking the source color takes the shift away), and Cancel -leaves the table as it was. A shifted swatch shows the source color at its upper left and the new color at its lower +leaves the table as it was. An OK that would shift a 257th color changes nothing, and the status bar shows the +limit; a key shifted to itself or a deleted color does not count, and a new shift writes `shifted` without them. A key +written another way (`#F00`) still names its color, so a new shift or Unshift replaces it. A list entry written another +way also names its color: the table marks it, Lock, Transparent, Web Shift and Delete Color act on it, and new entries +are written as lowercase `#rrggbb`. A `#rrggbbaa` spelling names no table color. A shifted swatch shows the source color at its upper left and the new color at its lower right, with the lock mark, and Lock stays on until the color is unshifted. Web Shift replaces a shift by hand, and Unshift All Colors in the table's menu clears `shifted` and `webShift`. Only Web Colors in the picker starts off. @@ -13350,7 +13366,10 @@ dialog exposes `name`, `font_family`, `font_style`, `size`, `leading`, `kerning` `tcyLeftRight`, `rotation`, `akiLeft`, `akiRight`, `tsume`, `diacriticHorizontal`, `diacriticVertical`, `language`, `fill`, `fill_tint`, `stroke`, `stroke_tint`, `stroke_width`, `overprint_fill`, `overprint_stroke`, `ot_figure`, `ot_position`, `ot_liga`, `ot_calt`, `ot_dlig`, `ot_swsh`, `ot_salt`, `ot_titl`, `ot_ordn`, `ot_frac`, `ot_sets`, `section` (`general`, `basic`, `advanced`, `color` or `opentype`), and `preview`. An empty field leaves its -attribute unset. `leading` and `kerning` also accept `Auto` to store an explicit automatic value. +attribute unset. `leading` and `kerning` also accept `Auto` to store an explicit automatic value. A number field +given as text takes the arithmetic of the app's number fields (`"6x2"`, `"10+4"`) and a decimal comma; `size`, `leading`, +`baseline_shift`, `tcyUpDown`, `tcyLeftRight` and `stroke_width` also read a unit (`"1 in"`), a final `%` is read only +in `h_scale`, `v_scale`, `tsume`, `fill_tint` and `stroke_tint`, and a final `°` only in `rotation`. Advanced Character Formats holds `h_scale` and `v_scale` (percent, 1 to 10000), `baseline_shift` (points, -1296 to 1296), the Tate-chu-yoko Settings `tcyUpDown` and `tcyLeftRight` (points, -1296 to 1296, as `text.setRangeStyle` takes them; an explicit 0 stays distinct from unset), `rotation` (degrees, stored from -180 to 180), Insert Aki Left and Right `akiLeft` and `akiRight` (thousandths of diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9522c1895d..d40a4216cd 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: Text styles panel: right-click item context menus for Character Styles and Paragraph Styles with Options, Duplicate, Delete, Redefine, Clear Overrides; scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side columns; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: Text styles panel: right-click item context menus for Character Styles and Paragraph Styles with Options, Duplicate, Delete, Redefine, Clear Overrides; scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side columns; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -322,7 +322,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | anti-aliasing ghost borders (#983); TIFF choices and settings are implemented | 2–4 | estimated | | Print, colour management, separations, flattener | 3 | 80% | Production Preflight available; print preview fidelity remains | 2–4 | estimated | | Automation (Actions, Variables, scripting, batch) | 3 | 60% | a scripting surface (Illustrator: JavaScript/ExtendScript), Batch, image and graph variables, dataset import/export | 8–14 | estimated; MCP `add_text` exposes existing vertical type; score and hours unchanged | -| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Asset Export item context menus implemented (G12); Properties per context, 2 Preferences options stored but unused (#394, audited 2026-10-30: Scratch Disks, legacy vector clipboard), context menus in the panels that have none, accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; the line under the Preferences fields describes each General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices, Hyphenation, Plug-ins & Scratch Disks, User Interface, Performance, File Handling, Clipboard Handling, Appearance of Black and Devices setting on hover and keyboard focus (#8199, #8223, #8248, #8264, #8360, #8376, #8402, #8429, #8453, #8475, #8483, #8498), score and hours unchanged; numeric-field focus and normal text drags regression-tested (#1326); a focus click released more than 1 pt from its press keeps the caret and a tap within 1 pt selects all (#6659); artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged; Swatches item context menus have focused regressions and rendered-layout evidence below; Character Styles and Paragraph Styles item context menus have focused regressions (panels::text_styles::tests::right_click_context_menu_*); scores and estimates unchanged | +| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Asset Export item context menus implemented (G12); Properties per context, 2 Preferences options stored but unused (#394, audited 2026-10-30: Scratch Disks, legacy vector clipboard), context menus in the panels that have none, accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; the line under the Preferences fields describes each General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices, Hyphenation, Plug-ins & Scratch Disks, User Interface, Performance, File Handling, Clipboard Handling, Appearance of Black and Devices setting on hover and keyboard focus (#8199, #8223, #8248, #8264, #8360, #8376, #8402, #8429, #8453, #8475, #8483, #8498), score and hours unchanged; numeric-field focus and normal text drags regression-tested (#1326); a focus click released more than 1 pt from its press keeps the caret and a tap within 1 pt selects all (#6659); artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged; Swatches item context menus have focused regressions and rendered-layout evidence below; Character Styles and Paragraph Styles item context menus have focused regressions (panels::text_styles::tests::right_click_context_menu_*); swatches dropped on New Swatch or Delete Swatch carry the selected swatches the find field or kind filter hides (#8620); scores and estimates unchanged | | Libraries, Links, Package | 2 | 82% | shared libraries, linked graphics, gradients and patterns as library items (no cloud by design) | 2–3 | estimated; #5804: private native-picked raster editor (scores unchanged) | | Generative AI (Text to Vector, Generative Recolor, Shape Fill, Concept to Vector, Prompt to Edit, Rewrite Text) | 2 | 0% | a pluggable provider and the panels; needs an owner decision on models | 30–60 | measured (absent) | | **Feature depth** | **105** | **~75%** | | **~250–420** | | @@ -769,6 +769,7 @@ since 2026-10-01. - **Mirrored handles in a Direct Selection drag (#7842):** Cmd/Ctrl added after a handle drag begins puts the anchor's other handle opposite the dragged one at the same length, on paths, type on a path and blend spines, and the anchor keeps its kind; Shift constrains the dragged handle first, and Alt keeps the handles independent. At an open end, where no segment leaves the anchor on the other side, the handle moves as it does without Cmd/Ctrl. When Cmd/Ctrl lends Direct Selection for the gesture while another tool, such as the Pen, is chosen, that press does not mirror; letting it go and pressing it again during the drag does. This is VectorCraft's own behavior. Regression tests: `crates/engine/tests/direct_handle_mirror.rs`. - **Cut of picked anchors (#6361):** Edit › Cut removes direct-selected anchors from their path and from a compound path's member, with the segments attached to them, as Clear does. Picked segments still lose only those segments. When a path also has a picked segment, Cut removes and copies only its picked segments and ignores its picked anchors, on every contour, as Clear does; an anchor left without a surviving segment is removed with them. Regression tests: `cut_*_anchors_*` and `cut_of_an_anchor_with_a_segment_on_another_contour_leaves_the_source_as_clear_does` in `crates/engine/tests/it/copy_direct_selection.rs`. - **Escape in Selection tool drags:** Escape during a Selection tool move or Alt-drag copy, a bounding-box scale or rotation, a marquee, or a corner widget, pie widget or bracket drag cancels it: the art returns to its state at the press, no copy is left, no undo step is added, the release does nothing, and the tool stays chosen. This is VectorCraft's own behavior. Regression tests: `escape_cancels_*` in `select/tests.rs` and `pie.rs`, and `escape_cancels_a_selection_tool_move_copy_scale_or_rotation` in `tests/selectescape.rs`. +- **Commands run during a tool drag:** by VectorCraft's own rule, a command that changes the document while a tool drag is in progress (from a panel, a menu or `run_command`) records its own undo step before the drag's. The drag goes on with the art the command left, Escape cancels only the drag, and Undo takes back the drag first and the command next, with Real-time Drawing on or off. A selection the command makes does not change which objects the drag moves. Commands that keep the drag as a step first (Undo, Redo, `command.batch` and others), a Quick Pen press, and a copy made with `object.transform` during an Alt-drag work as before. Regression tests: `crates/engine/src/tests/interaction_commands.rs` and `tests::drag_commands` in `crates/ui-egui`. - **Large Shift-marquee selections and Select › Inverse:** `select.toggle` and `select.add` with many ids (a Shift-drag marquee sends them together) go through the selection once instead of once per id, and Select › Inverse looks each object up in a set of the selected ones. The resulting selection, its order and the reply are the same as before. With 50,000 objects the selection step of toggling every object off took 528 to 655 ms before and 2.5 to 4.6 ms after in 7 runs, wall clock on a machine that was running other builds (`cargo run --release -p vectorcraft-engine --example selection_bench`). Regression tests: `add_all_does_what_adding_each_does` and `toggle_all_does_what_toggling_each_does` in `crates/doc/src/selection/tests.rs`, and `toggle_and_add_handle_each_listed_id_in_order` in `crates/engine/tests/it/selection_commands.rs`. - **Shift-click in the Layers panel's selection column on a large layer:** `layer.selectAll {id, add: true}` checks whether the row's art is all selected with a set of the selected objects, and removes or adds that art in one pass instead of once per object. The resulting selection, its order, the reply and the highlighted rows are the same as before. On a layer of 50,000 objects the whole command took a median of 733 ms before and 6.9 ms after when all of the layer's art was selected, and 369 ms before and 24 ms after when every other object was, in 7 runs each, wall clock on Linux while other builds were running (`cargo run --release -p vectorcraft-engine --example layer_select_bench`). Regression test: `a_shift_click_in_the_selection_column_matches_adding_or_removing_each_id` in `crates/engine/src/tests/layers.rs`. - **Ctrl/Cmd-click and Shift-click on Layers panel target circles (#8639):** the target circles follow the same modifier rules as the row names, as the help page describes for selecting objects in the Layers panel: Shift for adjacent objects, Ctrl or Command for non-adjacent ones ([Move objects to different layers](https://helpx.adobe.com/illustrator/desktop/manage-layers/create-and-organize-layers/move-objects-to-different-layers.html)). Ctrl/Cmd-click adds the item (a layer: its art) to the selection or takes it out, which Shift-click did before (#913); Shift-click selects the art of every row from the last circle clicked (else the targeted row) to this one, and Shift+Ctrl/Cmd-click adds it (`layer.target {range, add?}`). Hidden or locked art and art outside the isolated group in the range is left out, and nothing stays targeted. Regression tests: `clicking_a_target_circle_targets_the_layer` and `shift_clicking_a_target_circle_selects_a_range_of_rows` in `crates/ui-egui/src/panels/layers/tests.rs`. @@ -1083,7 +1084,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Headless CLI (`vectorcraft-cli run`, `convert`, `info`, `bench`, `perf`, `mcp`). A `run` step, like a `command_batch` step over MCP, can use an earlier step's result (`"$1.id"`, #785); `run --commands FILE` (or `-` for standard input) reads the steps from a JSON array or JSON Lines, past the Windows command-line limit (#3147, `apps/vectorcraft-cli/tests/it/cli.rs` `run_reads_*`, `run_refuses_malformed_commands_naming_the_step`). - File › Scripts › Check Script… reads a script written for Illustrator (`.jsx`, `.jsxinc` or a compiled `.jsxbin`) without running any of it and reports what it needs (the document model, files, dialogs, menu commands, features only Illustrator has), what it would do outside the document, the menu commands and document-model members it uses, its directives and included files, and the problems that would stop it loading (`script.check`, which also reads `.js` files); File › Open and drag-and-drop show the report for `.jsx`, `.jsxinc` and `.jsxbin` files. - Check Script reads names by the same identifier rule as `vectorcraft-js`: Unicode 17.0 `ID_Start` characters, `$` and `_` start a name, and `ID_Continue` characters and `$` continue it (https://www.unicode.org/reports/tr31/, https://tc39.es/ecma262/#sec-names-and-keywords). U+2118, U+203F, U+00B7 and the zero width non-joiner and joiner are name characters, and U+00B2 and U+2E2F are not. Of the characters Unicode 17.0 assigned, U+088F starts a name and U+1ACF may follow its first character. A `\uXXXX` escape is read as its character only where a name may hold it, so `\u0030abc` does not become a name that starts with a digit; a `\u{…}` escape takes any number of hexadecimal digits up to U+10FFFF, and one that is empty, unclosed, out of range or a surrogate is not part of a name. Each `\u{…}` escape read in a name is reported as syntax newer than ES3, which has only the four-digit form (https://ecma-international.org/wp-content/uploads/ECMA-262_3rd_edition_december_1999.pdf, section 7.6). A private name may start with an escape (`this.#\u{61}pp` is the private name `#app`), and a private name at the start of a line inside braces is not read as a directive unless its name is a directive's. Tests: `crates/scriptcheck/src/tests.rs` (`names_are_made_of_the_unicode_identifier_characters`, `an_escape_stands_for_a_character_only_where_a_name_may_hold_it`, `braced_escapes_in_names_are_read_by_their_value`, `braced_name_escape_reports_later_syntax_and_member`, `private_names_with_escaped_starts_are_single_tokens`, `private_name_at_line_start_is_not_a_directive`), `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs` (`both_lexers_take_the_same_characters_into_names`). - - Check Script reports `file.write` and `filesWritten` when a script sets a File object's `length`, `hidden` or `readonly` (https://extendscript.docsforadobe.dev/file-system-access/file-object/), by plain or compound assignment, `++` or `--`, or the name as a string literal in brackets. It leaves out only objects that are always Folder objects, `new Folder(…)` and the `Folder` places such as `Folder.temp` other than `Folder.current`, which a script can assign; `Folder(…)` gives a File object when the path names a file and `Folder.selectDialog()` gives a File or Folder object (https://extendscript.docsforadobe.dev/file-system-access/folder-object/), so setting those counts, as it does on a variable that any assignment, in any branch or included file, gives such an object. Nothing counts as a Folder object in a check whose files use `with`, name `eval`, `Function`, `evalFile` or `constructor` as a word or as a string literal in brackets (`this['eval'](s)`, `(function () {}).constructor(s)`), read, call or assign a property in brackets on any object (a `[` after a value, not an array literal) when the brackets hold anything but one number or string literal (`g[k] = …`, `$['global'][k] = …`, `this[k](s)`, `this['ev' + 'al'](s)`, `this[('eval')](s)`, `this[0, 'eval'](s)`, `$[k](f)`, `(function () {})[k](s)`, or a preprocessor line inside the brackets) or the `[` opens while 4,096 other `[` are open, assign a property in brackets whose name is a string literal of more than 256 characters, assign properties of more than 1,000 different names on members, or assign or declare `Folder`, and a variable whose name a member assignment writes (`$.global.d = …`, `this.d = …`, `this['d'] = …`, with the string's escapes undone) counts as one that may hold a File object (`setting_a_folders_length_or_flags_does_not_write`, `a_variable_that_may_hold_a_file_counts_as_one`, `a_file_in_a_local_variable_leaves_an_outer_folder_alone`, `a_folder_that_other_code_may_rebind_counts_as_a_file`, `a_folder_that_unnamed_code_may_rebind_counts_as_a_file`, `a_bracketed_name_is_read_whole_or_counts_as_any_name`, `a_bracketed_variable_read_counts_as_any_name`, `a_bracketed_joined_name_counts_as_any_name`, `a_bracketed_name_in_parentheses_counts_as_any_name`, `a_bracketed_comma_expression_counts_as_any_name`, `a_bracketed_variable_call_on_dollar_counts_as_any_name`, `a_bracketed_variable_constructor_counts_as_any_name`, `a_literal_name_in_brackets_leaves_the_folder_alone`, `a_directive_in_a_bracketed_name_counts_as_any_name`). A test lists every global and member the script host adds to the JavaScript engine, except VectorCraft's own `vc` and its members, and fails when one has no row; for each one that reaches outside the document it checks that `script.check` reports the expected `outside` id, and it checks that the checker lists every directive the host reads. Tests: `crates/scriptcheck/src/tests.rs` (`setting_a_files_length_or_flags_writes_it`), `crates/engine/tests/it/script_host_vs_scriptcheck.rs` (`every_name_the_host_adds_has_a_row`, `every_name_that_reaches_outside_has_its_checker_id`, `the_checker_lists_every_directive_the_host_reads`). + - Check Script reports `file.write` and `filesWritten` when a script sets a File object's `length`, `hidden` or `readonly` (https://extendscript.docsforadobe.dev/file-system-access/file-object/), by plain or compound assignment, `++` or `--`, or the name as a string literal in brackets. It leaves out only objects that are always Folder objects, `new Folder(…)` and the `Folder` places such as `Folder.temp` other than `Folder.current`, which a script can assign; `Folder(…)` gives a File object when the path names a file and `Folder.selectDialog()` gives a File or Folder object (https://extendscript.docsforadobe.dev/file-system-access/folder-object/), so setting those counts, as it does on a variable that any assignment, in any branch or included file, gives such an object. Nothing counts as a Folder object in a check whose files use `with`, name `eval`, `Function`, `evalFile` or `constructor` as a word or as a string literal in brackets (`this['eval'](s)`, `(function () {}).constructor(s)`), read, call or assign a property in brackets on any object (a `[` after a value, not an array literal) when the brackets hold anything but one number or string literal (`g[k] = …`, `$['global'][k] = …`, `this[k](s)`, `this['ev' + 'al'](s)`, `this[('eval')](s)`, `this[0, 'eval'](s)`, `$[k](f)`, `(function () {})[k](s)`, or a preprocessor line inside the brackets) or the `[` opens while 4,096 other `[` are open, assign a property in brackets whose name is a string literal of more than 256 characters, assign properties of more than 1,000 different names on members, or assign or declare `Folder`, and a variable whose name a member assignment writes (`$.global.d = …`, `this.d = …`, `this['d'] = …`, with the string's escapes undone) counts as one that may hold a File object (`setting_a_folders_length_or_flags_does_not_write`, `a_variable_that_may_hold_a_file_counts_as_one`, `a_file_in_a_local_variable_leaves_an_outer_folder_alone`, `a_folder_that_other_code_may_rebind_counts_as_a_file`, `a_folder_that_unnamed_code_may_rebind_counts_as_a_file`, `a_bracketed_name_is_read_whole_or_counts_as_any_name`, `a_bracketed_variable_read_counts_as_any_name`, `a_bracketed_joined_name_counts_as_any_name`, `a_bracketed_name_in_parentheses_counts_as_any_name`, `a_bracketed_comma_expression_counts_as_any_name`, `a_bracketed_variable_call_on_dollar_counts_as_any_name`, `a_bracketed_variable_constructor_counts_as_any_name`, `a_literal_name_in_brackets_leaves_the_folder_alone`, `a_directive_in_a_bracketed_name_counts_as_any_name`). On the same Folder objects, calls of the File-only functions `open`, `read`, `readch`, `readln`, `write`, `writeln`, `copy`, `createAlias`, `openDlg` and `saveDlg`, which a Folder object does not have, count as no file read, write or dialog; `create`, `remove`, `rename`, `getFiles` and `selectDlg` still count (`file_only_calls_on_a_folder_do_nothing`). A test lists every global and member the script host adds to the JavaScript engine, except VectorCraft's own `vc` and its members, and fails when one has no row; for each one that reaches outside the document it checks that `script.check` reports the expected `outside` id, and it checks that the checker lists every directive the host reads. Tests: `crates/scriptcheck/src/tests.rs` (`setting_a_files_length_or_flags_writes_it`), `crates/engine/tests/it/script_host_vs_scriptcheck.rs` (`every_name_the_host_adds_has_a_row`, `every_name_that_reaches_outside_has_its_checker_id`, `the_checker_lists_every_directive_the_host_reads`). - `vectorcraft-js` parses JavaScript as ECMAScript 5.1 defines it, with the legacy octal forms, block functions and lenient regular expressions of Annex B, into a syntax tree with source spans. A comma may follow the last argument of a call or `new` expression and the last parameter of a function other than a setter, as ECMAScript 2017 allows (https://tc39.es/ecma262/2017/#sec-left-hand-side-expressions, https://tc39.es/ecma262/2017/#sec-function-definitions); `f(,)` and `f(1,,)` give a `SyntaxError`. It reads the `#target`, `#include` and other preprocessor lines as directives without running them, and a script that breaks the grammar or an early-error rule gives a `SyntaxError` with its line and column. Nesting past the parser's depth limit (`Options::max_depth`, 200 by default) gives a `SyntaxError` instead of exhausting the stack. `cargo xtask test262` fetches the conformance suite at a pinned commit and parses its ES5 tests: 5,411 of 5,418 runs pass (the 7 others use `let` and `const`). This entry covers parsing; the next entry covers running scripts. Tests: `crates/js/src/tests.rs`, `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs`. - `vectorcraft-js` identifiers, written out or as `\uXXXX` and `\u{...}` escapes, take the characters Unicode's `ID_Start` and `ID_Continue` properties allow (https://www.unicode.org/reports/tr31/), plus `$` and, at the start, `_`, as later ECMAScript editions define them (https://tc39.es/ecma262/#sec-names-and-keywords). `Other_ID_Start` characters such as U+2118 and `Other_ID_Continue` characters such as U+00B7 and the zero width non-joiner and joiner are accepted, and no `Pattern_Syntax` or `Pattern_White_Space` character is. Letter categories come from Unicode 17.0, so U+088F starts an identifier and U+1ACF may follow its first character; characters assigned after Unicode 17.0 are not yet identifier characters. Tests: `crates/js/src/tests.rs` (`identifier_characters_are_unicode_17_id_start_and_id_continue`, which checks every code point, `identifiers_take_the_characters_unicode_17_assigned`, `identifiers_take_the_other_id_start_and_continue_characters`, `identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes`, `no_pattern_syntax_or_white_space_character_is_an_identifier_character`). - `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`. @@ -1105,6 +1106,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Numeric fields keep the pointer's pressed character as the text-drag start when movement exceeds the click threshold (#1326); a completed focus click selects the unit too. Pixel/point, plain and optional fields are regression-tested in both directions, before/after focus, with replacement text; keyboard focus, double-click, arrows and wheel keep their prior behavior. Native egui input confirms partial replacement gives 17 px instead of 700 px, one Undo/Redo, window captures and an exact saved-document read in a separate CLI process. A focus click released more than 1 pt from its press keeps the caret, and a tap within 1 pt still selects all (#6659; short-drag and jitter-tap regressions in `tests/numfields.rs`). - Unit fields and length strings take `%` in arithmetic: `3cm*50%` reads as 1.5 cm, and `50pt+25%` reads as 62.5 pt. - Value fields and length strings read `x` as a multiplication sign, as they read `*` (#8435; the help's "Calculate values in a panel or dialog box" lists `x` for multiplication: [help PDF, archived](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf)). `X` and `×` also multiply; that is VectorCraft's own choice. `10x2` reads as 20 and `2x3 mm` as 6 mm. A lowercase `x` right after a `p` stays the `px` unit (`2px x 3` is 6 px, and `2px3` is not read). Tests: `x_is_a_multiplication_sign` in `crates/doc/src/tests/units.rs`. + - The number fields of Character Style Options read typed text with the same arithmetic and a decimal comma (`6x2` is 12, `200/2%` is 100%); the length fields also read a unit (`1 in` is 72 pt). A final `%` is read only in the percent fields and a final `°` only in Character Rotation, and an exponent (`1e3`) is not read. Tests: `number_fields_take_field_arithmetic` and `tsume_field_shows_sets_resets_and_commits` in `crates/ui-egui/src/dialogs/char_style_options/tests.rs`. - The contextual task bar's handle drags it anywhere on the canvas (kept whole on it as the window resizes); unpinned it keeps that offset as it follows the selection, and its More Options menu hides it, pins its position across selection changes (`window.taskBar.pin`), resets it under the selection (`window.taskBar.reset`) and shows the Properties panel. As in Illustrator the position isn't kept across launches. Not done: the bar's variants for other tools (only the selection tools, the Type tools, the basic shape tools, the Smooth tool and the Artboard tool show it). - A click on another object moves the contextual task bar under it without hiding it for the press; it gives way only to a drag (#4681). - With one image selected, the contextual task bar offers Image Trace, which traces the image at once with the Default preset (the Image Trace panel is left as it was), and Crop Image; with an Image Trace object it offers Expand, which keeps only the traced paths. This follows Illustrator's bar: for a selected image it includes Image Trace, Retype and Crop Image, and traced artwork can be expanded from it ([Contextual Task Bar announcement](https://community.adobe.com/announcements-651/contextual-task-bar-in-illustrator-2025-quick-actions-when-you-need-them-1546580)). Offset Path and Simplify, which don't apply to an image, aren't offered for one. Not done: Retype, which the app doesn't have. @@ -1496,6 +1498,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Direct Selection and Group Selection, a drag that starts on an object while the selection also holds direct-selected anchors or segments moves those anchors and the objects selected whole in one undo step (`path.moveAnchors`), as a drag of a selected anchor does, and the other anchors of a partly selected path stay in place. While Alt is held during the drag, it copies the selected objects instead (`object.transform`). When direct-selected anchors are moved or transformed together with objects selected whole (such a drag, an anchor drag, an arrow key, or Move, Rotate, Scale, Reflect and Shear without a copy), a path inside a selected group is transformed once, with the group. VectorCraft's own preference General › Interpolate Control Points When Moving Anchors (`interpolateControlPoints`, off by default, fixes #7832): on, a Direct Selection drag, an arrow-key nudge, a Move or a Transform Again of selected anchors re-maps both handles of each segment with one moved end by the turn, uniform scale and move that take its old ends to its new ends, so a segment between corner anchors keeps its shape; a segment with both ends moved, or with its ends at the same place before or after the move, moves rigidly, and a smooth anchor keeps its handles in line. The commands take an `interpolate` param that defaults to the preference, and the value used joins the journal and Transform Again. Each drag or nudge is one undo step (`a_nudge_with_the_preference_on_re_maps_both_handles_of_the_segment`, `a_direct_selection_drag_with_the_preference_on_re_maps_the_handles_in_one_undo_step`, `a_smooth_anchor_keeps_its_handles_in_line`). VectorCraft's own preference General › Delete Removes Anchor Points and Keeps Paths Joined (`deleteKeepsPathsJoined`, off by default, part of #8326): on, Delete, Backspace and Edit › Clear remove the direct-selected anchors of each path as Remove Anchor Points does, refitting the curve around each one, so a closed path stays closed and an open path stays in one piece; the next anchor along (the one before at an open path's end) is selected, so the next Delete goes on along the path. Paths with a selected segment are still cut there, objects selected whole are still deleted, and a path left with fewer than two anchors goes, in one undo step. `edit.clear` takes a `keepJoined` param that defaults to the preference, and the value used joins the journal (`with_the_preference_on_delete_keeps_a_closed_path_closed_and_selects_the_next_anchor`, `several_paths_and_an_object_selected_whole_change_in_one_undo_step`, `with_the_preference_on_delete_and_backspace_keep_the_path_joined`). + VectorCraft's own preference General › Double-Click Adds Anchor Points (`doubleClickAddsAnchorPoints`, off by default, part of #8326): on, a double-click without modifier keys on a path segment with Direct Selection adds an anchor at the clicked point, keeping the curve's shape, with only the new anchor selected, in one undo step (`path.insertAnchor` with `selectAnchor`); on an anchor, a handle, a center point, a blend's spine point or a fill the double-click does what it did before, and a clipping path's segment gets the anchor (`with_the_preference_on_a_double_click_on_a_segment_adds_an_anchor_there`, `with_the_preference_on_a_double_click_in_a_group_adds_only_on_a_segment`, `with_the_preference_on_a_double_click_gives_way_to_spine_points_and_reaches_clipping_paths`, `with_the_preference_on_a_double_click_on_a_segment_adds_an_anchor_in_one_undo_step`, `the_double_click_and_delete_preferences_are_separate`). A path segment with a control point whose x or y is infinite or larger in size than `f64::MAX / 16` is measured by its control points, so its bounds hold the whole curve and the canvas check refuses an edit that leaves such a path selected (`path.create` included). With Direct Selection, the Pen and the anchor tools, a group, compound path or clip group selected whole shows the anchors of its paths filled, as a path selected whole does; the direction handles still show only on a path that is selected itself. Public references: [Adjust anchor point, handle, and bounding box display size](https://web.archive.org/web/20251114182206/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/adjust-anchor-point-handle-and-bounding-box-display-size.html) and [Drawing basics](https://web.archive.org/web/20231130064834/https://helpx.adobe.com/illustrator/using/drawing-basics.html) (archived copies). When the Add Anchor Point tool, the Pen's Auto Add, the Smart Pen's Alt-click on a segment or Alt-click with the Scissors adds an anchor to a path with direct-selected anchors or segments (`path.insertAnchor`), the same points stay selected: the anchors and segments after the new anchor are numbered one higher, and a selected segment that the new anchor splits stays selected as its two halves. @@ -1576,6 +1579,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A Smooth drag measures only the anchors and curved segments near the drag, and each against only the stretches of the drag near it. A release still looks up every anchor and curved segment of a path in the drag's grid, so the lookups still grow with the path's length. The grid reduces the number of stretch measures. On a curved path of 100,000 anchors, a drag of 200 points over 200 pt of it makes 7,533 stretch measures to find the curved segments in its reach, where it made 19,899,801 (99,999 segments times 199 stretches). The smoothed path is the same as before (engine tests `a_drag_over_a_long_path_measures_only_what_is_near_it` and `the_drag_grid_gives_the_results_of_measuring_the_whole_drag` in `crates/engine/src/cmd/draw2/smooth.rs`). A segment leading out of the stretch a Smooth drag smooths that is in the drag's reach for no more than 1/64 of the reach from the stretch's anchor is left as it is, and the stretch ends at that anchor, so a drag that reaches an anchor an earlier drag added at the edge of its reach does not split the segment beyond it again or leave a corner there (`path.smoothRegion`). The 1/64 share is VectorCraft's own value (`tests/draw2.rs`, `smooth_drags_again_and_again_along_part_of_an_ellipse_add_no_anchors_or_corners`). Before a press that draws a new path, the Pencil cursor shows a small star, as [Draw freeform paths with the Pencil tool](https://web.archive.org/web/20260926095638/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-freeform-paths-with-the-pencil-tool.html) describes; over a selected path within Edit selected paths' distance, which the press continues from an end or redraws, the star is not shown ([Reshape paths with the Pencil tool](https://web.archive.org/web/20260106004407/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/reshape-paths-with-the-pencil-tool.html)). + With Edit selected paths on, a Pencil or Paintbrush stroke that starts on a selected path and ends farther than its distance takes the path with it (a closed path opens where the stroke starts; an open one is cut there and drops the part the stroke heads along), one that returns to its start adds a loop, one over an open path's two ends closes it, a stroke across a closed shape replaces the side nearer to it, the stroke's ends bend onto the path, and a selected compound path's member paths are redrawn (`path.freehand` `redraw`, #3793); while the stroke is drawn, the preview shows it as drawn and the path changes at the release ([Reshape paths with the Pencil tool](https://web.archive.org/web/20260106004407/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/reshape-paths-with-the-pencil-tool.html)). Keep selected in the Pencil and Paintbrush Tool Options is on by default: while it is on, a stroke selects the path it draws or continues and replaces the earlier selection. While it is off, a new stroke leaves nothing selected, the earlier selection included, as the reference application starts the stroke by dropping it (#5752); a continued or redrawn path is deselected while the rest of the selection stays (`path.freehand` `keepSelected`). With two open paths selected, a Pencil stroke from an end of one that ends within Edit selected paths' distance of an end of the other connects them into one path with the first path's appearance, in one undo step, as [Connect two paths with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/connect-two-paths-with-the-pencil-tool.html) describes (`path.freehand` `connect`). `path.freehand` and `brush.freehand` refuse a `connect` without `extend` with an error, and check a `connect` given with `extend` before a stroke of one point returns, so a bad one changes neither the path's brush nor the selection. @@ -1625,6 +1629,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Ctrl/Cmd+Alt-clicking an eye switches the other layers to Outline and the row's layer to Preview, or switches all layers back to Preview when the others are in Outline (`layer.outlineOthers`, `layer.previewAll`). Ctrl/Cmd+Alt-clicking New Layer adds a layer directly below the current layer, at its level (`layer.new {below: true}`), and Ctrl/Cmd+Alt-clicking New Sublayer adds a sublayer under the contents of the layer it goes into (`layer.newSublayer {bottom: true}`), each in one undo step. The reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists these clicks for placing a layer below the selected layer and a new sublayer at the bottom of the layer list. Alt-clicking a layer's or sublayer's name makes it the current layer, as a click does, and selects its visible, unlocked art, as its selection square does (`layer.selectAll`, then `layer.setCurrent`); on a hidden or locked layer it clears the selection. The reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists Alt-click on the layer name for selecting all objects on the layer. + A layer or sublayer whose selectable art is all selected shows the full-sized selection square instead of the small one, as the [help page](https://helpx.adobe.com/illustrator/desktop/manage-layers/create-and-organize-layers/layers-overview.html) describes for a layer with every item selected. As VectorCraft's own rules, sublayers follow the same rule, "all" means the visible, unlocked art its selection square selects (hidden or locked art does not keep the square small, and a selected member of a group is not the group), and a layer with no such art shows no square. A group row keeps the small square while only its members are selected (`panels::layers` tests `a_layer_with_all_its_art_selected_shows_the_full_square`, `a_layer_without_art_shows_no_square` and `full_layers_are_the_layers_with_all_their_art_selected`). Object › Arrange › Send to Current Layer returns the error "the target layer is locked or hidden" and leaves the selected objects where they are when the current layer is hidden or locked, or is inside a hidden or locked layer. Selected objects are deselected, the key object included, when a row drag moves them into a hidden layer or group, when `node.move` moves them into a hidden or locked layer or group, when Merge Selected moves them into a hidden or locked layer, when Collect in New Layer moves them into a new layer inside a hidden or locked layer, when Flatten Artwork moves them into a locked layer, and when applying a data set hides them. Layer Options for several highlighted rows shows the first row's settings, and OK changes only the settings set in the dialog: each row keeps its own color, Template, Lock, Show, Print, Preview and Dim Images otherwise (`crates/ui-egui/src/dialogs/layer_options.rs` tests). @@ -1858,7 +1863,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Character panel menu's Character Direction (with the Indic options; `text.setFormat {charDirection}`, `text.setRangeStyle {charDirection}`) sets the selected characters left to right or right to left inside their paragraph, as a Unicode bidi embedding: a date set Left to Right keeps its order in right-to-left text, and a word set Right to Left keeps the punctuation after it on its left. Default (the default) leaves the characters to the bidi algorithm; character styles and the native file keep the setting. In vertical type, the Tabs panel names its alignment buttons Top-Justified Tab, Center-Justified Tab, Bottom-Justified Tab and Decimal-Justified Tab, in their tool tips and for screen readers, and labels the position field Y. In horizontal type the buttons keep the names Left-Justified Tab and Right-Justified Tab, and the field keeps the label X. The Tabs panel's ruler is numbered in the General unit with the canvas rulers' label steps and a tick every tenth of a step. With the panel menu's Snap to Unit on, or Shift held, a tab stop placed by a click on the ruler or dragged on it lands on the nearest tick (`text.tabs.set`). - With Snap to Unit off and Shift not held, a tab stop placed by a click on the Tabs panel's ruler or dragged on it lands on the nearest whole point. A position typed in the X or Y field keeps its hundredths of a point. + With Snap to Unit off and Shift not held, a tab stop placed by a click on the Tabs panel's ruler or dragged on it lands on the nearest whole point. A position typed in the X or Y field keeps its hundredths of a point. When the shown paragraph has no tab stops and no indent marker is selected, a position typed in the X or Y field and committed adds a stop there with the chosen alignment and selects it, in one undo step, as a click on the ruler does; the [archived user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=521) gives typing a position as another way to set a new stop. The field holds a typed position to 0 to 100,000 pt (VectorCraft's own limits). Tests `panels::tabs::tests::typing_x_into_a_paragraph_without_stops_adds_and_selects_a_stop`, `typing_y_into_vertical_type_without_stops_adds_a_stop`, `a_refused_first_stop_adds_nothing_and_records_no_undo` and `typing_the_first_stop_over_mixed_paragraphs_uses_the_displayed_list`. The Tabs ruler's upper first-line marker and lower left-indent marker show absolute positions and set paragraph indents (`text.setFormat`). Dragging the lower marker keeps the upper position, while Ctrl-dragging it (Command on macOS) moves both; marker drags snap like tab stops, and each release is one undo step. With differing left indents, only the upper marker is shown and its absolute target applies to every touched paragraph. When a drag on the Tabs panel's ruler or a value typed in its X field moves a tab stop past another stop, the moved stop stays selected. With the Selection tool, the Tabs panel shows the ruler and stops of the first paragraph of the first selected text object, also when the text is inside a selected group or a shape is selected before it; a selection without text shows "No text selected". A stop set on that ruler is set on every selected text object and the text in selected groups, and other objects are left as they were. This is VectorCraft's own rule. Tests `panels::tabs::tests::the_ruler_shows_text_selected_after_an_object_that_is_not_text`, `the_ruler_shows_text_inside_a_selected_group`, `a_stop_added_on_a_mixed_selection_sets_every_selected_text` and `a_selection_without_text_shows_no_ruler`. @@ -2001,8 +2006,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Validation on 2026-11-15: native Windows formatting, workspace Clippy and all 39 focused Swatches tests passed. Windows full CI stopped at unchanged engine tests `tests::package::a_confined_package_names_files_outside_the_read_root_by_name` (slash-sensitive report assertion) and `tests::plugins::plugin_storage_behind_a_link_is_left_alone` (storage-link setup returned AlreadyExists). Both cases pass in the Linux/WSL full CI run, which passed all 13 gates. No engine or CI workflow changes are included. The Swatches panel menu has Add Selected Colors, on while art is selected: it adds a swatch for each color of the selected art that the panel does not hold yet, as global swatches the art's matching paints link to, in one undo step ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/use-swatches/add-colors-to-swatches.html) describes the panel menu command that adds the selected artwork's colors). The swatch names and the colors it reads (fills, strokes, text, gradient stops, mesh points) are VectorCraft's own, as for Add Used Colors. Add Used Colors and Add Selected Colors record no undo step when there is no new color, and still end typing in progress as its own step. With Global Edit on, the members the command does not read keep their colors. Evidence: `add_selected_colors_adds_the_selection_colors_as_global_swatches` in `crates/ui-egui/src/panels/swatches/tests.rs`; `add_used_colors_with_no_new_color_records_no_undo_step`, `add_used_colors_with_no_new_color_ends_the_typing` and `add_selected_colors_in_global_edit_keeps_the_other_members_colors` in `crates/engine/src/tests/swatchcmds.rs`. The panel's Delete Swatch and Swatch Options (footer buttons and panel menu), New Color Group and Save Swatch Library treat only None and [Registration] as reserved, so a user swatch or color group whose name starts with `[` can be deleted, edited, grouped and saved; selected names the document no longer holds are left out (`panels::swatches::tests::bracketed_user_swatches_and_groups_can_be_deleted_and_edited`). - Dragging swatches onto Delete Swatch deletes them ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=136), Replace, merge, or delete swatches section, lists this drag as one of the ways to delete the selected swatches): a swatch or color group dragged from the Swatches panel, in any view, and released on the Delete Swatch button is deleted through `swatch.delete`, even while nothing was selected and the button is disabled for clicks. A swatch that is part of the selection carries the other selected swatches of its kind with it. VectorCraft's own rules: the drop asks first as a plain click does, and Alt does not skip the question; Cancel keeps everything, and OK deletes them in one undo step; None and [Registration] are never taken; the button is enabled while swatches are selected or while a swatch or group of the active document is being dragged, and it is outlined only while such a swatch or group is held over it, so a paint from another panel, art and a swatch dragged from another document delete nothing. Tests: `panels::swatches::tests::swatches_dropped_on_delete_swatch_are_deleted_after_asking`, `delete_swatch_ignores_other_drags`. - Dragging swatches onto New Swatch duplicates them ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/use-swatches/duplicate-swatches.html) gives this drag as another way to duplicate the selected swatches): a swatch dragged from the Swatches panel, in any view, and released on the New Swatch button is copied through `swatch.duplicate` without opening the New Swatch dialog. A swatch that is part of the selection carries the other selected swatches with it. VectorCraft's own rules: each copy goes just after its swatch and in its color group, named `<name> copy` and then `<name> copy 2`; the copies of one drop are one undo step and are selected; modifiers held on release do not change the drop; color groups, None and [Registration] are not duplicated; the button is outlined only while such a swatch of the active document is held over it, so a paint from another panel, art, a swatch dragged from another document and a swatch deleted during the drag duplicate nothing. Tests: `panels::swatches::tests::swatches_dropped_on_new_swatch_are_duplicated`, `new_swatch_ignores_other_drags`. + Dragging swatches onto Delete Swatch deletes them ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=136), Replace, merge, or delete swatches section, lists this drag as one of the ways to delete the selected swatches): a swatch or color group dragged from the Swatches panel, in any view, and released on the Delete Swatch button is deleted through `swatch.delete`, even while nothing was selected and the button is disabled for clicks. A swatch that is part of the selection carries the other selected swatches of its kind with it, also those the find field or the kind filter hides. VectorCraft's own rules: the drop asks first as a plain click does, and Alt does not skip the question; Cancel keeps everything, and OK deletes them in one undo step; None and [Registration] are never taken; the button is enabled while swatches are selected or while a swatch or group of the active document is being dragged, and it is outlined only while such a swatch or group is held over it, so a paint from another panel, art and a swatch dragged from another document delete nothing. Tests: `panels::swatches::tests::swatches_dropped_on_delete_swatch_are_deleted_after_asking`, `delete_swatch_ignores_other_drags`. + Dragging swatches onto New Swatch duplicates them ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/use-swatches/duplicate-swatches.html) gives this drag as another way to duplicate the selected swatches): a swatch dragged from the Swatches panel, in any view, and released on the New Swatch button is copied through `swatch.duplicate` without opening the New Swatch dialog. A swatch that is part of the selection carries the other selected swatches with it, also those the find field or the kind filter hides. VectorCraft's own rules: each copy goes just after its swatch and in its color group, named `<name> copy` and then `<name> copy 2`; the copies of one drop are one undo step and are selected in panel order; modifiers held on release do not change the drop; color groups, None and [Registration] are not duplicated; the button is outlined only while such a swatch of the active document is held over it, so a paint from another panel, art, a swatch dragged from another document and a swatch deleted during the drag duplicate nothing. Tests: `panels::swatches::tests::swatches_dropped_on_new_swatch_are_duplicated`, `new_swatch_ignores_other_drags`, `footer_drops_carry_selected_swatches_that_find_hides`. Editing, renaming, deleting or merging a global swatch also changes the colors linked to it in graph designs, the art of brushes and the tile that pattern editing's Cancel puts back, in the same undo step as the rest of the art; Default Swatches with replace unlinks them there too. A swatch step in `command.batch` (Delete, Swatch Options, Merge, Edit Color Group) changes the fill and stroke for new art as the command run on its own does, so art drawn later in the batch or after it takes the same paint; a batch that fails, and a canceled batch preview, put back the paints it started with, and a canceled Swatch Options preview leaves them as they were. These swatch commands also change the fills and strokes of the appearance new art takes, and Undo and Redo of the command or the batch put the paints for new art back with the swatches. Spot Colors options (`swatch.spotOptions`) and Default Swatches with replace (`swatch.resetDefaults {replace: true}`) as `command.batch` steps also change the fill and stroke for new art as each command run on its own does: a fill or stroke linked to a Lab spot swatch keeps its link and tint and takes the Lab values or their CMYK equivalent, and one linked to a swatch the replace removes keeps its color and loses the link. Evidence: `swatch_steps_in_a_batch_change_the_new_art_paints_as_commands_do`, `spot_colors_options_in_a_batch_change_the_new_art_paints_as_the_command_does`, `default_swatches_replace_in_a_batch_unlinks_the_new_art_paints_as_the_command_does`, `undo_and_redo_of_a_swatch_edit_put_back_the_new_art_paints`, `swatch_edits_reach_the_paints_of_the_new_art_template`, `a_failed_batch_puts_back_the_new_art_paints_a_swatch_step_changed` and `canceling_a_swatch_options_preview_keeps_the_new_art_paints` in `crates/engine/src/tests/swatches.rs`. Add Used Colors (`swatch.addUsedColors`) and Select All Unused (`swatch.unused`) look colors, swatch names, links, tints and gradients up in hash sets instead of searching every swatch and color for each color or linked paint (New Color Group from artwork too), and New Swatch with several colors (`swatch.new`), New Color Group (`swatch.newGroup`) and Edit Color Group (`swatch.editGroup`) name their new swatches from one set of the names already taken. The new swatches keep their names, order and links, and Select All Unused lists the same swatches. Evidence: `add_used_colors_adds_each_new_color_once_with_free_names`, `add_used_colors_global_links_every_paint_of_a_new_color`, `unused_matches_links_tints_colors_gradients_and_patterns_exactly`, `new_swatches_from_colors_are_numbered_after_names_already_taken`, `new_color_group_numbers_its_colors_after_the_group_and_its_moved_swatches`, `new_color_group_from_artwork_lists_each_color_once_with_free_names` and `edit_color_group_numbers_extra_colors_after_the_names_it_keeps` in `crates/engine/src/tests/swatchcmds.rs`; `free_swatch_names_match_naming_each_swatch_as_it_is_added` and `free_swatch_names_match_new_swatch_names_as_swatches_are_added` in `crates/doc/src/swatches.rs`. @@ -2085,7 +2090,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With a gradient stop or a freeform gradient point selected, Alt-clicking a color swatch in the Swatches panel recolors it instead of the inactive Fill or Stroke. In the Gradient tool's freeform Lines mode, moving the pointer out of the object and back ends the line being drawn, and the next click on the object starts a new line from the point it adds. The help page describes this way of starting another line segment in the same object ([Create freeform gradient in lines mode](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=262)). As VectorCraft's own rules, the line ends as soon as the pointer, with no button held, moves off the object's own art, its fill, stroke or glyphs (other art lying over the object still counts as inside), and Escape and a click off the art still end it as before (`xform::freeform::tests::leaving_the_object_ends_the_line`). - **Freeform gradient colors in their own model:** Object ▸ Expand and Object ▸ Create Gradient Mesh (`object.mesh.create`) mix a freeform gradient's points in the color model they share: points of C50 M20 Y0 K10 give mesh points of C50 M20 Y0 K10, and RGB points keep their values in a working RGB space other than sRGB. The canvas, the gradient chips and the SVG, PDF, EPS and EMF writers mix the points in that model too. PDF and EPS write a gradient whose points are all CMYK, or all Gray in a CMYK file, as a CMYK image, which PDF's Output settings convert as they convert any CMYK image. Points in different models mix in display RGB (on the canvas in a CMYK document that shows transparency, as the inks of each point), and a CMYK document stores the result of Expand as CMYK through the color settings. Points colored along CMYK stops (`paint.editGradient {stops}`, or a CMYK gradient switched to freeform) are CMYK, and so are a point `paint.freeform.splitLine` adds between CMYK points and a point `paint.freeform.addPoint` adds without `color` to CMYK points. Public reference: [Gradients](https://web.archive.org/web/20250714042311/https://helpx.adobe.com/illustrator/using/gradients.html) and [Meshes](https://web.archive.org/web/20250812201019/https://helpx.adobe.com/illustrator/using/meshes.html), which do not state how colors in different models mix; the rule is VectorCraft's own. - - **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty-one more arrowheads (among them Line Arrow: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, cut square, #5421), and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. A width profile's sides run as a smooth C1 curve between the width points (a monotone cubic Hermite, Fritsch–Carlson, with the one-sided three-point PCHIP slope at the profile's ends and flat either side of a step), sampled adaptively along the path (two samples per profile segment, refined where the width bends, and leaning on dense path flattening) so straight runs draw it too; added samples offset along the source curve's exact tangent, not the flattened chord, so high zoom follows the true width; the sampled edges are fitted with G1 cubics within a tenth of the flattening tolerance (0.001 pt at the default 0.01 pt) rather than one cubic per flatten step, so exports stay close to a uniform stroke's path data; a point reshapes the curve as far as its neighbours' neighbours (their slopes depend on it), and coincident points still step. + - **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty-one more arrowheads (among them Line Arrow: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, cut square, #5421), and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. A width profile's sides run as a smooth C1 curve between the width points (a monotone cubic Hermite, Fritsch–Carlson, with each end's own span slope and flat either side of a step), sampled adaptively along the path (two samples per profile segment, refined until the line between samples stays within the outline tolerance, and reusing a segment's own flattened points only where they already follow the curve) so straight runs draw it too; added samples offset along the source curve's exact tangent, not the flattened chord, so high zoom follows the true width; the sampled edges are fitted with G1 cubics within the flattening tolerance (0.01 pt) rather than one cubic per flatten step, so a profiled outline draws the same shape as a uniform one and exports stay close to its path data; a point reshapes the curve as far as its neighbours' neighbours (their slopes depend on it), and coincident points still step. - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: Stylus Wheel for Pattern brushes and on Windows and the web, pen pressure on macOS where the windowing layer reports none, and tilt, bearing and rotation for Pattern and Bristle brushes and on native Wayland and the web. Under Tints and Tints and Shades, art in black ink alone goes by its ink amount, and a process or gray stroke color's tints and shades stay in that color's model; these are VectorCraft's own rules. Scale Proportionately art is scaled across by the stroke weight and the Width, as Stretch to Fit Stroke Length and Stretch Between Guides art is, on top of the scale the path length gives it, so a 3 pt stroke draws the art three times as wide as a 1 pt stroke. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page says Scale Proportionately keeps the art's proportions and does not say how the stroke weight applies; that rule is VectorCraft's own. Evidence: `tests::art_brush_proportional_grows_with_weight` (vectorcraft-brush). @@ -3433,7 +3438,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | 2026-10-23 | minor | Artboard Options: Show Center Mark and Show Cross Hairs (`artboard.setProps`/`artboard.new` `showCenterMark`, `showCrossHairs`) draw a center cross and lines from the middle of each side through the center on the canvas only, in one undo step; video safe areas, video rulers and the pixel aspect ratio remain missing; scores and estimates unchanged. | | 2026-10-23 | minor | Path operations: Simplify of part of a path: with anchors or segments of a path direct-selected, Object › Path › Simplify (slider, Auto-Simplify and dialog) refits only each run of selected segments between its end anchors; no longer listed as missing; evidence added; score and hours unchanged (estimated). | | 2026-10-23 | minor | Path operations: Simplify: Object › Path › Simplify opens its slider at the Auto-Simplify level for the selection, previewing that result, instead of at 1 pt; partial-path simplify remains missing; score and hours unchanged (estimated). | -| 2026-10-23 | minor | Width-profile outlines sample adaptively: two samples per profile segment, refined where the width bends, and only where the flattened path does not already sample the width. The sampled edges are fitted with G1 cubics within a tenth of the flattening tolerance (0.001 pt by default) instead of one cubic per flatten step. On the reviewer's 1,500-ellipse fixture (20–200 pt ellipses, 3–12 pt weights) the PDF falls to 3.59 MB and the SVG to 6.79 MB (reported main baselines 4.48 MB and 9.30 MB, about 0.80× and 0.73×), and `profiled_outlines_stay_compact` guards the path-element count. Scores and estimates unchanged. | +| 2026-10-23 | minor | Width-profile outlines sample adaptively: two samples per profile segment, refined until the line between samples stays within the outline tolerance, and only where the flattened path does not already sample the width. The sampled edges are fitted with G1 cubics within the flattening tolerance (0.01 pt by default) instead of one cubic per flatten step, and a profiled outline now covers the same area as before the smoothing (on a star with the Wave profile, 15597.7 pt² against 15595.4 pt², and the same on a Wave-profile line). On the reviewer's 1,500-ellipse fixture (20–200 pt ellipses, 3–12 pt weights) the PDF falls to 3.59 MB and the SVG to 6.79 MB (reported main baselines 4.48 MB and 9.30 MB, about 0.80× and 0.73×), and `profiled_outlines_stay_compact` guards the path-element count. Scores and estimates unchanged. | | 2026-10-22 | minor | Drawing tools: a Pen, Anchor Point or Direct Selection drag's preview no longer stalls (#834: the position where the pointer re-entered the window could be skipped, and the move in the release's frame was lost); score and hours unchanged (estimated) | | 2026-10-22 | minor | Live vector effects: the Transform effect has Transform Objects, Transform Patterns and Scale Strokes & Effects, its checkboxes visible (#885); the area row now lists only the options on a fill's or stroke's own Transform effect. Score and hours unchanged (estimated). | | 2026-10-22 | minor | Libraries panel: the buttons beside the library picker show the items as icons (the default) or in a list, colours and graphics as rows with their names (a colour's hex value too), dragged and dropped by row; graphic thumbnails are shrunk to the size they are drawn at, so thin strokes stay whole. Tests: `panels::libraries::tests::the_list_view_shows_names_and_takes_drops_by_row`, `the_panel_draws_its_libraries`. Scores and hours unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e736d3aae5..c74a8a8d7b 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -223,7 +223,7 @@ tools, never checked side by side) isn't captured row by row. | Blend Replace Spine, move and Undo redraw (#5179) | CPU regression-tested | Renderer damage bounds include keys and steps rotated along a curved spine. Both original straight and curved CPU regressions pass, checking full-frame agreement and that every changed pixel lies inside the advertised redraw area. | | Several blend spine points picked and dragged together (#5285) | done | with Direct Selection, Shift-click picks more points of a selected blend's spine or takes one away, as on a path; dragging any picked point moves them all, and the key objects on them, in one undo step (`object.blend.spine.moveAnchor {with}`); a marquee picks the spine points inside it on the topmost selected blend, and with Shift adds or takes them away | | Add/Delete/Anchor Point tools; Anchor Point tool drags segments to reshape | done | #2267: a click on a handle end retracts that handle and leaves the anchor a corner with the other one; Shift held at the press on an anchor moves it, handles and all (Shift kept down: at 45° steps) instead of pulling out handles; Alt held while dragging a handle links it with the opposite handle and makes the anchor smooth, on a blend's spine too | -| Pencil: Fidelity, Keep selected, Alt to Smooth, edit selected paths, close by proximity | done | Fidelity is in screen pixels, the same at any zoom, and goes down to 0.01 px in the dialog and the tool, which sends `path.freehand` the value in points at the current zoom (#5729; the Smooth tool keeps 0.05 pt); its slider runs across the Tool Options row on a logarithmic rail from 0.01 to 20 px, the field shows hundredths, and the slider's and the field's arrow keys step hundredths up to 0.1 px, tenths up to 1 px and whole pixels above (Shift ×10) (#3328); Alt key toggles to Smooth Tool (#2001); Shift held at the press draws a straight line at 45° steps from the Constrain Angle, and Alt held at the press (with Alt key toggles to Smooth Tool off) a straight line at any angle (#3799), with a straight-line cursor (a short level line) while Shift or Alt is held before the press, and a path-continuation cursor (a short rising line) over an end of a selected open path, where the stroke continues the path, freehand or straight, and while a continuing stroke ends near an open end of another selected path it connects to; Edit Selected Paths continues a selected path from an end and, from a stroke that starts and ends on a selected path, redraws the section between (the shorter way round a closed path, #2850); with Keep selected (Pencil and Paintbrush, on by default) on, a stroke selects the path it draws or continues and replaces the earlier selection, and off a new stroke leaves nothing selected, the earlier selection included, while a continued or redrawn path is deselected and the rest of the selection stays; a filled Pencil path keeps a stroke of None (#1804, part of #1679); while a freehand stroke is drawn back to within Close Paths When Ends Are Within of its start, or a stroke continuing a selected path (a straight line too) to within it of that path's other end, the Pencil and the Paintbrush show the closing cursor, and a release there closes the path; a Pencil stroke from an end of one selected open path to an end of another connects the two into one path | +| Pencil: Fidelity, Keep selected, Alt to Smooth, edit selected paths, close by proximity | done | Fidelity is in screen pixels, the same at any zoom, and goes down to 0.01 px in the dialog and the tool, which sends `path.freehand` the value in points at the current zoom (#5729; the Smooth tool keeps 0.05 pt); its slider runs across the Tool Options row on a logarithmic rail from 0.01 to 20 px, the field shows hundredths, and the slider's and the field's arrow keys step hundredths up to 0.1 px, tenths up to 1 px and whole pixels above (Shift ×10) (#3328); Alt key toggles to Smooth Tool (#2001); Shift held at the press draws a straight line at 45° steps from the Constrain Angle, and Alt held at the press (with Alt key toggles to Smooth Tool off) a straight line at any angle (#3799), with a straight-line cursor (a short level line) while Shift or Alt is held before the press, and a path-continuation cursor (a short rising line) over an end of a selected open path, where the stroke continues the path, freehand or straight, and while a continuing stroke ends near an open end of another selected path it connects to; Edit Selected Paths continues a selected path from an end and, from a stroke that starts and ends on a selected path, redraws the section between (the way round a closed path that leaves the bigger shape, so a stroke across a shape carves off its smaller part and an arch over a thin shape's side keeps the shape; on an open path the way the stroke runs along it at each end decides: where it starts it replaces the part it runs along, where it lands it joins the part it runs into, so it replaces the part between, closes the path round it without the closing cursor, or ends where the pen is lifted; #2850), the stroke's ends bent smoothly onto the path; a stroke lifted farther than the distance takes the path with it (a closed path opens where the stroke starts, an open one is cut there and drops the part the stroke heads along), one back to its starting point adds a loop, and a selected compound path's member paths are redrawn too (#3793); while such a stroke is drawn the preview shows the stroke as drawn and the path changes at the release; with Keep selected (Pencil and Paintbrush, on by default) on, a stroke selects the path it draws or continues and replaces the earlier selection, and off a new stroke leaves nothing selected, the earlier selection included, while a continued or redrawn path is deselected and the rest of the selection stays; a filled Pencil path keeps a stroke of None (#1804, part of #1679); while a freehand stroke is drawn back to within Close Paths When Ends Are Within of its start, or a stroke continuing a selected path (a straight line too) to within it of that path's other end, the Pencil and the Paintbrush show the closing cursor, and a release there closes the path; a Pencil stroke from an end of one selected open path to an end of another connects the two into one path | | Drop Shadow, Outer Glow and Inner Glow: Opacity, the offsets, Blur and Darkness have spinner arrows that step by one (a unit for distances), repeat when held and stop at the fields' ends (#5367, #5368) | done | dialogs::effect test drop_shadow_and_outer_glow_fields_have_spinner_arrows; other effect dialogs' number fields still have none | | Effect dialogs' colour fields: a swatch beside the hex follows typed values, and a double-click opens the Color Picker over the dialog, whose OK fills it and Cancel comes back unchanged (#5365) | done | dialogs::effect tests outer_glow_colour_swatch_opens_the_color_picker and drop_shadow_colour_swatch_opens_the_color_picker (Drop Shadow's Color, #5364); the picker previews nothing itself, the effect dialog previews the returned colour | | Join tool scrubbing, Average, Join | done | Join merges the direct-selected anchors lying on one another along a path, as after Average, into one (#1533); the Join tool trims two crossing open paths whose overhanging ends it scrubs over and joins them at the crossing, instead of drawing a segment between their ends (#5844) |