diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 0bcea57790..a1122e5a7c 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -33,8 +33,8 @@ pub use inline::{SYMBOL_HALF, SYMBOL_SIZES}; pub use shared::Shared; pub use symbol_export_type::{SYMBOL_EXPORT_TYPE, SymbolExportType}; pub use symbol_nine_slice::{ - EditedNineSlice, MAX_SLICE_GROWTH, MIN_CENTER_BAND, NineSliceGuide, NineSliceMap, PAINTED_EFFECTS, SYMBOL_NINE_SLICE, SymbolNineSlice, - charge_symbol_art, + EditedNineSlice, MAX_GUIDE_FRACTION, MAX_SLICE_GROWTH, MIN_CENTER_BAND, NineSliceGuide, NineSliceMap, PAINTED_EFFECTS, SYMBOL_NINE_SLICE, + SymbolNineSlice, charge_symbol_art, }; pub use symbol_overrides::SymbolOverride; pub use symbol_registration::{SYMBOL_REGISTRATION, SymbolRegistration}; diff --git a/crates/doc/src/live.rs b/crates/doc/src/live.rs index b4c0f9fdd8..39fe8cbc43 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -55,7 +55,7 @@ use blend_spec::{blend_color_shift, blend_ramp}; pub use envelope::{ EnvelopeKind, EnvelopeMap, EnvelopeOptions, H_DOWN, H_LEFT, H_RIGHT, H_UP, PreserveShape, TypeInk, envelope_bounds, envelope_content_bounds, envelope_content_boxes, envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_of, envelope_overlay, envelope_stroke_margin, - set_type_ink, smooth_handles, + set_type_ink, smooth_handles, warp_grid, }; pub(crate) use expand::max_outset; pub use expand::{ diff --git a/crates/doc/src/live/envelope.rs b/crates/doc/src/live/envelope.rs index f197837020..44dc406c1d 100644 --- a/crates/doc/src/live/envelope.rs +++ b/crates/doc/src/live/envelope.rs @@ -525,21 +525,106 @@ pub fn envelope_of(doc: &crate::Document, id: NodeId) -> Option<&Node> { doc.ancestry(id)?.into_iter().rev().find_map(|a| doc.node(a).filter(|n| matches!(n.kind, NodeKind::Envelope { .. }))) } -/// What a selected envelope shows on the canvas: its mesh lines (a warp's surface on a 4×4 grid, -/// a mesh envelope's own grid) or its top object's outline, and for a mesh envelope the grid to -/// edit (its points and handles). +/// What a selected envelope shows on the canvas: its mesh lines (a warp's surface on its +/// [`warp_grid`], a mesh envelope's own grid) or its top object's outline, and for a warp or mesh +/// envelope the grid to edit (its points and handles; none while its contents are edited). pub fn envelope_overlay(n: &Node) -> Option<(PathData, Option)> { - let NodeKind::Envelope { kind, .. } = &n.kind else { return None }; + let NodeKind::Envelope { kind, editing, .. } = &n.kind else { return None }; + let points = |grid: GradientMesh| (!*editing).then_some(grid); match &**kind { - EnvelopeKind::Mesh { rows, cols, points, handles } => { - let grid = envelope_grid(*rows, *cols, points, handles)?; - Some((grid.lines(), Some(grid))) + EnvelopeKind::Mesh { rows, cols, points: at, handles } => { + let grid = envelope_grid(*rows, *cols, at, handles)?; + Some((grid.lines(), points(grid))) } - EnvelopeKind::Warp { .. } => Some((EnvelopeMap::of(n)?.surface_mesh(4, 4, Color::BLACK).lines(), None)), + EnvelopeKind::Warp { .. } => match warp_grid(n) { + Some(grid) => Some((grid.lines(), points(grid))), + None => Some((EnvelopeMap::of(n)?.surface_mesh(4, 4, Color::BLACK).lines(), None)), + }, EnvelopeKind::TopObject { path, .. } => Some((path.clone(), None)), } } +/// The grid sizes [`warp_grid`] tries, in order: patches per row and per column. +const WARP_GRIDS: [u32; 3] = [4, 8, 16]; + +/// How far a [`warp_grid`] may draw from the warp it replaces, as a share of the diagonal of the +/// warp's bounds. +const WARP_GRID_TOLERANCE: f64 = 1e-3; + +/// The grid a warp envelope's points and handles are edited on: its surface sampled on the first +/// of 4×4, 8×8 and 16×16 patches whose curves draw within [`WARP_GRID_TOLERANCE`] of the warp, with +/// handles along it, as a gradient mesh with black points. Editing a point makes the envelope a +/// mesh envelope with this grid. `None` for other nodes, for content with no bounds, and for a warp +/// that no such grid follows closely enough or whose grid isn't finite. +/// Built again only when the envelope's content objects, warp, frame or options change, or what +/// type is measured with ([`set_type_ink`]). +pub fn warp_grid(n: &Node) -> Option { + let NodeKind::Envelope { content, kind, frame, options, .. } = &n.kind else { return None }; + if !matches!(**kind, EnvelopeKind::Warp { .. }) { + return None; + } + // `None` until a measure is registered, so a grid kept before then is built again after. + let inputs = TYPE_INK.get().map(|(_, inputs)| inputs()); + let key: Vec = content.iter().map(|c| Arc::as_ptr(c) as usize).collect(); + let same = |k: &KeptGrid| k.kind == **kind && k.frame == **frame && k.options == *options && k.inputs == inputs; + if let Some(grid) = WARP_GRIDS_KEPT.with_borrow(|kept| kept.get(&key).filter(|k| same(k)).map(|k| k.grid.clone())) { + return grid; + } + let grid = build_warp_grid(n); + WARP_GRIDS_KEPT.with_borrow_mut(|kept| { + if kept.len() >= WARP_GRID_KEPT { + // Entries for content that no longer exists go first, then one entry at a time. + kept.retain(|_, k| k.content.iter().all(|c| c.strong_count() > 0)); + if kept.len() >= WARP_GRID_KEPT + && let Some(any) = kept.keys().next().cloned() + { + kept.remove(&any); + } + } + // The weak pointers keep the content's addresses from being reused while the entry is kept. + let kept_content = content.iter().map(Arc::downgrade).collect(); + kept.insert(key, KeptGrid { content: kept_content, kind: (**kind).clone(), frame: **frame, options: *options, inputs, grid: grid.clone() }); + }); + grid +} + +/// A grid [`warp_grid`] built, with what it was built from. +struct KeptGrid { + content: Vec>, + kind: EnvelopeKind, + frame: Affine, + options: EnvelopeOptions, + inputs: Option, + grid: Option, +} + +/// How many grids [`warp_grid`] keeps on one thread. +const WARP_GRID_KEPT: usize = 1024; + +std::thread_local! { + /// The grids [`warp_grid`] built on this thread, by the addresses of their envelopes' content. + static WARP_GRIDS_KEPT: std::cell::RefCell, KeptGrid>> = Default::default(); +} + +/// [`warp_grid`], built from scratch. +fn build_warp_grid(n: &Node) -> Option { + let map = EnvelopeMap::of(n)?; + let bounds = map.bounds()?; + let tol = bounds.width().hypot(bounds.height()) * WARP_GRID_TOLERANCE; + if !tol.is_finite() { + return None; + } + WARP_GRIDS.into_iter().find_map(|k| { + let m = map.surface_mesh(k, k, Color::BLACK); + let finite = m.points.iter().all(|q| q.p.is_finite() && q.handles.iter().all(|h| h.is_finite())); + // Each patch is checked at its corners, the middles of its sides and its middle. + let steps = 2 * k as usize; + let at = |i: usize| i as f64 / steps as f64; + let fits = || (0..=steps).all(|j| (0..=steps).all(|i| mesh_at(&m, at(i), at(j)).distance(map.at(at(i), at(j))) <= tol)); + (finite && fits()).then_some(m) + }) +} + /// The frame an envelope keeps after transform `m` (its frame so far composed with the /// transform): identity when its axes stay square to the page, unflipped, since evaluating on /// the page axes gives the same result then. @@ -760,6 +845,163 @@ mod tests { assert!(content_box(&nested, false, Affine::IDENTITY).is_some()); } + /// A warp envelope of `style` at `bend` with map `version` around a 200×100 rectangle at + /// (100, 50). + fn warp_node(style: &str, bend: f64, h: f64, version: u32) -> Node { + let rect = vectorcraft_geom::shapes::rectangle(Rect::new(100.0, 50.0, 300.0, 150.0)); + let content = Arc::new(Node::path(NodeId(1), rect, crate::Appearance::default_art())); + let kind = EnvelopeKind::Warp { style: style.into(), bend, h, v: 0.0, horizontal: true, version }; + Node::new( + NodeId(2), + NodeKind::Envelope { + content: vec![content], + kind: Box::new(kind), + fidelity: 50.0, + editing: false, + options: EnvelopeOptions::NEW, + frame: Box::new(Affine::IDENTITY), + }, + ) + } + + const STYLES: [&str; 15] = [ + "arc", + "arcLower", + "arcUpper", + "arch", + "bulge", + "shellLower", + "shellUpper", + "flag", + "wave", + "fish", + "rise", + "fisheye", + "inflate", + "squeeze", + "twist", + ]; + + /// Every warp style's Bézier net has a grid to edit: its points lie on the warp, and the grid + /// draws within a thousandth of the warp's diagonal of it, between the grid lines too. The + /// overlay shows that grid's lines and points. + #[test] + fn every_warp_style_has_a_grid_that_keeps_its_shape() { + for style in STYLES { + for (bend, h) in [(50.0, 0.0), (100.0, 0.0), (-100.0, 60.0)] { + let n = warp_node(style, bend, h, crate::live::WARP_NET); + let grid = warp_grid(&n).unwrap_or_else(|| panic!("{style} {bend} {h}: no grid")); + assert!(WARP_GRIDS.contains(&grid.rows) && grid.rows == grid.cols, "{style}: {}×{}", grid.rows, grid.cols); + let map = EnvelopeMap::of(&n).unwrap(); + let b = map.bounds().unwrap(); + let tol = b.width().hypot(b.height()) * 1e-3; + let k = grid.cols as usize; + for (i, q) in grid.points.iter().enumerate() { + let want = map.at((i % (k + 1)) as f64 / k as f64, (i / (k + 1)) as f64 / k as f64); + assert!(q.p.distance(want) < 1e-9, "{style}: point {i} at {:?}, the warp at {want:?}", q.p); + } + for j in 0..=20 { + for i in 0..=20 { + let (u, v) = (i as f64 / 20.0, j as f64 / 20.0); + let off = mesh_at(&grid, u, v).distance(map.at(u, v)); + assert!(off <= tol, "{style} {bend} {h}: {off} off at ({u}, {v})"); + } + } + let (lines, shown) = envelope_overlay(&n).unwrap(); + assert_eq!(shown.as_ref(), Some(&grid), "{style}"); + assert_eq!(lines, grid.lines(), "{style}"); + } + } + } + + /// A kept warp grid is built again when the content, the warp, the frame or the options change, + /// and is the grid built from scratch otherwise. + #[test] + fn a_kept_warp_grid_follows_changes() { + let n = warp_node("arc", 50.0, 0.0, crate::live::WARP_NET); + let first = warp_grid(&n); + assert!(first.is_some()); + assert_eq!(warp_grid(&n), first); + assert_eq!(build_warp_grid(&n), first); + let changed = |f: &dyn Fn(&mut Node)| { + let mut m = n.clone(); + f(&mut m); + let grid = warp_grid(&m); + assert_eq!(grid, build_warp_grid(&m)); + assert_ne!(grid, first); + }; + changed(&|m| { + if let NodeKind::Envelope { content, .. } = &mut m.kind { + Arc::make_mut(&mut content[0]).transform(Affine::translate((40.0, 0.0)), true); + } + }); + changed(&|m| { + if let NodeKind::Envelope { kind, .. } = &mut m.kind + && let EnvelopeKind::Warp { bend, .. } = &mut **kind + { + *bend = -30.0; + } + }); + changed(&|m| { + if let NodeKind::Envelope { frame, .. } = &mut m.kind { + **frame = Affine::rotate(0.3); + } + }); + changed(&|m| { + if let NodeKind::Envelope { options, .. } = &mut m.kind { + options.bounds_margin = [0.1; 4]; + } + }); + } + + /// The table of kept warp grids stays bounded: full of envelopes that still exist, it drops one + /// entry at a time instead of emptying, and it drops the entries of envelopes that are gone + /// first. + #[test] + fn the_kept_warp_grids_stay_bounded() { + let nodes: Vec = (0..WARP_GRID_KEPT + 10).map(|i| warp_node("arc", (i % 100) as f64, 0.0, crate::live::WARP_NET)).collect(); + for n in &nodes { + assert!(warp_grid(n).is_some()); + } + assert_eq!(WARP_GRIDS_KEPT.with_borrow(|kept| kept.len()), WARP_GRID_KEPT); + // Once the envelopes are gone, their entries are the ones dropped. + drop(nodes); + assert!(warp_grid(&warp_node("arc", 10.0, 0.0, crate::live::WARP_NET)).is_some()); + assert_eq!(WARP_GRIDS_KEPT.with_borrow(|kept| kept.len()), 1); + } + + /// A warp drawn by the old point map that no grid of up to 16×16 patches follows closely + /// enough, content without bounds and other envelopes have no warp grid; the overlay still + /// draws the old warp's lines. While an envelope's contents are edited, it shows no points. + #[test] + fn a_warp_no_grid_follows_has_no_grid_to_edit() { + let n = warp_node("fisheye", 100.0, 0.0, 0); + assert!(warp_grid(&n).is_none()); + let (lines, grid) = envelope_overlay(&n).unwrap(); + assert!(grid.is_none()); + assert!(lines.anchor_count() > 0); + // The same style on its Bézier net has one. + assert!(warp_grid(&warp_node("fisheye", 100.0, 0.0, crate::live::WARP_NET)).is_some()); + let mut empty = warp_node("arc", 50.0, 0.0, crate::live::WARP_NET); + if let NodeKind::Envelope { content, .. } = &mut empty.kind { + content.clear(); + } + assert!(warp_grid(&empty).is_none()); + let mut mesh = warp_node("arc", 50.0, 0.0, crate::live::WARP_NET); + if let NodeKind::Envelope { kind, .. } = &mut mesh.kind { + **kind = EnvelopeKind::Mesh { rows: 1, cols: 1, points: grid_points(Rect::new(0.0, 0.0, 1.0, 1.0), 1, 1), handles: vec![] }; + } + assert!(warp_grid(&mesh).is_none()); + // While the contents are edited, a warp's and a mesh envelope's lines show without points. + for mut n in [warp_node("arc", 50.0, 0.0, crate::live::WARP_NET), mesh] { + if let NodeKind::Envelope { editing, .. } = &mut n.kind { + *editing = true; + } + let (lines, grid) = envelope_overlay(&n).unwrap(); + assert!(grid.is_none() && lines.anchor_count() > 0); + } + } + /// A table that fills up is emptied instead of growing, and what is looked up after that is /// measured again. #[test] diff --git a/crates/doc/src/symbol_nine_slice.rs b/crates/doc/src/symbol_nine_slice.rs index 6949aa86fb..53f84e869c 100644 --- a/crates/doc/src/symbol_nine_slice.rs +++ b/crates/doc/src/symbol_nine_slice.rs @@ -10,9 +10,19 @@ //! The cells are sized along the symbol's own axes, and the instance's rotation, shear, reflection //! and position then apply to them. //! -//! The guides are stored as fractions (0..1) of the symbol's natural size, measured from the left -//! and top edges and from the right and bottom edges, so they survive resizing the art. Stored -//! under [`SYMBOL_NINE_SLICE`] keyed by symbol name; symbols without 9-slice have no entry. +//! A guide may lie outside the art, and the instance still scales, by the slices the art falls in +//! ([the help page](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf), +//! Use 9-slice scaling section). VectorCraft's own rules for that: a guide past an edge of the art +//! cuts the art at that edge, so the outer cell on its side holds no art; with both guides of an +//! axis past opposite edges the art scales as a whole along it; with both past the same edge the +//! art lies in the outer cell at the other edge and keeps its size, from that edge of the instance, +//! or shrinks to the instance's width or height when the instance is smaller than the art. +//! +//! The guides are stored as fractions of the symbol's natural size, measured from the left and top +//! edges and from the right and bottom edges, so they survive resizing the art. A fraction below 0 +//! puts a guide past its own edge, and one above 1 past the opposite edge; each lies within +//! ±[`MAX_GUIDE_FRACTION`], and the two guides of an axis keep their order. Stored under +//! [`SYMBOL_NINE_SLICE`] keyed by symbol name; symbols without 9-slice have no entry. //! //! [`NineSliceMap`] places such an instance's art for the canvas, bounds, Break Link, Expand and //! the exporters ([`Document::place_symbol_art`]). @@ -49,11 +59,16 @@ impl Default for SymbolNineSlice { } } +/// The farthest a guide may lie from its edge, as a fraction of the symbol's width or height, in +/// either direction (VectorCraft's own rule). +pub const MAX_GUIDE_FRACTION: f64 = 16.0; + impl SymbolNineSlice { - /// Guides from `[left, top, right, bottom]`; `None` unless each is finite, within 0..1, and the - /// two on each axis leave a gap between them. + /// Guides from `[left, top, right, bottom]`; `None` unless each is finite and within + /// ±[`MAX_GUIDE_FRACTION`], and the two on each axis leave a gap between them + /// (`left + right < 1`, `top + bottom < 1`). pub fn new(left: f64, top: f64, right: f64, bottom: f64) -> Option { - let ok = |v: f64| v.is_finite() && (0.0..=1.0).contains(&v); + let ok = |v: f64| v.is_finite() && (-MAX_GUIDE_FRACTION..=MAX_GUIDE_FRACTION).contains(&v); (ok(left) && ok(top) && ok(right) && ok(bottom) && left + right < 1.0 && top + bottom < 1.0).then_some(Self { left, top, right, bottom }) } @@ -102,7 +117,8 @@ pub struct EditedNineSlice { } impl EditedNineSlice { - /// Guide `g` as a line across the art's box, from one edge to the other, in the document. + /// Guide `g` as a line across the art's box, from one edge to the other, in the document. A + /// guide outside the art spans the art's height or width beside it. pub fn line(&self, g: NineSliceGuide) -> (Point, Point) { let (b, s) = (self.art, self.guides); let (a, c) = match g { @@ -126,14 +142,17 @@ impl EditedNineSlice { }) } - /// The guides with guide `g` moved across its axis to document point `p`. The guide stays - /// within the art's box, and [`MIN_CENTER_BAND`] short of the opposite guide, or where it is - /// when the guides are already closer than that. A point that is not finite leaves the guides - /// as they are. + /// The guides with guide `g` moved across its axis to document point `p`. The guide may pass + /// either edge of the art, up to [`MAX_GUIDE_FRACTION`] from its own edge, and stops + /// [`MIN_CENTER_BAND`] short of the opposite guide, or where it is when the guides are already + /// closer than that. A point that is not finite, or that gives a fraction that is not, leaves + /// the guides as they are. pub fn moved(&self, g: NineSliceGuide, p: Point) -> SymbolNineSlice { let (b, mut out) = (self.art, self.guides); let q = self.to_doc.inverse() * p; - let fit = |v: f64, other: f64, now: f64| if v.is_finite() { v.clamp(0.0, (1.0 - other - MIN_CENTER_BAND).max(now)) } else { now }; + let fit = |v: f64, other: f64, now: f64| { + if v.is_finite() { v.clamp(-MAX_GUIDE_FRACTION, (1.0 - other - MIN_CENTER_BAND).min(MAX_GUIDE_FRACTION).max(now)) } else { now } + }; match g { NineSliceGuide::Left => out.left = fit((q.x - b.x0) / b.width(), out.right, out.left), NineSliceGuide::Right => out.right = fit((b.x1 - q.x) / b.width(), out.left, out.right), @@ -181,20 +200,27 @@ const MAX_SLICE_DEPTH: u32 = 64; /// One axis of a 9-slice map: the three cells between the cuts and where each one goes. #[derive(Clone, Copy, Debug, PartialEq)] struct AxisMap { - /// The cuts in the art at its natural size: its start, the two guides, its end. + /// The cuts in the art at its natural size: its start, the two guides, its end. A guide + /// outside the art cuts it at the nearer end, so a cell can be empty. src: [f64; 4], /// Where the cuts go. The outer cells keep their length unless the scaled length is shorter - /// than both together; then both shrink in proportion and the middle cell is empty. + /// than both together; then both shrink in proportion and the middle cell is empty. An empty + /// cell's start is where the cell before it ends, so the map stays continuous. dst: [f64; 4], } impl AxisMap { - /// The axis from `lo` to `hi` with guides `near` and `far` (fractions of its length in from - /// each end), scaled by `k` (above 0). + /// The axis from `lo` to `hi` (`lo < hi`) with guides `near` and `far` (fractions of its + /// length in from each end, `near + far < 1`; either may lie past an end), scaled by `k` + /// (above 0). With both guides past the far end the art keeps its length from the scaled + /// start, and with both past the near end it keeps its length up to the scaled end; when the + /// scaled length is shorter than the art, the art shrinks to the scaled length. fn new(lo: f64, hi: f64, near: f64, far: f64, k: f64) -> Self { let len = hi - lo; - let (a, b) = (near * len, far * len); - let src = [lo, lo + a, hi - b, hi]; + let c1 = (lo + near * len).clamp(lo, hi); + let c2 = (hi - far * len).clamp(c1, hi); + let src = [lo, c1, c2, hi]; + let (a, b) = (c1 - lo, hi - c2); let (t0, t3) = (k * lo, k * hi); let room = t3 - t0; let (a, b) = if a + b <= room { @@ -203,9 +229,15 @@ impl AxisMap { let f = (room / (a + b)).max(0.0); (a * f, b * f) }; - let t1 = t0 + a; - let t2 = (t3 - b).max(t1); - Self { src, dst: [t0, t1, t2, t3] } + let dst = if c2 > c1 { + let t1 = t0 + a; + [t0, t1, (t3 - b).max(t1), t3] + } else if a > 0.0 { + [t0, t0 + a, t0 + a, t3] + } else { + [t3 - b, t3 - b, t3 - b, t3] + }; + Self { src, dst } } /// The cell `v` lies in; values outside the art belong to the outer cells. @@ -279,10 +311,11 @@ pub struct NineSliceMap { impl NineSliceMap { /// The map for an instance placed by `xf` that shows art with natural-size transform - /// `natural` and geometric bounds `art` (in symbol space). `None` when the art or the - /// transform is degenerate, or when the instance is at its natural size on both axes (then - /// `xf` places the art as it is). + /// `natural` and geometric bounds `art` (in symbol space). `None` when the guides are not ones + /// [`SymbolNineSlice::new`] accepts, when the art or the transform is degenerate, or when the + /// instance is at its natural size on both axes (then `xf` places the art as it is). pub fn new(guides: SymbolNineSlice, art: Rect, natural: Affine, xf: Affine) -> Option { + let guides = SymbolNineSlice::new(guides.left, guides.top, guides.right, guides.bottom)?; let b = natural.transform_rect_bbox(art); if ![b.x0, b.y0, b.x1, b.y1].into_iter().all(f64::is_finite) || b.width() <= 1e-9 || b.height() <= 1e-9 { return None; @@ -894,6 +927,113 @@ mod tests { assert!(got.iter().all(|b| finite(*b)), "{got:?}"); } + /// Guides may lie outside the art, up to 16 times its size from their edge, as long as the + /// two on each axis keep their order; values that are not finite are refused. + #[test] + fn guides_outside_the_art_are_accepted_in_order_and_within_the_limit() { + let ok = |l, t, r, b| SymbolNineSlice::new(l, t, r, b).is_some(); + assert!(ok(-0.25, 0.25, 0.25, 0.25)); + assert!(ok(1.25, 0.25, -0.5, 0.25), "both past the right edge"); + assert!(ok(0.25, -16.0, 0.25, 16.0) && ok(-16.0, 0.25, -16.0, 0.25)); + assert!(!ok(-16.5, 0.25, 0.25, 0.25) && !ok(0.25, 0.25, 0.25, 17.0)); + assert!(!ok(f64::NAN, 0.25, 0.25, 0.25) && !ok(0.25, f64::INFINITY, 0.25, 0.25) && !ok(0.25, 0.25, f64::NEG_INFINITY, 0.25)); + assert!(!ok(1.2, 0.25, -0.2, 0.25), "the left guide on the right one"); + assert!(!ok(0.25, 0.6, 0.25, 0.6), "crossed"); + let g = SymbolNineSlice::from_value(&json!([-0.25, 1.5, 0.5, -1.0])).unwrap(); + assert_eq!(g, SymbolNineSlice { left: -0.25, top: 1.5, right: 0.5, bottom: -1.0 }); + assert_eq!(SymbolNineSlice::from_value(&g.to_value()), Some(g)); + assert!(SymbolNineSlice::from_value(&json!([-0.25, 0.1, 1.5])).is_none()); + assert!(SymbolNineSlice::from_value(&json!([-20.0, 0.1, 0.5, 0.1])).is_none()); + // Guides built without the check are not used to place art. + let bad = SymbolNineSlice { left: f64::NAN, ..SymbolNineSlice::default() }; + assert!(NineSliceMap::new(bad, Rect::new(0.0, 0.0, 100.0, 100.0), Affine::IDENTITY, Affine::scale(2.0)).is_none()); + // Art without width or height has no map, whatever the guides. + let out = SymbolNineSlice::new(-0.25, 1.25, 0.25, -0.5).unwrap(); + for art in [Rect::new(0.0, 0.0, 0.0, 100.0), Rect::new(0.0, 0.0, 100.0, 0.0)] { + assert!(NineSliceMap::new(out, art, Affine::IDENTITY, Affine::scale(2.0)).is_none(), "{art:?}"); + } + } + + /// At 200 × 150, a left guide 25 % outside the art leaves the art in the center and right + /// columns: the left column holds no art, the center one (0..75) stretches to 0..175 and the + /// right one keeps its 25. Both guides outside on opposite sides scale the art as a whole on + /// that axis; both past the same side keep the art at its size in the outer cell at the other + /// side, from that side of the instance. + #[test] + fn art_scales_by_the_cells_it_falls_in_when_guides_lie_outside_it() { + let xf = Affine::scale_non_uniform(2.0, 1.5); + let d = markers(SymbolNineSlice::new(-0.25, 0.25, 0.25, 0.25)); + let got = boxes(&d, xf); + let k = 175.0 / 75.0; + assert!(near(got[0], Rect::new(0.0, 0.0, 200.0, 150.0)), "{:?}", got[0]); + assert!(near(got[1], Rect::new(0.0, 0.0, 10.0 * k, 10.0)), "the top-left square stretches: {:?}", got[1]); + assert!(near(got[2], Rect::new(190.0, 0.0, 200.0, 10.0)), "the top-right corner keeps its size: {:?}", got[2]); + assert!(near(got[5], Rect::new(45.0 * k, 65.0, 55.0 * k, 85.0)), "{:?}", got[5]); + // Both vertical guides outside, on opposite sides: the art scales as a whole across. + let d = markers(SymbolNineSlice::new(-0.25, 0.25, -1.0, 0.25)); + let got = boxes(&d, xf); + assert!(near(got[1], Rect::new(0.0, 0.0, 20.0, 10.0)) && near(got[2], Rect::new(180.0, 0.0, 200.0, 10.0)), "{got:?}"); + assert!(near(got[5], Rect::new(90.0, 65.0, 110.0, 85.0)), "{:?}", got[5]); + // Both past the right edge: the art keeps its width from the instance's left edge. + let d = markers(SymbolNineSlice::new(1.2, 0.25, -0.5, 0.25)); + let got = boxes(&d, xf); + assert!(near(got[0], Rect::new(0.0, 0.0, 100.0, 150.0)), "{:?}", got[0]); + assert!(near(got[2], Rect::new(90.0, 0.0, 100.0, 10.0)) && near(got[5], Rect::new(45.0, 65.0, 55.0, 85.0)), "{got:?}"); + // Both past the left edge: the art keeps its width up to the instance's right edge. + let d = markers(SymbolNineSlice::new(-0.5, 0.25, 1.2, 0.25)); + let got = boxes(&d, xf); + assert!(near(got[0], Rect::new(100.0, 0.0, 200.0, 150.0)), "{:?}", got[0]); + assert!(near(got[1], Rect::new(100.0, 0.0, 110.0, 10.0)), "{:?}", got[1]); + // The same rules apply to rows: both horizontal guides above the art keep its height up to + // the instance's bottom edge. + let d = markers(SymbolNineSlice::new(0.25, -0.5, 0.25, 1.2)); + let got = boxes(&d, xf); + assert!(near(got[0], Rect::new(0.0, 50.0, 200.0, 150.0)), "{:?}", got[0]); + assert!(near(got[3], Rect::new(0.0, 140.0, 10.0, 150.0)), "{:?}", got[3]); + // Smaller than the art, an art-covered outer cell shrinks in proportion. + let d = markers(SymbolNineSlice::new(1.2, 0.25, -0.5, 0.25)); + let got = boxes(&d, Affine::scale_non_uniform(0.5, 1.5)); + assert!(near(got[0], Rect::new(0.0, 0.0, 50.0, 150.0)) && near(got[1], Rect::new(0.0, 0.0, 5.0, 10.0)), "{got:?}"); + } + + /// With guides outside the art, the map stays finite, never runs backward, and does not jump + /// at the art's edges or at the guides; objects keep to the cells that hold art. + #[test] + fn the_map_with_guides_outside_the_art_is_continuous_and_monotone() { + let cases = [(-0.25, 0.25), (-0.25, -1.0), (1.2, -0.5), (-0.5, 1.2), (0.0, -16.0), (-16.0, 16.0), (0.25, 0.25)]; + for (l, r) in cases { + let d = markers(SymbolNineSlice::new(l, 0.25, r, 0.25)); + for sx in [0.3, 2.0, 1e6] { + let m = d.symbol_slice_map("S", Affine::scale_non_uniform(sx, 1.5)).unwrap(); + let at = |x: f64| m.map_point(Point::new(x, 40.0)).x; + let mut last = f64::NEG_INFINITY; + for i in 0..=1200 { + let x = -10.0 + i as f64 * 0.1; + let v = at(x); + assert!(v.is_finite() && v >= last - 1e-12 * last.abs().max(1.0), "{l} {r} {sx}: {x} → {v} after {last}"); + last = v; + } + for edge in [0.0, 75.0, 100.0] { + let jump = (at(edge + 1e-9) - at(edge - 1e-9)).abs(); + assert!(jump < 1e-6 * sx.max(1.0), "{l} {r} {sx}: a jump of {jump} at {edge}"); + } + } + } + // A gradient bar across the art with the left guide outside is drawn in the two columns + // that hold art, not three. + let mut d = markers(SymbolNineSlice::new(-0.25, 0.25, 0.25, 0.25)); + let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default()))); + let bar = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 40.0, 100.0, 60.0)), Appearance::basic(gradient, Paint::None, 0.0)); + let m = d.symbol_slice_map("S", Affine::scale_non_uniform(2.0, 1.5)).unwrap(); + assert_eq!(m.place(&bar, &d).children().map(Vec::len), Some(2)); + assert_eq!(m.most_placed(&bar, &d), 7); + // With both guides outside on opposite sides, the bar lies in one cell and is moved whole. + let d = markers(SymbolNineSlice::new(-0.25, 0.25, -0.25, 0.25)); + let m = d.symbol_slice_map("S", Affine::scale_non_uniform(2.0, 1.5)).unwrap(); + assert!(matches!(m.place(&bar, &d).kind, NodeKind::Path { .. })); + assert_eq!(m.most_placed(&bar, &d), 1); + } + /// A negative scale reflects the sized cells; a rotation turns them, the corners keeping /// their size along the symbol's own axes. #[test] @@ -1456,27 +1596,37 @@ mod tests { assert!(d.edited_nine_slice().is_none()); } - /// Moving a guide changes that guide alone, follows the pointer across its axis only, stays - /// within the art's box and stops short of the opposite guide. + /// Moving a guide changes that guide alone, follows the pointer across its axis only, may pass + /// either edge of the art up to [`MAX_GUIDE_FRACTION`], and stops short of the opposite guide. #[test] - fn a_moved_guide_stays_in_the_art_and_short_of_the_opposite_guide() { + fn a_moved_guide_passes_the_arts_edges_and_stops_short_of_the_opposite_guide() { let xf = Affine::translate((10.0, 20.0)) * Affine::scale(2.0); let e = editing(Some(SymbolNineSlice::default()), xf).edited_nine_slice().unwrap(); let q = SymbolNineSlice { left: 0.25, top: 0.25, right: 0.25, bottom: 0.25 }; assert_eq!(e.moved(NineSliceGuide::Left, Point::new(30.0, 999.0)), SymbolNineSlice { left: 0.1, ..q }); assert_eq!(e.moved(NineSliceGuide::Bottom, Point::new(-50.0, 180.0)), SymbolNineSlice { bottom: 0.2, ..q }); - assert_eq!(e.moved(NineSliceGuide::Top, Point::new(0.0, -500.0)), SymbolNineSlice { top: 0.0, ..q }); - assert_eq!(e.moved(NineSliceGuide::Right, Point::new(1e6, 0.0)), SymbolNineSlice { right: 0.0, ..q }); + // Past the art's near edges: the art spans 10..210 across and 20..220 down. + assert_eq!(e.moved(NineSliceGuide::Left, Point::new(-40.0, 50.0)), SymbolNineSlice { left: -0.25, ..q }); + assert_eq!(e.moved(NineSliceGuide::Top, Point::new(0.0, -500.0)), SymbolNineSlice { top: -2.6, ..q }); + assert_eq!(e.moved(NineSliceGuide::Right, Point::new(1e6, 0.0)), SymbolNineSlice { right: -MAX_GUIDE_FRACTION, ..q }); + assert_eq!(e.moved(NineSliceGuide::Left, Point::new(-1e300, 0.0)), SymbolNineSlice { left: -MAX_GUIDE_FRACTION, ..q }); let crossed = e.moved(NineSliceGuide::Left, Point::new(200.0, 50.0)); assert!((crossed.left - (0.75 - MIN_CENTER_BAND)).abs() < 1e-12, "{crossed:?}"); assert!(SymbolNineSlice::new(crossed.left, crossed.top, crossed.right, crossed.bottom).is_some()); assert_eq!(e.moved(NineSliceGuide::Top, Point::new(f64::NAN, f64::NAN)), q); + assert_eq!(e.moved(NineSliceGuide::Top, Point::new(0.0, f64::INFINITY)), q); + // With the right guide past the art's right edge, the left one may pass that edge too. + let wide = SymbolNineSlice { right: -0.5, ..q }; + let e = editing(Some(wide), xf).edited_nine_slice().unwrap(); + assert_eq!(e.moved(NineSliceGuide::Left, Point::new(260.0, 50.0)), SymbolNineSlice { left: 1.25, ..wide }); + assert!(near_point(e.line(NineSliceGuide::Right).0, Point::new(310.0, 20.0))); + assert!(near_point(e.line(NineSliceGuide::Right).1, Point::new(310.0, 220.0))); // Saved guides closer than the minimum center band keep their place when a drag does not // move them closer. let narrow = SymbolNineSlice::new(0.00005, 0.25, 0.9999, 0.25).unwrap(); let e = editing(Some(narrow), xf).edited_nine_slice().unwrap(); assert_eq!(e.moved(NineSliceGuide::Left, Point::new(200.0, 50.0)), narrow); - assert_eq!(e.moved(NineSliceGuide::Left, Point::new(0.0, 50.0)), SymbolNineSlice { left: 0.0, ..narrow }); + assert_eq!(e.moved(NineSliceGuide::Left, Point::new(0.0, 50.0)), SymbolNineSlice { left: -0.05, ..narrow }); // A mirrored placement measures along the symbol's own axes. let e = editing(Some(SymbolNineSlice::default()), Affine::scale_non_uniform(-1.0, 1.0)).edited_nine_slice().unwrap(); assert!(near_point(e.line(NineSliceGuide::Left).0, Point::new(-25.0, 0.0))); diff --git a/crates/doc/tests/warp_grid_type_ink.rs b/crates/doc/tests/warp_grid_type_ink.rs new file mode 100644 index 0000000000..ae000a3f6a --- /dev/null +++ b/crates/doc/tests/warp_grid_type_ink.rs @@ -0,0 +1,49 @@ +//! A warp grid kept before type's measure is registered is built again once it is, even when the +//! registered inputs number is 0. One test in its own process, so nothing has registered the +//! measure before it runs. +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::sync::Arc; + +use vectorcraft_doc::live::{EnvelopeOptions, set_type_ink, warp_grid}; +use vectorcraft_doc::{CharStyle, EnvelopeKind, Node, NodeId, NodeKind, TextObject}; +use vectorcraft_geom::{Affine, Point, Rect}; + +/// A measure that gives every type the same box, well away from its laid-out box. +fn fixed_ink(_: &TextObject, _: Affine, _: Option<(vectorcraft_geom::Homography, Affine)>) -> Option { + Some(Rect::new(0.0, 0.0, 400.0, 300.0)) +} + +fn no_inputs() -> u64 { + 0 +} + +/// An arc warp around `t`, its content in a new `Arc`. +fn warp_of(t: &TextObject) -> Node { + let content = Arc::new(Node::new(NodeId(1), NodeKind::Text(Box::new(t.clone())))); + let kind = EnvelopeKind::Warp { style: "arc".into(), bend: 50.0, h: 0.0, v: 0.0, horizontal: true, version: 1 }; + Node::new( + NodeId(2), + NodeKind::Envelope { + content: vec![content], + kind: Box::new(kind), + fidelity: 50.0, + editing: false, + options: EnvelopeOptions::NEW, + frame: Box::new(Affine::IDENTITY), + }, + ) +} + +#[test] +fn a_warp_grid_kept_before_the_type_measure_is_built_again() { + let t = TextObject::point(Point::new(100.0, 100.0), "Type", CharStyle::default()); + let n = warp_of(&t); + let before = warp_grid(&n); + set_type_ink(fixed_ink, no_inputs); + let fresh = warp_grid(&warp_of(&t)); + assert!(fresh.is_some()); + assert_ne!(fresh, before, "the registered measure moves the grid"); + assert_eq!(warp_grid(&n), fresh, "the grid kept from before the registration is built again"); +} diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index eb227300e0..e9d64864d0 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -1351,7 +1351,7 @@ mod tests { group.appearance = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0).into(); for id in [REVOLVE, crate::EXTRUDE] { assert!(crate::validate_three_d(&group, id, &json!({})).is_ok(), "{id} on the group itself"); - let refused = crate::validate_three_d_at(&group, id, &json!({}), Some((0, 0))).unwrap_err(); + let refused = crate::validate_three_d_at(&group, id, &json!({}), (Some(0), 0)).unwrap_err(); assert!(refused.contains("on the group itself"), "{id}: {refused}"); } } diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 91f73049f1..52739983a5 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -6,7 +6,7 @@ use serde_json::Value; use vectorcraft_doc::color::{BlendMode, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId, NodeKind, OpacityMask, StrokeLayer}; use vectorcraft_geom::{FillRule, PathData, Rect}; -use vectorcraft_three_d::{Bevel, BevelShape, Extrude, Facet, Inflate, Mesh, PlanarFace, View}; +use vectorcraft_three_d::{Bevel, BevelShape, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, PlanarFace, View}; #[cfg(test)] use vectorcraft_doc::color::Color; @@ -250,36 +250,64 @@ pub fn validate_solid(n: &Node, id: &str, p: &Value) -> Result<(), String> { /// [`validate_solid`] with the symbols of `doc`: a symbol instance, a blend and a clipping group /// build from the art they show ([`resolve`]). pub fn validate_solid_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) -> Result<(), String> { - validate_solid_for(doc, n, id, p, None) + validate_solid_for(doc, n, id, p, (None, None)) } -/// [`validate_solid_in`] for the effect on the object (`item` `None`) or on its appearance item -/// `item`, whose shadow is cast by that item's solid alone. -fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, item: Option) -> Result<(), String> { +/// [`validate_solid_in`] for the effect at `(item, index)`: index `index` of the effects of the +/// object (`item` `None`) or of its appearance item `item`, whose shadow is cast by that item's +/// solid alone. The index is the effects' length for a new effect. The solids are checked as +/// [`solid_art_in`] draws them: from the shapes after the geometry effects before the 3D effect. +/// On the object (or group) with `index` `None`, that effect is its first visible Extrude & Bevel, +/// Inflate or Rotate, as drawn, or a new one after its other effects when it has none. +fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: (Option, Option)) -> Result<(), String> { validate_solid_params(id, p)?; if let Some(doc) = doc { graphics::validate_symbols(doc, p)?; } let label = label_of(id); let n = &*source::resolve_for(doc, n, label, is_plane(id))?; + let effects = &n.appearance.effects; + let index = match at { + (None, Some(index)) => index, + _ => solid(effects).map_or(effects.len(), |(index, _)| index), + }; + let before = effects.get(..index).unwrap_or(effects); if is_container(n) { - let shapes = members(n, label)?; + let mut shapes = members(n, label)?; + reshape_members(n, before, &mut shapes); let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?; shapes.iter().try_for_each(|s| facets(id, &s.path, s.rule, b, p).map(|_| ()))?; + check_solids(id, p, &shapes)?; return cast_shadow(id, p, &shapes).map(|_| ()); } let (path, rule) = object_profile(n, label)?; - let b = path.bounds().ok_or_else(|| format!("{label} requires a shape with at least two anchors"))?; - facets(id, &path, rule, b, p)?; + let anchors = || format!("{label} requires a shape with at least two anchors"); + path.bounds().ok_or_else(anchors)?; + let ctx = GeomContext::of(n); // With its shadow on, the shadow of the object's solids (or of the item's) must fit too. - let items = match item.and_then(|i| n.appearance.items.get(i)) { - Some(item) => vec![item.clone()], - None => solid_paints(n), + let (path, items) = match at.0.and_then(|i| Some((n.appearance.items.get(i)?, at.1.unwrap_or(usize::MAX)))) { + Some((item, index)) => { + let path = geometry(&path, effects, &ctx); + (geometry(&path, item.effects().get(..index).unwrap_or(item.effects()), &ctx.item(item)), vec![item.clone()]) + } + None => (geometry(&path, before, &ctx), solid_paints(n)), }; + let b = path.bounds().ok_or_else(anchors)?; + facets(id, &path, rule, b, p)?; let shapes = [Profile { path, rule, items, opacity: 1.0, scopes: vec![] }]; + check_solids(id, p, &shapes)?; cast_shadow(id, p, &shapes).map(|_| ()) } +/// Do the solids 3D effect `id` with parameters `p` builds from the fills and strokes of `shapes` +/// fit, each on its own and all of them together ([`built_solids`])? Rotate's planes are not +/// counted. +fn check_solids(id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> { + let Some(b) = union_bounds(shapes).filter(|_| !is_plane(id)) else { return Ok(()) }; + let (parts, bounds) = solid_parts(shapes, b); + built_solids(id, p, &parts, bounds, MAX_OBJECT_FACES).try_for_each(|r| r.map(|_| ())) +} + /// [`profile`], or the error a command reports for object `n`: type with no outlines to build from /// (empty, or only spaces) is a shape without anchors, an image is traced first, and any other /// object is the wrong kind. @@ -457,26 +485,28 @@ pub fn validate_three_d_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value if crate::revolve::is_revolve(id) { crate::revolve::validate_in(doc, n, id, p) } else { validate_solid_in(doc, n, id, p) } } -/// [`validate_three_d`] for an effect at `(item, index)`, index `index` of the effects of -/// appearance item `item` of `n` (the effects' length for a new effect), or on the object itself -/// when `at` is `None`. A Revolve on a fill or stroke is checked in that item's paint, after the -/// item's geometry effects before it, together with the object's other items that carry a Revolve. -/// A group's or layer's fills and strokes take no 3D effect: only the group's own effect draws. -pub fn validate_three_d_at(n: &Node, id: &str, p: &Value, at: Option<(usize, usize)>) -> Result<(), String> { +/// [`validate_three_d`] for an effect at `(item, index)`: index `index` of the effects of +/// appearance item `item` of `n`, or of the object itself when `item` is `None` (the effects' +/// length for a new effect). An Extrude & Bevel, Inflate or Rotate is checked on the shapes after +/// the geometry effects before that index. A Revolve on a fill or stroke is checked in that item's +/// paint, after the item's geometry effects before it, together with the object's other items that +/// carry a Revolve. A group's or layer's fills and strokes take no 3D effect: only the group's own +/// effect draws. +pub fn validate_three_d_at(n: &Node, id: &str, p: &Value, at: (Option, usize)) -> Result<(), String> { validate_three_d_at_in(None, n, id, p, at) } /// [`validate_three_d_at`] with the symbols of `doc` ([`validate_solid_in`]). A symbol instance, a /// blend and a clipping group take a 3D effect as groups do: on the object itself. -pub fn validate_three_d_at_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: Option<(usize, usize)>) -> Result<(), String> { +pub fn validate_three_d_at_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: (Option, usize)) -> Result<(), String> { graphics::validate(id, p)?; match at { - Some(_) if is_container(n) || source::resolves(n) => { + (Some(_), _) if is_container(n) || source::resolves(n) => { Err("A 3D effect on a group or layer goes on the group itself, not on its fill or stroke".into()) } - Some((item, index)) if crate::revolve::is_revolve(id) => crate::revolve::validate_item_of(n, id, p, item, index), - Some((item, _)) => validate_solid_for(doc, n, id, p, Some(item)), - None => validate_three_d_in(doc, n, id, p), + (Some(item), index) if crate::revolve::is_revolve(id) => crate::revolve::validate_item_of(n, id, p, item, index), + (None, _) if crate::revolve::is_revolve(id) => crate::revolve::validate_in(doc, n, id, p), + (item, index) => validate_solid_for(doc, n, id, p, (item, Some(index))), } } @@ -596,6 +626,55 @@ fn solid_parts(shapes: &[Profile], fallback: Rect) -> (Vec>, Rect) { (parts, bounds) } +#[cfg(test)] +thread_local! { + /// How many solids [`built_solids`] has built on this thread, for the tests. + static SOLIDS_BUILT: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The solids Extrude & Bevel (Classic included) or Inflate `id` with parameters `p` builds from +/// `parts` ([`solid_parts`]) about `bounds`, one result for each part in order, each built only as +/// the iterator reaches it. A stroke's solid past its own limits is `None` (left out of the art, its +/// faces not counted); a fill's is an error. The faces of the solids kept count together: once they +/// pass `limit` ([`MAX_OBJECT_FACES`] for the art) the result is an error, and +/// no later part is built. An error ends the iterator. +fn built_solids<'a>( + id: &'a str, + p: &'a Value, + parts: &'a [Part<'a>], + bounds: Rect, + limit: usize, +) -> impl Iterator>, String>> + 'a { + // Inflate's eye is placed for every puff together, as far away as the highest needs. + let mut inflated = (id == INFLATE).then(|| { + let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect(); + vectorcraft_three_d::inflate_each(&shapes, bounds, inflate_options(p), view_options(p)) + }); + let mut kept = 0usize; + let mut ended = false; + parts.iter().map_while(move |(item, _, area, rule, _, _)| { + if ended { + return None; + } + #[cfg(test)] + SOLIDS_BUILT.with(|n| n.set(n.get() + 1)); + let built = match inflated.as_mut() { + Some(each) => each.next().unwrap_or_else(|| Ok(vec![])), + None => facets(id, area, *rule, bounds, p), + }; + let result = match built { + Ok(f) => { + kept = kept.saturating_add(f.len()); + if kept > limit { Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string()) } else { Ok(Some(f)) } + } + Err(_) if matches!(item, AppearanceItem::Stroke(_)) => Ok(None), + Err(e) => Err(e), + }; + ended = result.is_err(); + Some(result) + }) +} + /// What a face of one of the solids [`art_for`] draws in one order was built from: the facet's /// depth, whether it is a side face and whether it is turned away from the viewer, the bounds of /// its polygon, the index of its shape, and whether its solid is that shape's fill or one of its @@ -983,24 +1062,19 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile return Some(if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() }); } let (parts, bounds) = solid_parts(shapes, b); - let built = if fx.id == INFLATE { - // One eye for every puff, as far away as the highest needs. - let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect(); - vectorcraft_three_d::inflate_together(&shapes, bounds, inflate_options(&p), view_options(&p)) - } else { - parts.iter().map(|(_, _, area, rule, _, _)| facets(&fx.id, area, *rule, bounds, &p)).collect() - }; let mut solids = vec![]; - for ((item, opacity, _, _, scopes, member), f) in parts.iter().zip(built) { + for ((item, opacity, _, _, scopes, member), f) in parts.iter().zip(built_solids(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES)) { let item: &AppearanceItem = item; match f { - Ok(f) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => return None, - Ok(f) => solids.push((item, *opacity, *scopes, f, *member)), + Ok(Some(f)) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => { + return None; + } + Ok(Some(f)) => solids.push((item, *opacity, *scopes, f, *member)), // A stroke's outline past the limits is left out; the fill's solid still draws. - Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {} - // A loaded file or a shape edited past the limits keeps drawing its source path - // instead of failing the frame; commands validate the same evaluator and report its - // errors. + Ok(None) => {} + // A loaded file or a shape edited past the limits (its own, or those of the object's + // solids together) keeps drawing its source path instead of failing the frame; + // commands validate the same evaluator and report its errors. Err(_) => return None, } } @@ -1374,15 +1448,26 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize) return Ok(out); } let (parts, bounds) = solid_parts(shapes, b); + // The solids the art draws, past the limits of the object's solids together as it is + // ([`built_solids`]), each built and its faces counted as the loop reaches it, then dropped. + let drawn = built_solids(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES).map(|r| r.map(|f| f.is_some())); // Inflate lays out every puff at once (they share one eye); each Inflate and Extrude & Bevel // solid and its mesh are built as the loop reaches them. let mut inflated = (fx.id == INFLATE).then(|| { let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect(); vectorcraft_three_d::inflate_meshes(&shapes, bounds, inflate_options(&p), view) }); - let extrude = extrude_options(&p); - for (item, member, area, rule, _, _) in &parts { + let extrude = if fx.id == CLASSIC_EXTRUDE { classic_extrude_options(&p) } else { extrude_options(&p) }; + for ((item, member, area, rule, _, _), drawn) in parts.iter().zip(drawn) { let item: &AppearanceItem = item; + if !drawn? { + // A stroke the art leaves out is left out of the meshes too; Inflate's next puff + // still belongs to the next part. + if let Some(built) = inflated.as_mut() { + built.next(); + } + continue; + } let mesh = match inflated.as_mut() { Some(built) => built.next().unwrap_or_else(|| Ok(Mesh::default())), None => vectorcraft_three_d::extrude_mesh(area, *rule, bounds, extrude, view), diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index 5041f01bb2..b4e012f977 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -353,6 +353,142 @@ fn a_stroke_past_the_limits_is_left_out() { } } +/// Each solid [`built_solids`] gives for effect `id` on `n` within `limit` faces together, as its +/// face count (`None` for a stroke left out) or the error, every result the iterator gives. +fn solid_faces(id: &str, n: &Node, limit: usize) -> Vec, String>> { + let shapes = [Profile { path: profile(n).unwrap().0, rule: FillRule::NonZero, items: solid_paints(n), opacity: 1.0, scopes: vec![] }]; + let p = crate::merged_params(id, &json!({})); + let (parts, bounds) = solid_parts(&shapes, union_bounds(&shapes).unwrap()); + built_solids(id, &p, &parts, bounds, limit).map(|r| r.map(|f| f.map(|f| f.len()))).collect() +} + +/// The solids of one object count their faces together: at the limit they all build, one face past +/// it is an error, and the solids after the one that passes it are never built. +#[test] +fn an_objects_solids_count_their_faces_together() { + for id in [EXTRUDE, CLASSIC_EXTRUDE, INFLATE] { + let mut n = square_node(); + // A second stroke, so a solid follows the one that passes the limit. + let stroke = n.appearance.items[1].clone(); + n.appearance.items.push(stroke); + let counts: Vec = solid_faces(id, &n, MAX_OBJECT_FACES).into_iter().map(|c| c.unwrap().unwrap()).collect(); + assert!(counts.len() == 3 && counts.iter().all(|c| *c > 0), "{id}: {counts:?}"); + let total: usize = counts.iter().sum(); + assert!(solid_faces(id, &n, total).iter().all(Result::is_ok), "{id}: at the limit"); + let past = solid_faces(id, &n, total - 1); + assert_eq!(past.last(), Some(&Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string())), "{id}"); + SOLIDS_BUILT.with(|b| b.set(0)); + let past = solid_faces(id, &n, counts[0] + counts[1] - 1); + assert!(past.len() == 2 && past[1].is_err(), "{id}: {past:?}"); + assert_eq!(SOLIDS_BUILT.with(std::cell::Cell::get), 2, "{id}: the second stroke's solid is never built"); + } +} + +/// A convex polygon of `corners` corners about (20,000, 20,000), filled red, with no stroke. +fn polygon_node(id: u64, corners: usize) -> Node { + let points: Vec = (0..corners) + .map(|k| { + let (s, c) = (k as f64 * std::f64::consts::TAU / corners as f64).sin_cos(); + Point::new(20_000.0 + 10_000.0 * c, 20_000.0 + 10_000.0 * s) + }) + .collect(); + let path = PathData::single(vectorcraft_geom::SubPath::polyline(&points, true)); + Node::path(NodeId(id), path, Appearance::basic(Paint::solid(RED), Paint::None, 0.0)) +} + +/// A group whose members' solids each fit, but not all of them together, draws its source art, and +/// the commands that check the effect report the error, as do its mesh and its wireframe; one +/// member fewer, within the limit, draws. +#[test] +fn a_groups_solids_together_past_the_limit_draw_the_source() { + let member = polygon_node(1, 16_384); + let mut alone = member.clone(); + alone.appearance.effects.push(fx(EXTRUDE, json!({}))); + let [Ok(Some(each))] = solid_faces(EXTRUDE, &alone, MAX_OBJECT_FACES)[..] else { panic!("one solid") }; + // Members stacked in one place each build the same solid. + let fits = MAX_OBJECT_FACES / each; + let group = |count: usize| { + let members = (0..count) + .map(|k| { + let mut m = member.clone(); + m.id = NodeId(k as u64 + 1); + Arc::new(m) + }) + .collect(); + let mut g = Node::group(NodeId(9999), members); + g.appearance.effects.push(fx(EXTRUDE, json!({}))); + g + }; + let within = group(fits); + assert!(validate_solid(&within, EXTRUDE, &json!({})).is_ok(), "{fits} × {each} faces"); + assert!(solid_art(&within).is_some()); + let past = group(fits + 1); + assert_eq!(validate_solid(&past, EXTRUDE, &json!({})), Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string())); + assert!(solid_art(&past).is_none(), "the source art draws"); + assert_eq!(three_d_meshes(&past), Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string())); + assert_eq!(three_d_wireframe_in(None, &past), Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string())); +} + +/// A fill and strokes whose solids each fit, but not all of them together, draw the source art, +/// and the strokes after the one past the limit are not left out to make room. +#[test] +fn a_fill_and_strokes_together_past_the_limit_draw_the_source() { + let mut n = polygon_node(1, 16_384); + n.appearance.effects.push(fx(EXTRUDE, json!({}))); + let stroke = AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(BLUE), 20.0)); + n.appearance.items.push(stroke.clone()); + // Strokes alike each build the same solid. + let [Ok(Some(fill)), Ok(Some(each))] = solid_faces(EXTRUDE, &n, MAX_OBJECT_FACES)[..] else { panic!("a fill's solid and a stroke's") }; + let fits = (MAX_OBJECT_FACES - fill) / each; + assert!(fits >= 2, "{fill} + {fits} × {each}"); + n.appearance.items.extend(std::iter::repeat_n(stroke, fits - 1)); + assert!(validate_solid(&n, EXTRUDE, &json!({})).is_ok(), "{fill} + {fits} × {each}"); + let art = solid_art(&n).unwrap(); + assert!(faces(&art).iter().any(|f| blue(f))); + n.appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(BLUE), 20.0))); + assert_eq!(validate_solid(&n, EXTRUDE, &json!({})), Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string())); + assert!(solid_art(&n).is_none(), "the source art draws"); +} + +/// The check builds the solids from the shapes the art draws them from: after the geometry effects +/// before the 3D effect, on an object, on its fill and on a group. Copies a Transform effect before +/// it makes that take the solids past the limit fail the check, as the art then draws the source. +#[test] +fn the_check_counts_the_faces_after_the_geometry_effects_before() { + let mut alone = polygon_node(1, 16_384); + alone.appearance.effects.push(fx(EXTRUDE, json!({}))); + let [Ok(Some(each))] = solid_faces(EXTRUDE, &alone, MAX_OBJECT_FACES)[..] else { panic!("one solid") }; + // Side by side, each copy builds the same solid. + let copies = |k: usize| fx("distort.transform", json!({"moveH": 30_000.0, "copies": k})); + for (k, fits) in [(1, true), (MAX_OBJECT_FACES / each, false)] { + let mut n = polygon_node(1, 16_384); + n.appearance.effects = vec![copies(k), fx(EXTRUDE, json!({}))]; + assert_eq!(validate_solid(&n, EXTRUDE, &json!({})).is_ok(), fits, "on the object, {k} copies"); + assert_eq!(solid_art(&n).is_some(), fits, "on the object, {k} copies"); + let mut f = polygon_node(1, 16_384); + f.appearance.items[0].effects_mut().extend([copies(k), fx(EXTRUDE, json!({}))]); + assert_eq!(validate_three_d_at(&f, EXTRUDE, &json!({}), (Some(0), 1)).is_ok(), fits, "on the fill, {k} copies"); + assert_eq!(solid_art(&f).is_some(), fits, "on the fill, {k} copies"); + let mut g = Node::group(NodeId(9999), vec![Arc::new(polygon_node(1, 16_384))]); + g.appearance.effects = vec![copies(k), fx(EXTRUDE, json!({}))]; + assert_eq!(validate_solid(&g, EXTRUDE, &json!({})).is_ok(), fits, "on a group, {k} copies"); + assert_eq!(solid_art(&g).is_some(), fits, "on a group, {k} copies"); + // A new effect goes after the copies. + let mut new = polygon_node(1, 16_384); + new.appearance.effects = vec![copies(k)]; + assert_eq!(validate_three_d_at(&new, EXTRUDE, &json!({}), (None, 1)).is_ok(), fits, "a new effect, {k} copies"); + } + // A hidden effect checked at its own index counts only the effects before it: copies after it + // copy the drawn art once it is shown again. + let mut hidden = polygon_node(1, 16_384); + let mut extrude = fx(EXTRUDE, json!({})); + extrude.visible = false; + hidden.appearance.effects = vec![extrude, copies(MAX_OBJECT_FACES / each)]; + assert!(validate_three_d_at(&hidden, EXTRUDE, &json!({}), (None, 0)).is_ok()); + hidden.appearance.effects[0].visible = true; + assert!(solid_art(&hidden).is_some()); +} + /// At no volume Inflate's front is flat: turned, the fill's cells are all drawn before the stroke's, /// whatever their depths, as the extrusion's caps are. When the fill puffs, a stroke too narrow to /// puff on the grid stays flat and keeps its depths: the fill's puff is drawn over its far side. diff --git a/crates/effects/src/solids/tests_mesh.rs b/crates/effects/src/solids/tests_mesh.rs index 1ae347c978..aeefafbc77 100644 --- a/crates/effects/src/solids/tests_mesh.rs +++ b/crates/effects/src/solids/tests_mesh.rs @@ -59,6 +59,20 @@ fn the_meshes_of_one_object_share_one_triangle_budget() { assert!(meshes_for(effect, &shapes, &mut total, MAX_MESH_TRIANGLES).is_err_and(|e| e.contains("too complex"))); } +/// A mesh past the budget stops the export before the solids after it are built. +#[test] +fn the_solids_after_a_mesh_past_the_budget_are_not_built() { + let mut n = square_node(1, 100.0); + n.appearance.effects.push(fx(EXTRUDE, json!({}))); + let first = three_d_meshes(&n).unwrap()[0].mesh.triangles.len(); + let shapes = [Profile { path: profile(&n).unwrap().0, rule: FillRule::NonZero, items: solid_paints(&n), opacity: 1.0, scopes: vec![] }]; + let Some(effect) = n.appearance.effects.first() else { panic!("no effect") }; + let mut total = MAX_MESH_TRIANGLES - first + 1; + SOLIDS_BUILT.with(|b| b.set(0)); + assert!(meshes_for(effect, &shapes, &mut total, MAX_MESH_TRIANGLES).is_err_and(|e| e.contains("too complex"))); + assert_eq!(SOLIDS_BUILT.with(std::cell::Cell::get), 1, "the stroke's solid is never built"); +} + #[test] fn revolve_stops_at_the_first_mesh_past_the_budget() { // The fill revolves into a mesh; the stroke's profile, copied 1000 times, is too complex to @@ -109,6 +123,22 @@ fn an_extruded_mesh_is_as_deep_as_the_effect() { assert!((hi[2] - lo[2] - 30.0).abs() < 1e-9 && (hi[0] - lo[0] - 100.0).abs() < 1e-9, "{lo:?} {hi:?}"); } +/// Extrude & Bevel (Classic) exports the solid it draws: its bevel as wide as it is high. +#[test] +fn a_classic_extrusion_exports_its_own_bevel() { + let mut n = square_node(1, 100.0); + n.appearance.items.truncate(1); + let params = json!({ "bevel": "classic", "bevelHeight": 10.0 }); + n.appearance.effects.push(fx(CLASSIC_EXTRUDE, params.clone())); + let meshes = three_d_meshes(&n).unwrap(); + let p = crate::merged_params(CLASSIC_EXTRUDE, ¶ms); + let path = profile(&n).unwrap().0; + let bounds = path.bounds().unwrap(); + let own = vectorcraft_three_d::extrude_mesh(&path, FillRule::NonZero, bounds, classic_extrude_options(&p), view_options(&p)).unwrap(); + assert_eq!(meshes.len(), 1); + assert_eq!(meshes[0].mesh, own); +} + #[test] fn revolve_gives_a_mesh_in_the_top_fill() { let mut b = BezPath::new(); diff --git a/crates/effects/src/solids/wireframe.rs b/crates/effects/src/solids/wireframe.rs index f1dc324679..00e741bfe6 100644 --- a/crates/effects/src/solids/wireframe.rs +++ b/crates/effects/src/solids/wireframe.rs @@ -4,13 +4,13 @@ use std::collections::{HashMap, HashSet, VecDeque}; use std::sync::Arc; use vectorcraft_doc::color::{Color, Paint}; -use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId}; +use vectorcraft_doc::{Appearance, Document, Effect, Node, NodeId}; use vectorcraft_geom::{Anchor, CubicBez, PathData, Point, SubPath}; use vectorcraft_three_d::Facet; use super::{ - INFLATE, Profile, ROTATE, facets, geometry, has_solid, inflate_options, is_container, is_plane, is_three_d, label_of, members, object_profile, - region, reshape_members, resolve, resolve_for, solid, solid_paints, solid_parts, union_bounds, view_options, + Profile, ROTATE, built_solids, facets, geometry, has_solid, is_container, is_plane, is_three_d, label_of, members, object_profile, region, + reshape_members, resolve, resolve_for, solid, solid_paints, solid_parts, union_bounds, }; use crate::{GeomContext, is_geometry}; @@ -125,7 +125,8 @@ fn solid_face_paths(doc: Option<&Document>, n: &Node) -> Result, S /// The outlines of the facets effect `fx` builds from `shapes`, as `art_for` builds them: Rotate and /// Rotate (Classic) turn every fill and stroke; Extrude & Bevel and Inflate build a solid from each shape's /// top fill and from the outline of each stroke. A stroke whose solid is past the limits is left out, -/// as it is left out of the drawn art. +/// as it is left out of the drawn art; past the limits of the object's solids together, the result +/// is an error, as the canvas draws the source art. fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result, String> { let label = label_of(&fx.id); let b = union_bounds(shapes).ok_or_else(|| format!("{label} requires a shape with at least two anchors"))?; @@ -141,18 +142,9 @@ fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result, String> return Ok(out); } let (parts, bounds) = solid_parts(shapes, b); - let built: Vec, String>> = if fx.id == INFLATE { - let shapes: Vec<(&PathData, vectorcraft_geom::FillRule)> = parts.iter().map(|(_, _, area, rule, ..)| (area, *rule)).collect(); - vectorcraft_three_d::inflate_together(&shapes, bounds, inflate_options(&p), view_options(&p)) - } else { - parts.iter().map(|(_, _, area, rule, ..)| facets(&fx.id, area, *rule, bounds, &p)).collect() - }; - for ((item, ..), f) in parts.iter().zip(built) { - match f { - Ok(f) => out.extend(f.iter().map(Facet::path)), - Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {} - Err(e) => return Err(e), - } + // The solids the art draws, each past the limits of the object's solids together as it is. + for f in built_solids(&fx.id, &p, &parts, bounds, vectorcraft_three_d::MAX_OBJECT_FACES) { + out.extend(f?.iter().flatten().map(Facet::path)); } Ok(out) } diff --git a/crates/effects/src/solids/wireframe/tests.rs b/crates/effects/src/solids/wireframe/tests.rs index 5ea4423ab3..792fbdb28a 100644 --- a/crates/effects/src/solids/wireframe/tests.rs +++ b/crates/effects/src/solids/wireframe/tests.rs @@ -1,6 +1,6 @@ use serde_json::{Value, json}; use vectorcraft_doc::color::{Color, Paint}; -use vectorcraft_doc::{Appearance, Node, NodeId}; +use vectorcraft_doc::{Appearance, AppearanceItem, Node, NodeId}; use vectorcraft_geom::{BezPath, Rect}; use super::*; diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 347968b2c5..50c63b59cd 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -199,7 +199,7 @@ pub fn specs() -> Vec { "New Symbol…", [], None, - "{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions 0..1 of the natural size (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions → {name, id, registration, exportType, nineSlice, type}", + "{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions → {name, id, registration, exportType, nineSlice, type}", has_selection, symbol_new ), @@ -208,7 +208,7 @@ pub fn specs() -> Vec { "Symbol Options…", [], None, - "{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic} rename a symbol (its instances and the graphics mapped onto 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions 0..1) and Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes); default name: current → {name, registration, exportType, nineSlice, type}", + "{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic} rename a symbol (its instances and the graphics mapped onto 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1) and Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes); default name: current → {name, registration, exportType, nineSlice, type}", has_doc, symbol_options ), diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index edd2335f6a..2fb31c5f6b 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -47,21 +47,20 @@ fn export_type_param(p: &Value, cmd: &str) -> Result> { } /// `nineSlice` (bool) and `nineSliceGuides` ([left, top, right, bottom] fractions of the natural -/// size): `None` leaves the symbol alone, `Some(None)` turns 9-slice off, `Some(Some(g))` turns it -/// on with guides `g` (the symbol's current ones, else a quarter in from each edge, when none are -/// given). +/// size, below 0 or above 1 for a guide outside the art): `None` leaves the symbol alone, +/// `Some(None)` turns 9-slice off, `Some(Some(g))` turns it on with guides `g` (the symbol's +/// current ones, else a quarter in from each edge, when none are given). fn nine_slice_param(p: &Value, cmd: &str, current: Option) -> Result>> { let on = match p.get("nineSlice") { None | Some(Value::Null) => None, Some(v) => Some(v.as_bool().ok_or_else(|| bad(cmd, "nineSlice must be true or false"))?), }; - let guides = - match p.get("nineSliceGuides") { - None | Some(Value::Null) => None, - Some(v) => Some(SymbolNineSlice::from_value(v).ok_or_else(|| { - bad(cmd, "nineSliceGuides must be [left, top, right, bottom], each 0..1, with left + right < 1 and top + bottom < 1") - })?), - }; + let guides = match p.get("nineSliceGuides") { + None | Some(Value::Null) => None, + Some(v) => Some(SymbolNineSlice::from_value(v).ok_or_else(|| { + bad(cmd, "nineSliceGuides must be [left, top, right, bottom], each -16..16, with left + right < 1 and top + bottom < 1") + })?), + }; Ok(match (on, guides) { (Some(false), _) => Some(None), (None, None) => None, diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 3201adfbe6..17fcb63fe2 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -457,9 +457,10 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { for (target, at) in targets.iter().copied().zip(item.per_target(s, &targets)) { let d = &s.doc()?.doc; let n = d.node(target).ok_or(EngineError::NoNode(target))?; - // A new effect goes after the item's others. + // A new effect goes after the item's (or the object's) others. let on = at.and_then(|at| at.effects_item(&n.appearance, C).ok()).flatten(); - let on = on.and_then(|i| Some((i, n.appearance.items.get(i)?.effects().len()))); + let on = on.and_then(|i| Some((Some(i), n.appearance.items.get(i)?.effects().len()))); + let on = on.unwrap_or((None, n.appearance.effects.len())); effects::validate_three_d_at_in(Some(d), n, id, &effect.params, on).map_err(|e| bad(C, e))?; if let Some(name) = effects::missing_symbol(d, &effect.params, None) { return Err(bad(C, format!("no symbol named `{name}`"))); @@ -786,7 +787,7 @@ fn set_params(s: &mut Session, p: &Value) -> Result { return Err(bad(C, format!("no symbol named `{name}`"))); } if visible != Some(false) { - effects::validate_three_d_at_in(Some(d), n, to, &prospective, target.map(|item| (item, index))).map_err(|e| bad(C, e))?; + effects::validate_three_d_at_in(Some(d), n, to, &prospective, (target, index)).map_err(|e| bad(C, e))?; } else { // Hidden, the effect draws nothing, so its object need not fit. The values given are // checked, and after a change of 3D type so is every value it keeps. diff --git a/crates/engine/src/cmd/effectcmd/graphics.rs b/crates/engine/src/cmd/effectcmd/graphics.rs index 1801c83492..3365a1b764 100644 --- a/crates/engine/src/cmd/effectcmd/graphics.rs +++ b/crates/engine/src/cmd/effectcmd/graphics.rs @@ -131,7 +131,7 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result { graphic.scale = frame.fitting_scale(art); } let params = effects::with_graphic(&effects::merged_params(&effect.id, &effect.params), &graphic); - effects::validate_three_d_at_in(Some(d), n, &effect.id, ¶ms, item.map(|i| (i, index))).map_err(|e| bad(C, e))?; + effects::validate_three_d_at_in(Some(d), n, &effect.id, ¶ms, (item, index)).map_err(|e| bad(C, e))?; edits.push((id, item, index, graphic)); } let first = edits.first().map(|(.., g)| g.to_value()); diff --git a/crates/engine/src/cmd/effectcmd/tests.rs b/crates/engine/src/cmd/effectcmd/tests.rs index 8b5f90eb4a..306aaa4797 100644 --- a/crates/engine/src/cmd/effectcmd/tests.rs +++ b/crates/engine/src/cmd/effectcmd/tests.rs @@ -169,6 +169,44 @@ fn solid_effects_apply_to_a_group_and_its_members_stay_editable() { assert_eq!(s.doc().unwrap().doc, before, "nothing changed"); } +/// Extrude & Bevel is refused, and nothing changes, on a path whose fill's and strokes' solids each +/// fit but together pass the limit of their faces; with one stroke the effect applies. +#[test] +fn extrude_is_refused_when_its_solids_together_are_too_complex() { + use vectorcraft_doc::color::{Color, Paint}; + use vectorcraft_doc::{Appearance, AppearanceItem}; + let (mut s, id) = session_with_rect(); + let points: Vec = (0..16_384) + .map(|k| { + let (sin, cos) = (k as f64 * std::f64::consts::TAU / 16_384.0).sin_cos(); + vectorcraft_geom::Point::new(20_000.0 + 10_000.0 * cos, 20_000.0 + 10_000.0 * sin) + }) + .collect(); + let polygon = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&points, true)); + let painted = |strokes: usize| { + let mut items = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0).items; + let stroke = AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::WHITE), 20.0)); + items.extend(std::iter::repeat_n(stroke, strokes)); + items + }; + let set = |s: &mut Session, strokes: usize| { + let n = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap(); + let NodeKind::Path { path, live, .. } = &mut n.kind else { panic!("a path") }; + *path = polygon.clone(); + *live = None; + n.appearance.items = painted(strokes); + }; + // The fill's solid and each stroke's fit on their own; sixty strokes' together do not. + set(&mut s, 60); + let before = s.doc().unwrap().doc.clone(); + let err = s.execute("effect.apply", &json!({"effect": "threeD.extrude", "ids": [id.0], "item": null})).unwrap_err().to_string(); + assert!(err.contains("The 3D surface is too complex; simplify the shape"), "{err}"); + assert_eq!(s.doc().unwrap().doc, before, "nothing changed"); + set(&mut s, 1); + s.execute("effect.apply", &json!({"effect": "threeD.extrude", "ids": [id.0], "item": null})).unwrap(); + assert!(effects::solid_art(&node(&s, id)).is_some()); +} + /// A group of a clipping group (a rectangle clipped by an ellipse) and a rectangle: the session, /// the clipping group and the group. fn group_with_a_clipping_group() -> (Session, NodeId, NodeId) { diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index 0f866c6588..fafcc12215 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -424,25 +424,45 @@ fn a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles() { /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n{xa}0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n;\n" ) }; + // Styles of one paint (`/SimpleStyle`): a red 2 pt stroke and no fill, and a gradient fill, + // which isn't read, so it is left out rather than listed with no paint. + let one_paint = |name: &str, paint: &str| format!("/KnownStyle :\n({name}) /Name ,\n/SimpleStyle :\n{paint}/Paint ;\n/Def ;\n"); let styles = format!( - "%AI9_BeginArtStyles\n{}{}{}%AI9_EndArtStyles\n%AI9_BeginArtStyleList\n(Red)\n(Green)\n(Blue)\n%AI9_EndArtStyleList\n", + "%AI9_BeginArtStyles\n{}{}{}{}{}%AI9_EndArtStyles\n\ + %AI9_BeginArtStyleList\n(Red)\n(Green)\n(Blue)\n(Red outline)\n(Sky fill)\n%AI9_EndArtStyleList\n", style("Blue", "0 0 0 0 0 0 1 Xa\n"), style("Green", "0 0 0 0 0 1 0 Xa\n"), - style("Red", "0 0 0 0 1 0 0 Xa\n") + style("Red", "0 0 0 0 1 0 0 Xa\n"), + one_paint("Red outline", "0 R\n0 1 1 0 K\n0 J 0 j 2 w 10 M []0 d\n1 0 Xd\n"), + one_paint("Sky fill", "0 O\n0 Bb\n2 (Sky) 0 0 0 100 1 0 0 1 0 0 Bg\n0 BB\n0 1 Xd\n") ); let data = ai::editing_data(200.0, 100.0, &styles); let file = ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f"); let mut s = Session::new(); let p = json!({"dataBase64": vectorcraft_format::base64_encode(&file), "name": "fills.ai"}); let r = s.execute("graphicStyle.loadLibrary", &p).unwrap(); - assert_eq!((&r["name"], &r["count"]), (&json!("fills"), &json!(3)), "{r}"); - let lib = s.execute("graphicStyle.library", &json!({"library": r["library"]})).unwrap(); + assert_eq!((&r["name"], &r["count"]), (&json!("fills"), &json!(4)), "{r}"); + let library = r["library"].clone(); + let lib = s.execute("graphicStyle.library", &json!({"library": library})).unwrap(); let names: Vec<&str> = lib["styles"].as_array().unwrap().iter().map(|g| g["name"].as_str().unwrap()).collect(); - assert_eq!(names, ["Red", "Green", "Blue"], "{lib}"); + assert_eq!(names, ["Red", "Green", "Blue", "Red outline"], "{lib}"); + // The outline style strokes a rectangle red, 2 pt wide, and leaves it unfilled. + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let id = NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + let r = s.execute("graphicStyle.addFromLibrary", &json!({"library": library, "names": ["Red outline"], "apply": true, "ids": [id.0]})).unwrap(); + assert_eq!(r["added"], json!(["Red outline"]), "{r}"); + let doc = &s.doc().unwrap().doc; + let look = &doc.node(id).unwrap().appearance; + assert!(look.fill().is_none(), "{look:?}"); + let strokes: Vec<_> = look.items.iter().filter(|i| matches!(i, vectorcraft_doc::AppearanceItem::Stroke(_))).collect(); + assert_eq!(strokes.len(), 1, "{look:?}"); + let stroke = look.stroke().unwrap(); + assert_eq!((stroke.paint.color(), stroke.width), (Some(vectorcraft_color::Color::cmyk(0.0, 1.0, 1.0, 0.0)), 2.0), "{look:?}"); + assert_eq!(doc.graphic_style("Red outline").map(|g| &g.appearance), Some(&**look)); let r = open(&mut s, "fills.ai", &file, json!({})).unwrap(); let doc = &s.doc().unwrap().doc; let styles: Vec<(&str, u32)> = doc.graphic_styles.iter().map(|g| (g.name.as_str(), g.id)).collect(); - assert_eq!(styles, [("Red", 1), ("Green", 2), ("Blue", 3)], "{r}"); + assert_eq!(styles, [("Red", 1), ("Green", 2), ("Blue", 3), ("Red outline", 4)], "{r}"); } /// A `.ai` symbol library (symbols and their list, no layers) opens with its symbols, and Other diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 019f9baf73..e3e72861b9 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -629,9 +629,13 @@ fn clip_shape((frame, room): Clip) -> PathData { enum ClipTo { /// It stays as it is. Keep, - /// It is clipped to this path: the clipping path of the clip group holding just it changes, - /// else it goes into a new clip group. + /// It is clipped to this path (Placement Options' clip): the clipping path of the clip group + /// holding just it changes, else it goes into a new clip group. Path(PathData), + /// It is clipped to this path, the clipping path its DCS file draws it through: as [`ClipTo::Path`], + /// except that a plain group holding just it (as [`ClipTo::Off`] leaves one) becomes a clip group + /// again. + File(PathData), /// It goes into a new clip group of this path, inside the clip group that holds it. Nest(PathData), /// The clipping path of the clip group holding just it goes (a DCS file's clipping path that @@ -693,7 +697,7 @@ fn clip_to( match img.clip.as_ref().map(|path| path.transformed(new_xf)) { // A clipping mask made in the document stays, with the file's clip group inside it. Some(path) if held.is_some() && !file_held => ClipTo::Nest(path), - Some(path) => ClipTo::Path(path), + Some(path) => ClipTo::File(path), None if file_held => ClipTo::Off, None => ClipTo::Keep, } @@ -742,7 +746,7 @@ impl Nested<'_> { let mut new = Arc::new(new); self.update(&mut new, true); *n = match clip { - ClipTo::Path(path) | ClipTo::Nest(path) => Arc::new(self.clip_group(new, path)), + ClipTo::Path(path) | ClipTo::File(path) | ClipTo::Nest(path) => Arc::new(self.clip_group(new, path)), ClipTo::Keep | ClipTo::Off => new, }; } @@ -758,12 +762,16 @@ impl Nested<'_> { let mut slots: Vec<(usize, Arc)> = vec![]; // The object a clip group that loses its clipping path holds alone. let mut declipped = None; + // The clipping path and object of a plain group holding just the object, which becomes a + // clip group again. + let mut reclipped = None; if let Some(children) = n.children() { // A clip group holding just the object: its clipping path changes. let clip_path = match (&n.kind, &children[..]) { (NodeKind::Group { clip: true, .. }, [c, _]) if matches!(c.kind, NodeKind::Path { clipping: true, .. }) => Some(c), _ => None, }; + let plain = matches!((&n.kind, &children[..]), (NodeKind::Group { clip: false, .. }, [_])); for (i, c) in children.iter().enumerate() { if !(nested && (self.pick)(c)) { let mut new = Arc::clone(c); @@ -782,14 +790,15 @@ impl Nested<'_> { self.update(&mut new, true); match (clip, clip_path) { (ClipTo::Keep, _) => slots.push((i, new)), - (ClipTo::Path(clip), Some(path)) if i == 1 => { + (ClipTo::Path(clip) | ClipTo::File(clip), Some(path)) if i == 1 => { let mut path = Node::clone(path); if let NodeKind::Path { path: p, .. } = &mut path.kind { *p = clip; } slots.extend([(0, Arc::new(path)), (1, new)]); } - (ClipTo::Path(clip) | ClipTo::Nest(clip), _) => { + (ClipTo::File(clip), None) if plain => reclipped = Some((clip, new)), + (ClipTo::Path(clip) | ClipTo::File(clip) | ClipTo::Nest(clip), _) => { let group = self.clip_group(new, clip); slots.push((i, Arc::new(group))); } @@ -798,13 +807,21 @@ impl Nested<'_> { } } } - if mask.is_none() && slots.is_empty() && declipped.is_none() { + if mask.is_none() && slots.is_empty() && declipped.is_none() && reclipped.is_none() { return; } + let reclipped = reclipped.map(|(clip, object)| (Arc::new(self.clipping_path(clip)), object)); let n = Arc::make_mut(n); if let (Some(art), Some(m)) = (mask, n.extras_if_any().and_then(|e| e.mask.as_mut())) { m.art = art; } + // A plain group of just the object that becomes a clip group again. + if let Some((path, object)) = reclipped { + if let NodeKind::Group { children, clip } = &mut n.kind { + (*children, *clip) = (vec![path, object], true); + } + return; + } // A clip group that stays as a plain group of just the object. if let Some(object) = declipped { if let NodeKind::Group { children, clip } = &mut n.kind { @@ -823,15 +840,18 @@ impl Nested<'_> { /// A clip group of `object` clipped to `clip`, as [`clip_image_to`] makes one in the layers. fn clip_group(&mut self, object: Arc, clip: PathData) -> Node { - let (path_id, group_id) = (NodeId(self.next), NodeId(self.next + 1)); - self.next += 2; - let none = vectorcraft_color::Paint::None; - let mut path = Node::path(path_id, clip, Appearance::basic(none.clone(), none, 0.0)); - if let NodeKind::Path { clipping, .. } = &mut path.kind { - *clipping = true; - } + let path = self.clipping_path(clip); + let group_id = NodeId(self.next); + self.next += 1; Node::new(group_id, NodeKind::Group { children: vec![Arc::new(path), object], clip: true }) } + + /// A clipping path of `clip`, with the next node id. + fn clipping_path(&mut self, clip: PathData) -> Node { + let id = NodeId(self.next); + self.next += 1; + clipping_path(id, clip) + } } /// Placed documents `ids` show `src`, read from the file `link` points at, each placed as its @@ -964,15 +984,41 @@ fn clip_image_to(d: &mut Document, id: NodeId, path: PathData) -> Result<()> { new_clip_group(d, id, path) } +/// Clip object `id` of `d` to `path`, the clipping path its DCS file draws it through: the clipping +/// path of the clip group holding just it changes, a plain group holding just it (as [`unclip`] +/// leaves one) becomes a clip group again, else it goes into a new clip group. +fn clip_file_to(d: &mut Document, id: NodeId, path: PathData) -> Result<()> { + if set_clip_path(d, id, path.clone()) { + return Ok(()); + } + let plain = d.parent_of(id).filter(|g| match d.node(*g).map(|n| &n.kind) { + Some(NodeKind::Group { children, clip: false }) => matches!(&children[..], [o] if o.id == id), + _ => false, + }); + let Some(g) = plain else { return new_clip_group(d, id, path) }; + let clip = clipping_path(d.alloc_id(), path); + d.insert(Some(g), 0, clip)?; + if let Some(Node { kind: NodeKind::Group { clip, .. }, .. }) = d.node_mut(g) { + *clip = true; + } + Ok(()) +} + +/// A clipping path `id` of `path`, unpainted. +fn clipping_path(id: NodeId, path: PathData) -> Node { + let none = vectorcraft_color::Paint::None; + let mut clip = Node::path(id, path, Appearance::basic(none.clone(), none, 0.0)); + if let NodeKind::Path { clipping, .. } = &mut clip.kind { + *clipping = true; + } + clip +} + /// Put object `id` of `d` into a new clip group of `path`, where it is. fn new_clip_group(d: &mut Document, id: NodeId, path: PathData) -> Result<()> { let (par, index, _) = d.position(id).ok_or(EngineError::NoNode(id))?; let image = d.remove(id)?; - let none = vectorcraft_color::Paint::None; - let mut clip = Node::path(d.alloc_id(), path, Appearance::basic(none.clone(), none, 0.0)); - if let NodeKind::Path { clipping, .. } = &mut clip.kind { - *clipping = true; - } + let clip = clipping_path(d.alloc_id(), path); let group = Node::new(d.alloc_id(), NodeKind::Group { children: vec![std::sync::Arc::new(clip), image], clip: true }); d.insert(par, index, group)?; Ok(()) @@ -1037,6 +1083,7 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio clips.into_iter().try_for_each(|(id, clip)| match clip { ClipTo::Keep => Ok(()), ClipTo::Path(path) => clip_image_to(d, id, path), + ClipTo::File(path) => clip_file_to(d, id, path), ClipTo::Nest(path) => new_clip_group(d, id, path), ClipTo::Off => unclip(d, id), }) @@ -1962,15 +2009,21 @@ fn status_rank(status: &str) -> usize { /// holds them) or overlap an object that is, as Show DCS Transparency Interactions marks them. fn dcs_transparency(d: &Document) -> BTreeSet { /// Each visible DCS image's id, bounds and whether it is transparent, and the bounds of each - /// other visible object with its own transparency. - fn walk(d: &Document, n: &Node, held: bool, images: &mut Vec<(NodeId, Rect, bool)>, see_through: &mut Vec) { + /// other visible object with its own transparency; bounds are cut to `clip`, the bounds of the + /// clipping paths of the clip groups and layers holding the object. + fn walk(d: &Document, n: &Node, held: bool, clip: Option, images: &mut Vec<(NodeId, Rect, bool)>, see_through: &mut Vec) { if !n.visible { return; } let own = n.shows_own_transparency(); + // The part of the object that shows through `clip`; none when it is clipped away. + let shown = n.geometric_bounds().and_then(|b| match clip { + Some(c) => Some(c.intersect(b)).filter(|i| i.area() > 0.0), + None => Some(b), + }); match &n.kind { NodeKind::Image(im) if d.images.get(&im.key).is_some_and(ImageBlob::is_separated) => { - if let Some(b) = n.geometric_bounds() { + if let Some(b) = shown { images.push((n.id, b, held || own)); // A transparent DCS image is an object with its own transparency for the // others it overlaps. @@ -1979,16 +2032,25 @@ fn dcs_transparency(d: &Document) -> BTreeSet { } } } - _ if own => see_through.extend(n.geometric_bounds()), + _ if own => see_through.extend(shown), _ => {} } - for c in n.children().into_iter().flatten() { - walk(d, c, held || own, images, see_through); + let Some(children) = n.children() else { return }; + // A clip group's or clipping layer's first child clips the others. + let clip = match &n.kind { + NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. } => match children.first().and_then(|c| c.geometric_bounds()) { + Some(c) => Some(clip.map_or(c, |o| o.intersect(c))), + None => clip, + }, + _ => clip, + }; + for c in children { + walk(d, c, held || own, clip, images, see_through); } } let (mut images, mut see_through) = (vec![], vec![]); for l in &d.layers { - walk(d, l, false, &mut images, &mut see_through); + walk(d, l, false, None, &mut images, &mut see_through); } images .into_iter() diff --git a/crates/engine/src/cmd/live/commands.rs b/crates/engine/src/cmd/live/commands.rs index 0c835c7b5d..8a92d759f9 100644 --- a/crates/engine/src/cmd/live/commands.rs +++ b/crates/engine/src/cmd/live/commands.rs @@ -244,7 +244,7 @@ pub fn specs() -> Vec { "Move Envelope Mesh Point", [], None, - "{id, index, x, y, handle?: 0 right|1 left|2 down|3 up} move a point of a mesh envelope (its handles follow), or with `handle` place that handle end at (x, y); object.mesh.movePoint, addLine and deletePoint edit mesh envelopes too", + "{id, index, x, y, handle?: 0 right|1 left|2 down|3 up} move a point of a mesh or warp envelope (its handles follow), or with `handle` place that handle end at (x, y); a warp's points are those of its grid (4×4 patches, or 8×8 or 16×16 where 4×4 draws more than 0.1% of its diagonal away from the warp), and its first edit makes it a mesh envelope on that grid in the same undo step (a warp no such grid follows is refused: Reset with Mesh first); object.mesh.movePoint, movePoints, addLine and deletePoint edit mesh and warp envelopes too", has_doc, env_set_mesh_point ), @@ -263,7 +263,7 @@ pub fn specs() -> Vec { "Set Mesh Point Color", [], None, - "{id, index | points: [index…] | items: [{id, index | points}…], color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1} colour and/or opacity of gradient mesh points (one undo step; an index out of range changes nothing)", + "{id, index | points: [index…] | items: [{id, index | points}…], color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1} colour and/or opacity of gradient mesh points (one undo step; an index out of range changes nothing, and so does a call that changes no point, with no undo step)", has_doc, mesh_set_color ), @@ -272,7 +272,7 @@ pub fn specs() -> Vec { "Move Mesh Point", [], None, - "{id, index, x, y, handle?: 0 right|1 left|2 down|3 up} move a point of a gradient mesh or mesh envelope (its handles follow), or with `handle` place that handle end at (x, y)", + "{id, index, x, y, handle?: 0 right|1 left|2 down|3 up} move a point of a gradient mesh or a mesh or warp envelope (its handles follow; a warp becomes a mesh envelope, see object.envelope.setMeshPoint), or with `handle` place that handle end at (x, y)", has_doc, mesh_move_point ), @@ -281,7 +281,7 @@ pub fn specs() -> Vec { "Move Mesh Points", [], None, - "{id, points: [index…] | items: [{id, index | points}…], dx, dy} move points of gradient meshes or mesh envelopes by (dx, dy), their handles with them (one undo step; an index out of range changes nothing)", + "{id, points: [index…] | items: [{id, index | points}…], dx, dy} move points of gradient meshes or mesh or warp envelopes by (dx, dy), their handles with them (warps become mesh envelopes, see object.envelope.setMeshPoint; one undo step; an index out of range changes nothing, and so does a call that moves no point, with no undo step)", has_doc, mesh_move_points ), @@ -290,7 +290,7 @@ pub fn specs() -> Vec { "Add Mesh Line", [], None, - "{id, x, y, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), tolerance?: pt (0)} add a row and a column through (x, y), inside or on the edge, to a gradient mesh (new point in `color`) or a mesh envelope; a point outside within `tolerance` of the edge adds them through the nearest point of the edge; at a point that is already a mesh point it adds no line, and records no undo step unless `color` changes a gradient mesh's point (a mesh envelope's points have no color) → {index}", + "{id, x, y, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), tolerance?: pt (0)} add a row and a column through (x, y), inside or on the edge, to a gradient mesh (new point in `color`) or a mesh or warp envelope (a warp becomes a mesh envelope, see object.envelope.setMeshPoint); a point outside within `tolerance` of the edge adds them through the nearest point of the edge; at a point that is already a mesh point it adds no line, and records no undo step unless `color` changes a gradient mesh's point (an envelope's points have no color) → {index}", has_doc, mesh_add_line ), @@ -299,7 +299,7 @@ pub fn specs() -> Vec { "Delete Mesh Point", [], None, - "{id, index} delete the mesh lines through a point of a gradient mesh or mesh envelope", + "{id, index} delete the mesh lines through a point of a gradient mesh or a mesh or warp envelope (a warp becomes a mesh envelope, see object.envelope.setMeshPoint)", has_doc, mesh_delete_point ), diff --git a/crates/engine/src/cmd/live/envelope.rs b/crates/engine/src/cmd/live/envelope.rs index b9a315325b..5357ea51c0 100644 --- a/crates/engine/src/cmd/live/envelope.rs +++ b/crates/engine/src/cmd/live/envelope.rs @@ -1,6 +1,6 @@ use super::super::object::choice; use super::common::{fix_ids, ids_json, is_envelope, roots_param, selected_of, wrap}; -use super::mesh::{handle_param, index_param, whole}; +use super::mesh::{envelope_edit_grid, handle_param, index_param, mesh_envelope, warp_point_stays, whole}; use super::{ Affine, Appearance, Arc, Beside, Color, Document, EngineError, EnvelopeKind, EnvelopeMap, EnvelopeOptions, Node, NodeId, NodeKind, Paint, PathData, Point, PreserveShape, Result, Session, Value, bad, check_numbers, f64_or, f64_req, json, live, object_param, ok, switch_or, text_param, @@ -79,8 +79,7 @@ fn mesh_kind(map: &EnvelopeMap, maintain: bool, rows: u32, cols: u32) -> Envelop return EnvelopeKind::Mesh { rows, cols, points: map.grid(rows, cols), handles: vec![] }; } // The surface's points with handles along it: the grid lines keep the current shape. - let m = map.surface_mesh(rows, cols, Color::BLACK); - EnvelopeKind::Mesh { rows, cols, points: m.points.iter().map(|q| q.p).collect(), handles: m.points.iter().map(|q| q.handles).collect() } + mesh_envelope(&map.surface_mesh(rows, cols, Color::BLACK)) } pub(super) fn env_make_mesh(s: &mut Session, p: &Value) -> Result { @@ -428,7 +427,20 @@ pub(super) fn env_set_mesh_point(s: &mut Session, p: &Value) -> Result { let index = index_param(p, "index", C)?; let q = Point::new(f64_req(p, "x", C)?, f64_req(p, "y", C)?); let handle = handle_param(p, C)?; + // A warp whose point or handle stays where it is stays a warp. + if warp_point_stays(&s.doc()?.doc, id, index, handle, q, C)? { + return ok(); + } s.edit("Move Envelope Point", |d, _| { + // A warp's first edited point makes it a mesh envelope on its grid, in the same step. + if let Some(n) = d.node(id) + && matches!(&n.kind, NodeKind::Envelope { kind, .. } if matches!(**kind, EnvelopeKind::Warp { .. })) + { + let grid = envelope_edit_grid(n, C).ok_or_else(|| bad(C, "not a mesh envelope point"))??; + if let Some(NodeKind::Envelope { kind, .. }) = d.node_mut(id).map(|n| &mut n.kind) { + **kind = mesh_envelope(&grid); + } + } let Some(NodeKind::Envelope { kind, .. }) = d.node_mut(id).map(|n| &mut n.kind) else { return Err(bad(C, "not a mesh envelope point")); }; diff --git a/crates/engine/src/cmd/live/mesh.rs b/crates/engine/src/cmd/live/mesh.rs index 2290b56af4..97b6160718 100644 --- a/crates/engine/src/cmd/live/mesh.rs +++ b/crates/engine/src/cmd/live/mesh.rs @@ -119,31 +119,90 @@ fn with_mesh(s: &mut Session, p: &Value, cmd: &str, label: &str, envelopes: b s.edit(label, move |d, _| edit_grid(d, id, cmd, envelopes, f)) } -/// Run `f` on the gradient mesh `id` of `d`; with `envelopes`, a mesh envelope's grid too (its -/// points and handles are written back: editing fills in the handles). -fn edit_grid(d: &mut Document, id: NodeId, cmd: &str, envelopes: bool, f: impl FnOnce(&mut GradientMesh) -> Result) -> Result { - edit_kind(&mut d.node_mut(id).ok_or(EngineError::NoNode(id))?.kind, cmd, envelopes, f) +/// The grid an edit of envelope `n`'s points starts from: a mesh envelope's own grid, or a warp's +/// grid ([`live::warp_grid`]), which the edit turns into a mesh envelope. `None` for other nodes. +pub(super) fn envelope_edit_grid(n: &Node, cmd: &str) -> Option> { + let NodeKind::Envelope { kind, .. } = &n.kind else { return None }; + match &**kind { + EnvelopeKind::Mesh { rows, cols, points, handles } => { + Some(live::envelope_grid(*rows, *cols, points, handles).ok_or_else(|| bad(cmd, "the envelope's mesh is malformed"))) + } + EnvelopeKind::Warp { .. } => { + Some(live::warp_grid(n).ok_or_else(|| bad(cmd, "this warp's points can't be edited: use Reset with Mesh first"))) + } + EnvelopeKind::TopObject { .. } => None, + } } -/// [`edit_grid`] on a node's kind. -fn edit_kind(k: &mut NodeKind, cmd: &str, envelopes: bool, f: impl FnOnce(&mut GradientMesh) -> Result) -> Result { - match k { - NodeKind::Mesh(m) => f(m), - NodeKind::Envelope { kind, .. } if envelopes && matches!(**kind, EnvelopeKind::Mesh { .. }) => { - let EnvelopeKind::Mesh { rows, cols, points, handles } = &mut **kind else { - return Err(bad(cmd, "not a gradient mesh or mesh envelope")); - }; - let mut m = live::envelope_grid(*rows, *cols, points, handles).ok_or_else(|| bad(cmd, "the envelope's mesh is malformed"))?; - let r = f(&mut m)?; - (*rows, *cols) = (m.rows, m.cols); - *points = m.points.iter().map(|q| q.p).collect(); - *handles = m.points.iter().map(|q| q.handles).collect(); - Ok(r) - } - _ => Err(bad(cmd, if envelopes { "not a gradient mesh or mesh envelope" } else { "not a gradient mesh" })), +/// The mesh envelope kind of grid `m`, with its points' handles. +pub(super) fn mesh_envelope(m: &GradientMesh) -> EnvelopeKind { + EnvelopeKind::Mesh { + rows: m.rows, + cols: m.cols, + points: m.points.iter().map(|q| q.p).collect(), + handles: m.points.iter().map(|q| q.handles).collect(), } } +/// Does placing point `index` of warp envelope `id` of `d`, or that point's `handle` end, at `q` +/// leave it where it is? Such a placement is no edit. `false` for other objects and for an index +/// out of range, whose edits run as before. +pub(super) fn warp_point_stays(d: &Document, id: NodeId, index: usize, handle: Option, q: Point, cmd: &str) -> Result { + let Some(n) = d.node(id).filter(|n| matches!(&n.kind, NodeKind::Envelope { kind, .. } if matches!(**kind, EnvelopeKind::Warp { .. }))) else { + return Ok(false); + }; + let grid = envelope_grid_to_edit(n, cmd, true)?; + Ok(grid.points.get(index).is_some_and(|pt| match handle { + // The caller sends a handle's end as point plus handle; `q - p` can round away from it. + Some(h) => pt.handles.get(h).is_some_and(|v| pt.p + *v == q), + None => pt.p == q, + })) +} + +/// The grid of envelope `n` that [`edit_grid`] edits (only `envelopes`), or the error it fails with. +fn envelope_grid_to_edit(n: &Node, cmd: &str, envelopes: bool) -> Result { + match envelope_edit_grid(n, cmd).filter(|_| envelopes) { + Some(grid) => grid, + None => Err(bad(cmd, if envelopes { "not a gradient mesh or mesh envelope" } else { "not a gradient mesh" })), + } +} + +/// The grid of mesh `id` of `d` that [`edit_grid`] edits, as it is now. +fn grid_to_edit(d: &Document, id: NodeId, cmd: &str, envelopes: bool) -> Result { + match d.node(id) { + Some(Node { kind: NodeKind::Mesh(m), .. }) => Ok(m.clone()), + Some(n) => envelope_grid_to_edit(n, cmd, envelopes), + None => Err(EngineError::NoNode(id)), + } +} + +/// Run `f` on the gradient mesh `id` of `d`; with `envelopes`, a warp or mesh envelope's grid too +/// (see [`edit_node`]). +fn edit_grid(d: &mut Document, id: NodeId, cmd: &str, envelopes: bool, f: impl FnOnce(&mut GradientMesh) -> Result) -> Result { + edit_node(d.node_mut(id).ok_or(EngineError::NoNode(id))?, cmd, envelopes, f) +} + +/// [`edit_grid`] on a node: with `envelopes`, a warp or mesh envelope's grid +/// ([`envelope_edit_grid`]) is edited too, and its points and handles are written back as a mesh +/// envelope (editing fills in the handles, and makes a warp a mesh envelope). +fn edit_node(n: &mut Node, cmd: &str, envelopes: bool, f: impl FnOnce(&mut GradientMesh) -> Result) -> Result { + if let NodeKind::Mesh(m) = &mut n.kind { + return f(m); + } + let start = envelope_grid_to_edit(n, cmd, envelopes)?; + let mut m = start.clone(); + let r = f(&mut m)?; + // A warp stays a warp when the edit changed nothing. + let warp = matches!(&n.kind, NodeKind::Envelope { kind, .. } if matches!(**kind, EnvelopeKind::Warp { .. })); + if warp && m == start { + return Ok(r); + } + if let NodeKind::Envelope { kind, .. } = &mut n.kind { + **kind = mesh_envelope(&m); + } + Ok(r) +} + /// Most mesh points one command names, over all its meshes. const MAX_POINTS: usize = 1 << 20; @@ -178,7 +237,8 @@ fn point_items(p: &Value, cmd: &str) -> Result)>> { } /// Run `f` on each mesh point `items` names, as one undo step `label` (an index out of range -/// fails it, changing nothing); with `envelopes`, on mesh envelopes' points too. +/// fails it, changing nothing); with `envelopes`, on warp and mesh envelopes' points too. When `f` +/// changes no point, nothing changes and no undo step is recorded. fn with_points( s: &mut Session, items: &[(NodeId, BTreeSet)], @@ -187,6 +247,20 @@ fn with_points( envelopes: bool, mut f: impl FnMut(&mut live::MeshPoint) -> Result<()>, ) -> Result<()> { + let doc = &s.doc()?.doc; + let mut changes = false; + for (id, points) in items { + let mut m = grid_to_edit(doc, *id, cmd, envelopes)?; + for i in points { + let q = m.points.get_mut(*i).ok_or_else(|| bad(cmd, "index out of range"))?; + let before = q.clone(); + f(q)?; + changes |= *q != before; + } + } + if !changes { + return Ok(()); + } s.edit(label, |d, _| { for (id, points) in items { edit_grid(d, *id, cmd, envelopes, |m| { @@ -255,6 +329,10 @@ pub(super) fn mesh_move_point(s: &mut Session, p: &Value) -> Result { let index = index_param(p, "index", C)?; let q = Point::new(f64_req(p, "x", C)?, f64_req(p, "y", C)?); let handle = handle_param(p, C)?; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?; + if warp_point_stays(&s.doc()?.doc, id, index, handle, q, C)? { + return ok(); + } with_mesh(s, p, C, "Move Mesh Point", true, |m| { let pt = m.points.get_mut(index).ok_or_else(|| bad(C, "index out of range"))?; match handle { @@ -298,12 +376,12 @@ pub(super) fn mesh_add_line(s: &mut Session, p: &Value) -> Result { } // The lines are added to a copy of the object. A point that is already a mesh point adds none: // when its color stays too, nothing changes and no undo step is recorded. The grid is compared, - // not the node: a mesh envelope stored without handles takes them in any edit, and keeps no - // colors, so only its points and handles count. - let orig = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.kind.clone(); - let colored = matches!(orig, NodeKind::Mesh(_)); - let mut kind = orig.clone(); - let (i, same) = edit_kind(&mut kind, C, true, |m| { + // not the node: a mesh envelope stored without handles takes them in any edit, a warp becomes + // a mesh envelope, and neither keeps colors, so only their points and handles count. + let orig = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.clone(); + let colored = matches!(orig.kind, NodeKind::Mesh(_)); + let mut node = orig.clone(); + let (i, same) = edit_node(&mut node, C, true, |m| { let before = m.clone(); let i = add(m)?; let shape = |g: &GradientMesh| (g.rows, g.cols, g.points.iter().map(|q| (q.p, q.handles)).collect::>()); @@ -315,10 +393,10 @@ pub(super) fn mesh_add_line(s: &mut Session, p: &Value) -> Result { let index = s.edit("Add Mesh Line", move |d, _| { let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?; // Settling typed values before the edit may have changed the object: add the lines again. - if n.kind != orig { - return edit_kind(&mut n.kind, C, true, add); + if n.kind != orig.kind { + return edit_node(n, C, true, add); } - n.kind = kind; + n.kind = node.kind; Ok(i) })?; Ok(json!({ "index": index })) diff --git a/crates/engine/src/tests/dcs.rs b/crates/engine/src/tests/dcs.rs index 9853ed5da7..c801401de0 100644 --- a/crates/engine/src/tests/dcs.rs +++ b/crates/engine/src/tests/dcs.rs @@ -357,6 +357,42 @@ fn a_file_that_lost_its_clipping_path_unclips_the_image() { ); } +#[test] +fn a_file_that_gains_its_clipping_path_again_clips_the_group_that_stayed() { + let dir = temp_dir("update-regained-clip"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap(); + let placed = NodeId(r["ids"][0].as_u64().unwrap()); + let id = image_of(&s, &r["ids"][0]).id; + let other = s.execute("file.place", &json!({ "path": path, "at": [200, 100] })).unwrap(); + s.execute("symbol.new", &json!({ "name": "Pic", "ids": [other["ids"][0]] })).unwrap(); + let unclipped = String::from_utf8(two_plates()).unwrap().replacen("closepath clip newpath", "closepath newpath ", 1); + // The symbol's art: how deep the image is. + let depth = |s: &Session| { + fn find(n: &Node, at: usize) -> Option { + if matches!(n.kind, NodeKind::Image(_)) { + return Some(at); + } + n.children().and_then(|ch| ch.iter().find_map(|c| find(c, at + 1))) + } + find(&s.doc().unwrap().doc.symbols.iter().find(|w| w.name == "Pic").expect("the symbol").art, 0) + }; + let clipped_depth = depth(&s); + for _ in 0..2 { + std::fs::write(&path, unclipped.as_bytes()).unwrap(); + s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + std::fs::write(&path, two_plates()).unwrap(); + s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.parent_of(id), Some(placed), "the placed group holds the image itself"); + let NodeKind::Group { children, clip: true } = &doc.node(placed).unwrap().kind else { panic!("a clip group again") }; + assert!(matches!(&children[..], [c, im] if matches!(c.kind, NodeKind::Path { clipping: true, .. }) && im.id == id)); + assert_eq!(depth(&s), clipped_depth, "the symbol's image is not nested deeper"); + assert!(symbol_clip_width(&s, "Pic").is_some(), "the symbol's image is clipped again"); + } +} + /// The kind of group `g` is, as (clip, the kinds of its children are just one image). fn plain_group_of_image(g: &Node) -> Option<(bool, bool)> { match &g.kind { @@ -737,6 +773,88 @@ fn dcs_transparency_marks_transparent_and_overlapped_dcs_images() { assert!(error(&mut s, "links.list", json!({ "dcsTransparency": "yes" })).contains("dcsTransparency"), "a flag that isn't true or false"); } +#[test] +fn dcs_transparency_looks_only_at_the_part_of_an_image_its_clipping_path_shows() { + let dir = temp_dir("transparency-clipped"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap(); + let group = NodeId(r["ids"][0].as_u64().unwrap()); + let image = image_of(&s, &r["ids"][0]).id; + let (clip, all) = { + let doc = &s.doc().unwrap().doc; + let NodeKind::Group { children, clip: true } = &doc.node(group).unwrap().kind else { panic!("a clipping group") }; + (children[0].geometric_bounds().unwrap(), doc.node(image).unwrap().geometric_bounds().unwrap()) + }; + assert!(all.x1 - clip.x1 > 2.0, "the file's clipping path shows the left half: {clip:?} of {all:?}"); + // A half-transparent square over the part of the image the clipping path hides. + let x = (clip.x1 + all.x1) / 2.0 - 1.0; + let over = s.execute("shape.rectangle", &json!({"x": x, "y": all.y0, "width": 2, "height": 2})).unwrap()["id"].as_u64().unwrap(); + s.execute("transparency.set", &json!({"ids": [over], "opacity": 50})).unwrap(); + let marked = |s: &mut Session| s.execute("links.list", &json!({ "dcsTransparency": true })).unwrap()["links"][0]["dcsTransparency"] == true; + assert!(!marked(&mut s), "the square is over the hidden part only"); + s.execute("transparency.set", &json!({"ids": [over], "opacity": 100})).unwrap(); + let shown = s.execute("shape.rectangle", &json!({"x": clip.x0, "y": all.y0, "width": 2, "height": 2})).unwrap()["id"].as_u64().unwrap(); + s.execute("transparency.set", &json!({"ids": [shown], "opacity": 50})).unwrap(); + assert!(marked(&mut s), "a square over the part that shows"); +} + +#[test] +fn dcs_transparency_skips_a_transparent_object_its_own_clipping_paths_hide() { + let dir = temp_dir("transparency-clipped-over"); + let path = write(&dir, "pic.eps", &two_plates()); + // A session with the file placed, and the top-left corner of the image, inside the part its + // clipping path shows. + let placed = || { + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap(); + let b = image_of(&s, &r["ids"][0]).geometric_bounds().unwrap(); + (s, b.x0, b.y0) + }; + let rect = |s: &mut Session, x: f64, y: f64, width: f64| { + s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": width, "height": 2})).unwrap()["id"].as_u64().unwrap() + }; + let make = |s: &mut Session, ids: [u64; 2]| { + s.execute("select.set", &json!({ "ids": ids })).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap() + }; + let marked = |s: &mut Session| s.execute("links.list", &json!({ "dcsTransparency": true })).unwrap()["links"][0]["dcsTransparency"] == true; + // A half-transparent square over the part of the image that shows. + let square = |s: &mut Session, x: f64, y: f64| { + let id = rect(s, x, y, 2.0); + s.execute("transparency.set", &json!({"ids": [id], "opacity": 50})).unwrap(); + assert!(marked(s), "the square over the image"); + id + }; + + // Its own clip group's clipping path is beside it. + let (mut s, x, y) = placed(); + let over = square(&mut s, x, y); + let beside = rect(&mut s, x + 5.0, y, 2.0); + make(&mut s, [over, beside]); + assert!(!marked(&mut s), "a clip group that hides the square"); + + // Its layer's clipping path is beside it. + let (mut s, x, y) = placed(); + s.execute("layer.new", &json!({})).unwrap(); + square(&mut s, x, y); + rect(&mut s, x + 5.0, y, 2.0); + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute("layer.clippingMask.toggle", &json!({})).unwrap()["clip"].as_bool().unwrap()); + assert!(!marked(&mut s), "a clipping layer that hides the square"); + + // Each of two nested clipping paths shows part of the inner group, and only the inner one + // covers the square. + let (mut s, x, y) = placed(); + let over = square(&mut s, x, y); + let inner = rect(&mut s, x, y, 40.0); + let group = make(&mut s, [over, inner]); + assert!(marked(&mut s), "the inner clipping path shows the square"); + let outer = rect(&mut s, x + 10.0, y, 20.0); + make(&mut s, [group, outer]); + assert!(!marked(&mut s), "the two clipping paths together hide the square"); +} + #[test] fn dcs_transparency_counts_a_transparent_dcs_image_over_another() { let dir = temp_dir("transparency-two"); diff --git a/crates/engine/src/tests/envelope_edit.rs b/crates/engine/src/tests/envelope_edit.rs index 7b87bef2cb..ccad701312 100644 --- a/crates/engine/src/tests/envelope_edit.rs +++ b/crates/engine/src/tests/envelope_edit.rs @@ -151,6 +151,239 @@ fn mesh_handles_turn_with_the_envelope_and_round_trip() { assert!(matches!(n.kind, NodeKind::Envelope { kind, .. } if matches!(&*kind, EnvelopeKind::Mesh { handles, .. } if handles.is_empty()))); } +/// The kind of envelope `e`. +fn kind(s: &Session, e: NodeId) -> EnvelopeKind { + match node(s, e).kind { + NodeKind::Envelope { kind, .. } => *kind, + k => panic!("{k:?}"), + } +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +/// Moving a point of a warp envelope makes it a mesh envelope on the warp's grid with that point +/// moved, as one undo step: the other points and every handle stay where the warp had them, and +/// the shape away from the moved point stays the warp's. Undo gives back the warp, Redo the edit. +#[test] +fn moving_a_warp_point_makes_it_a_mesh_envelope_in_one_step() { + let mut s = session(); + let (_, e) = enveloped(&mut s, "object.envelope.makeWithWarp", json!({"style": "arc", "bend": 50})); + let warp = node(&s, e); + let grid = live::warp_grid(&warp).unwrap(); + assert_eq!((grid.rows, grid.cols), (4, 4)); + let before = EnvelopeMap::of(&warp).unwrap(); + let n = undo_len(&s); + // An interior point. + s.execute("object.mesh.movePoint", &json!({"id": e.0, "index": 6, "x": 160, "y": 120})).unwrap(); + assert_eq!(undo_len(&s), n + 1, "one undo step"); + let (rows, cols, points, handles) = mesh(&s, e); + assert_eq!((rows, cols, points.len(), handles.len()), (4, 4, 25, 25)); + for (i, q) in grid.points.iter().enumerate() { + let want = if i == 6 { Point::new(160.0, 120.0) } else { q.p }; + assert!(points[i].distance(want) < 1e-9, "point {i}: {:?} vs {want:?}", points[i]); + assert_eq!(handles[i], q.handles, "handles of point {i}"); + } + let moved = node(&s, e); + let after = EnvelopeMap::of(&moved).unwrap(); + let b = before.src(); + let tol = b.width().hypot(b.height()) * 1e-3; + for (u, v) in [(0.9, 0.9), (0.6, 0.875), (1.0, 0.5), (0.0, 1.0)] { + assert!(after.at(u, v).distance(before.at(u, v)) <= tol, "({u}, {v}): {:?} vs {:?}", after.at(u, v), before.at(u, v)); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(node(&s, e), warp, "Undo gives back the warp, style and bend included"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(mesh(&s, e).2[6], Point::new(160.0, 120.0)); + // A corner of a warp, and a handle with object.envelope.setMeshPoint. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("object.mesh.movePoints", &json!({"id": e.0, "points": [0], "dx": -10, "dy": -5})).unwrap(); + assert!(mesh(&s, e).2[0].distance(grid.points[0].p + Vec2::new(-10.0, -5.0)) < 1e-9); + s.execute("edit.undo", &json!({})).unwrap(); + let end = grid.points[12].p + Vec2::new(30.0, -30.0); + s.execute("object.envelope.setMeshPoint", &json!({"id": e.0, "index": 12, "x": end.x, "y": end.y, "handle": 0})).unwrap(); + let (_, _, points, handles) = mesh(&s, e); + assert!((points[12] + handles[12][live::H_RIGHT]).distance(end) < 1e-9); + assert_eq!(handles[12][live::H_LEFT], grid.points[12].handles[live::H_LEFT]); + assert_eq!(undo_len(&s), n + 1); +} + +/// After a warp's point is edited, the envelope keeps its content, options and fidelity; it saves +/// and opens again as it is; Reset with Mesh with Maintain Shape keeps the edited shape and Reset +/// with Warp gives the chosen style; Release gives back the edited mesh as its shape and Expand +/// keeps the edited distortion. +#[test] +fn an_edited_warp_saves_resets_releases_and_expands_as_edited() { + let mut s = session(); + let (_, e) = enveloped(&mut s, "object.envelope.makeWithWarp", json!({"style": "flag", "bend": 40})); + s.execute("object.envelope.options", &json!({"fidelity": 80, "distortAppearance": false})).unwrap(); + let warp = node(&s, e); + // The middle of the bottom edge, 30 down. + s.execute("object.mesh.movePoints", &json!({"id": e.0, "points": [22], "dx": 0, "dy": 30})).unwrap(); + let edited = node(&s, e); + let (NodeKind::Envelope { content: c0, options: o0, fidelity: f0, .. }, NodeKind::Envelope { content: c1, options: o1, fidelity: f1, .. }) = + (&warp.kind, &edited.kind) + else { + panic!("envelopes") + }; + assert_eq!((c0, o0, f0), (c1, o1, f1), "content, options and fidelity stay"); + let d = s.doc().unwrap().doc.clone(); + let back = vectorcraft_format::load(&vectorcraft_format::save(&d, false)).unwrap(); + assert_eq!(back.node(e), d.node(e), "a save opens again as edited"); + // Reset with Mesh, keeping the shape: the edited points. + let (_, _, points, _) = mesh(&s, e); + s.execute("object.envelope.resetWithMesh", &json!({"maintainShape": true})).unwrap(); + let (rows, cols, kept, _) = mesh(&s, e); + assert_eq!((rows, cols), (4, 4)); + for (p, q) in points.iter().zip(&kept) { + assert!(p.distance(*q) < 1e-6, "{p:?} vs {q:?}"); + } + // Reset with Warp: the chosen style replaces the edit. + s.execute("object.envelope.resetWithWarp", &json!({"style": "bulge", "bend": 30})).unwrap(); + assert!(matches!(kind(&s, e), EnvelopeKind::Warp { style, bend, .. } if style == "bulge" && bend == 30.0)); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(node(&s, e), edited); + // Release: the content and the edited mesh as the envelope's shape. + s.execute("select.set", &json!({"ids": [e.0]})).unwrap(); + let ids = s.execute("object.envelope.release", &json!({})).unwrap(); + let ids: Vec = ids["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect(); + let shape = ids.iter().find_map(|id| match node(&s, *id).kind { + NodeKind::Mesh(m) => Some(m), + _ => None, + }); + let shape = shape.expect("the envelope's shape"); + assert_eq!(shape.points.iter().map(|q| q.p).collect::>(), points); + s.execute("edit.undo", &json!({})).unwrap(); + // Expand: the distorted content follows the moved point, unlike the warp's. + let expanded = |s: &mut Session| { + s.execute("select.set", &json!({"ids": [e.0]})).unwrap(); + s.execute("object.envelope.expand", &json!({})).unwrap(); + let b = node(s, e).geometric_bounds().unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + b + }; + let edited_bounds = expanded(&mut s); + s.execute("edit.undo", &json!({})).unwrap(); + let warp_bounds = expanded(&mut s); + assert!(edited_bounds.y1 > warp_bounds.y1 + 5.0, "{edited_bounds:?} vs {warp_bounds:?}"); +} + +/// An edit of a warp's points that fails (an index out of range, here on the second of two +/// warps) changes neither warp and adds no undo step; a warp that no grid follows closely enough +/// shows no points and is refused, and so is a top object envelope. +#[test] +fn a_warp_point_edit_that_fails_changes_nothing() { + let mut s = session(); + let (_, e) = enveloped(&mut s, "object.envelope.makeWithWarp", json!({"style": "arc", "bend": 50})); + let (_, f) = enveloped(&mut s, "object.envelope.makeWithWarp", json!({"style": "wave", "bend": 50})); + let (we, wf, n) = (node(&s, e), node(&s, f), undo_len(&s)); + let r = s.execute("object.mesh.movePoints", &json!({"items": [{"id": e.0, "points": [0]}, {"id": f.0, "points": [3, 99999]}], "dx": 5, "dy": 5})); + assert!(r.is_err(), "{r:?}"); + let r = s.execute("object.envelope.setMeshPoint", &json!({"id": e.0, "index": 25, "x": 0, "y": 0})); + assert!(r.is_err(), "{r:?}"); + assert_eq!((node(&s, e), node(&s, f), undo_len(&s)), (we, wf, n), "nothing changed"); + // The old point map's fisheye: no grid of up to 16×16 patches follows it. + let (_, g) = enveloped(&mut s, "object.envelope.makeWithWarp", json!({"style": "fisheye", "bend": 100, "version": 0})); + let old = node(&s, g); + assert!(live::warp_grid(&old).is_none()); + assert!(live::envelope_overlay(&old).unwrap().1.is_none(), "no points show"); + let n = undo_len(&s); + for (cmd, p) in [ + ("object.mesh.movePoint", json!({"id": g.0, "index": 0, "x": 0, "y": 0})), + ("object.envelope.setMeshPoint", json!({"id": g.0, "index": 0, "x": 0, "y": 0})), + ("object.mesh.addLine", json!({"id": g.0, "x": 200, "y": 150})), + ] { + let r = s.execute(cmd, &p); + assert!( + matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "this warp's points can't be edited: use Reset with Mesh first"), + "{cmd}: {r:?}" + ); + } + assert_eq!((node(&s, g), undo_len(&s)), (old, n)); +} + +/// An edit that moves no point of a warp (no points named, a move by nothing, a point placed where +/// it is, a line added through one of its points) leaves it a warp and records no undo step. +#[test] +fn a_warp_edit_that_moves_nothing_leaves_the_warp() { + let mut s = session(); + let (_, e) = enveloped(&mut s, "object.envelope.makeWithWarp", json!({"style": "arc", "bend": 50})); + let (warp, n) = (node(&s, e), undo_len(&s)); + let grid = live::warp_grid(&warp).unwrap(); + s.execute("object.mesh.movePoints", &json!({"id": e.0, "points": [], "dx": 10, "dy": 0})).unwrap(); + s.execute("object.mesh.movePoints", &json!({"id": e.0, "points": [3, 6], "dx": 0, "dy": 0})).unwrap(); + assert_eq!((node(&s, e), undo_len(&s)), (warp.clone(), n)); + let q = grid.points[6].clone(); + s.execute("object.mesh.movePoint", &json!({"id": e.0, "index": 6, "x": q.p.x, "y": q.p.y})).unwrap(); + s.execute("object.envelope.setMeshPoint", &json!({"id": e.0, "index": 6, "x": q.p.x, "y": q.p.y})).unwrap(); + // A line added through a point of the warp's grid adds none. + let r = s.execute("object.mesh.addLine", &json!({"id": e.0, "x": q.p.x, "y": q.p.y})).unwrap(); + assert_eq!(r["index"], json!(6)); + assert_eq!((node(&s, e), undo_len(&s)), (warp, n)); + // An unknown mesh still fails. + assert!(s.execute("object.mesh.movePoints", &json!({"id": 99999, "points": [], "dx": 1, "dy": 0})).is_err()); +} + +/// A handle placed at its own end, sent as point plus handle, leaves a warp a warp, even where +/// `(p + v) - p` rounds to a value other than `v`. +#[test] +fn a_warp_handle_placed_at_its_end_leaves_the_warp() { + let mut s = session(); + let (_, e) = enveloped(&mut s, "object.envelope.makeWithWarp", json!({"style": "arc", "bend": 50})); + let (warp, n) = (node(&s, e), undo_len(&s)); + let grid = live::warp_grid(&warp).unwrap(); + let mut rounds = 0; + for (index, pt) in grid.points.iter().enumerate() { + for (h, v) in pt.handles.iter().enumerate() { + let end = pt.p + *v; + if end - pt.p != *v { + rounds += 1; + } + for cmd in ["object.mesh.movePoint", "object.envelope.setMeshPoint"] { + s.execute(cmd, &json!({"id": e.0, "index": index, "x": end.x, "y": end.y, "handle": h})).unwrap(); + assert_eq!((node(&s, e), undo_len(&s)), (warp.clone(), n), "{cmd}: point {index}, handle {h}"); + } + } + } + assert!(rounds > 0, "the grid has a handle whose end does not give the handle back"); +} + +/// With Direct Selection, a selected warp's point drags as `object.mesh.movePoint`: the preview +/// makes it a mesh envelope, Escape gives back the warp with no undo step, and a finished drag is +/// one undo step. While its contents are edited, its points don't take the press. +#[test] +fn direct_selection_drags_a_warps_point_and_escape_gives_it_back() { + let mut s = session(); + let (_, e) = enveloped(&mut s, "object.envelope.makeWithWarp", json!({"style": "arc", "bend": 50})); + let warp = node(&s, e); + let corner = live::warp_grid(&warp).unwrap().points[24].p; + s.execute("select.set", &json!({"ids": [e.0]})).unwrap(); + let v = ViewInfo::default(); + s.select_tool("directSelection", v).unwrap(); + let n = undo_len(&s); + s.pointer(&PointerEvent::new(PointerKind::Down, corner.x, corner.y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, corner.x + 20.0, corner.y + 10.0), v).unwrap(); + assert!(mesh(&s, e).2[24].distance(corner + Vec2::new(20.0, 10.0)) < 1e-9, "the preview moves the point"); + s.tool_key(vectorcraft_tools::ToolKey::Escape, vectorcraft_tools::Mods::default(), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, corner.x + 20.0, corner.y + 10.0), v).unwrap(); + assert_eq!((node(&s, e), undo_len(&s)), (warp.clone(), n), "Escape gives back the warp"); + s.pointer(&PointerEvent::new(PointerKind::Down, corner.x, corner.y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, corner.x + 20.0, corner.y + 10.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, corner.x + 20.0, corner.y + 10.0), v).unwrap(); + assert_eq!(undo_len(&s), n + 1); + assert!(mesh(&s, e).2[24].distance(corner + Vec2::new(20.0, 10.0)) < 1e-9); + // Edit Contents: the press doesn't take the envelope's point. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("object.envelope.editContents", &json!({"editing": true})).unwrap(); + s.execute("select.set", &json!({"ids": [e.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, corner.x, corner.y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, corner.x + 20.0, corner.y + 10.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, corner.x + 20.0, corner.y + 10.0), v).unwrap(); + assert!(matches!(kind(&s, e), EnvelopeKind::Warp { .. }), "{:?}", kind(&s, e)); +} + #[test] fn reset_with_mesh_keeps_the_warp_shape_along_the_grid() { let mut s = session(); diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index a3c7a72aee..9787401285 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -576,6 +576,42 @@ fn update_links_reads_files_again_inside_symbols_patterns_and_masks() { assert!(images(&s).iter().all(|(_, _, _, size)| *size == (20, 10)), "{:?}", images(&s)); } +/// An image that Placement Options clip, alone in a group the user made, goes into a new clip group +/// inside that group when its file grows, in the layers and in a symbol's art; the user's group +/// stays a plain group. +#[test] +fn placement_options_clip_an_image_alone_in_a_group_inside_that_group() { + let dir = Folder::new("clip-in-group"); + let photo = dir.file("photo.png"); + write(&photo, &png(20, 10, RED)); + let mut s = session(); + let mut groups = vec![]; + for _ in 0..2 { + let id = place(&mut s, &photo); + s.execute("links.placementOptions", &json!({"ids": [id.0], "preserve": "fill", "clip": true})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({"ids": [id.0]})).unwrap()["id"].as_u64().unwrap()); + groups.push((g, id)); + } + let (in_symbol, _) = groups[1]; + s.execute("symbol.new", &json!({"name": "Mark", "ids": [in_symbol.0]})).unwrap(); + write(&photo, &png(60, 20, BLUE)); + s.execute("links.update", &json!({})).unwrap(); + // A plain group holding just a clip group of a clipping path and an image. + let plain_of_clip = |n: &vectorcraft_doc::Node| match &n.kind { + NodeKind::Group { children, clip: false } => matches!(&children[..], [c] if matches!(&c.kind, + NodeKind::Group { children, clip: true } if matches!(&children[..], [p, im] + if matches!(p.kind, NodeKind::Path { clipping: true, .. }) && matches!(im.kind, NodeKind::Image(_))))), + _ => false, + }; + let d = &s.doc().unwrap().doc; + let (g, id) = groups[0]; + assert!(plain_of_clip(d.node(g).unwrap()), "{:?}", d.node(g)); + assert_ne!(d.parent_of(id), Some(g), "the image is in a new clip group"); + let mut found = false; + d.symbols[0].art.walk(&mut |n| found |= plain_of_clip(n)); + assert!(found, "{:?}", d.symbols[0].art); +} + #[test] fn a_missing_link_renders_its_preview_and_relinks() { let dir = Folder::new("missing"); diff --git a/crates/engine/src/tests/live.rs b/crates/engine/src/tests/live.rs index 7beb512ed0..10939d4b2a 100644 --- a/crates/engine/src/tests/live.rs +++ b/crates/engine/src/tests/live.rs @@ -1136,7 +1136,12 @@ fn mesh_points_move_and_colour_together() { assert!(s.execute("object.mesh.movePoints", &p).is_err(), "{p}"); } assert!(s.execute("object.mesh.setPointColor", &json!({"id": a.0, "points": [0, 9], "color": "#000000"})).is_err()); - assert_eq!(((mesh_of(&s, a), mesh_of(&s, b)), undo_len(&s)), (before, n), "nothing changed"); + assert_eq!(((mesh_of(&s, a), mesh_of(&s, b)), undo_len(&s)), (before.clone(), n), "nothing changed"); + // A call that changes no point records no undo step. + s.execute("object.mesh.movePoints", &json!({"id": a.0, "points": [], "dx": 1, "dy": 1})).unwrap(); + s.execute("object.mesh.movePoints", &json!({"id": a.0, "points": [0, 1], "dx": 0, "dy": 0})).unwrap(); + s.execute("object.mesh.setPointColor", &json!({"id": a.0, "points": [2, 6], "color": "#0000ff", "opacity": 0.25})).unwrap(); + assert_eq!(((mesh_of(&s, a), mesh_of(&s, b)), undo_len(&s)), (before, n), "no change, no undo step"); } #[test] diff --git a/crates/engine/src/tests/symbol_nine_slice.rs b/crates/engine/src/tests/symbol_nine_slice.rs index fba17f11ee..b0689d1587 100644 --- a/crates/engine/src/tests/symbol_nine_slice.rs +++ b/crates/engine/src/tests/symbol_nine_slice.rs @@ -250,3 +250,103 @@ fn a_guide_dragged_on_the_canvas_changes_how_a_scaled_instance_draws() { let left = s.doc().unwrap().doc.symbol_nine_slice("Panel").unwrap().left; assert!((left - 0.05).abs() < 1e-9, "{left}"); } + +/// The 200 × 150 [`panel`] instance with its left guide 25 % outside the art: the left column +/// holds no art, so the corner square is in the center column, which runs 0..75 in the art and +/// 0..175 in the instance, and the center square moves with it. The rows are as before. +fn assert_left_outside(boxes: &[Rect]) { + let k = 175.0 / 75.0; + let want = [ + Rect::new(50.0, 50.0, 250.0, 200.0), + Rect::new(50.0, 50.0, 50.0 + 10.0 * k, 60.0), + Rect::new(50.0 + 45.0 * k, 115.0, 50.0 + 55.0 * k, 135.0), + ]; + assert_eq!(boxes.len(), want.len(), "{boxes:?}"); + for (b, w) in boxes.iter().zip(want) { + assert!(close(*b, w), "{b:?} vs {w:?} in {boxes:?}"); + } +} + +/// `symbol.options` takes guides outside the art, within -16..16 and in order on each axis, as +/// one undo step; a scaled instance then draws by the cells its art falls in, and Break Link to +/// Symbol gives that art. Values out of range or out of order are refused without an edit. +#[test] +fn guides_outside_the_art_are_set_by_command_and_scale_by_the_cells_that_hold_art() { + let (mut s, id) = panel(); + s.execute("symbol.options", &json!({"name": "Panel", "nineSliceGuides": [-0.25, 0.25, 0.25, 0.25]})).unwrap(); + assert_left_outside(&placed_boxes(&s, id)); + let list = s.execute("symbol.list", &json!({})).unwrap(); + assert_eq!(list["symbols"][0]["nineSlice"], json!([-0.25, 0.25, 0.25, 0.25])); + for bad in [json!([-16.5, 0.25, 0.25, 0.25]), json!([0.25, 0.25, 0.25, 17]), json!([1.2, 0.25, -0.2, 0.25]), json!([0.25, 0.6, 0.25, 0.6])] { + let e = s.execute("symbol.options", &json!({"name": "Panel", "nineSliceGuides": bad})).unwrap_err().to_string(); + assert!(e.contains("each -16..16"), "{e}"); + } + assert_eq!(s.doc().unwrap().doc.symbol_nine_slice("Panel").unwrap().left, -0.25, "no edit"); + s.execute("symbol.options", &json!({"name": "Panel", "nineSliceGuides": [1.25, 0.25, -0.5, 0.25]})).unwrap(); + // Both vertical guides past the art's right edge: the art keeps its width from the left. + let boxes = placed_boxes(&s, id); + assert!(close(boxes[0], Rect::new(50.0, 50.0, 150.0, 200.0)) && close(boxes[1], Rect::new(50.0, 50.0, 60.0, 60.0)), "{boxes:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_left_outside(&placed_boxes(&s, id)); + let r = s.execute("symbol.breakLink", &json!({})).unwrap(); + let art = NodeId(r["ids"][0].as_u64().unwrap()); + assert_left_outside(&path_boxes(s.doc().unwrap().doc.node(art).unwrap())); +} + +/// Dragging the left guide past the art's left edge on the canvas puts it outside the art, as one +/// undo step, and the scaled instance draws by the cells that hold art. +#[test] +fn a_guide_dragged_past_the_arts_edge_lies_outside_it() { + let (mut s, id) = panel(); + s.execute("symbol.edit", &json!({"name": "Panel"})).unwrap(); + let v = ViewInfo::default(); + s.select_tool("selection", v).unwrap(); + let e = s.doc().unwrap().doc.edited_nine_slice().unwrap(); + let ((a, b), (l, r)) = (e.line(NineSliceGuide::Left), (e.line(NineSliceGuide::Left).0.x, e.line(NineSliceGuide::Right).0.x)); + let y = (a.y + b.y) / 2.0; + // The guides lie a quarter in from each edge, so the art's left edge lies half the guides' + // distance to the left of the left guide, and 25 % outside it lies as far again. + let to = l - (r - l); + s.pointer(&PointerEvent::new(PointerKind::Down, l + 1.0, y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, to, y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, to, y), v).unwrap(); + let g = s.doc().unwrap().doc.symbol_nine_slice("Panel").unwrap(); + assert!((g.left + 0.25).abs() < 1e-9, "{g:?}"); + let e = s.doc().unwrap().doc.edited_nine_slice().unwrap(); + assert!((e.line(NineSliceGuide::Left).0.x - to).abs() < 1e-9, "the guide is drawn where it was dropped"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.symbol_nine_slice("Panel").unwrap().left, 0.25, "one undo step"); + s.execute("edit.redo", &json!({})).unwrap(); + s.execute("symbol.exitEditing", &json!({})).unwrap(); + assert_left_outside(&placed_boxes(&s, id)); +} + +/// A native file keeps guides outside the art exactly, and an instance opened from it draws as +/// before saving; a file whose saved guides are out of range or out of order opens with 9-slice +/// off for that symbol. +#[test] +fn guides_outside_the_art_survive_saving_and_reopening_a_native_file() { + let (mut s, id) = panel(); + let guides = [-0.123456789, 1.5, 0.3, -2.75]; + s.execute("symbol.options", &json!({"name": "Panel", "nineSliceGuides": guides})).unwrap(); + s.execute("symbol.options", &json!({"name": "Panel", "nineSliceGuides": [-0.25, 0.25, 0.25, 0.25]})).unwrap(); + s.execute("symbol.options", &json!({"name": "Panel", "nineSliceGuides": guides})).unwrap(); + let doc = s.doc().unwrap().doc.clone(); + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + let g = back.symbol_nine_slice("Panel").unwrap(); + assert_eq!([g.left, g.top, g.right, g.bottom], guides); + let placed = |d: &vectorcraft_doc::Document| { + let NodeKind::SymbolInstance { symbol, xf } = &d.node(id).unwrap().kind else { panic!("an instance") }; + let art = d.symbols.iter().find(|s| &s.name == symbol).unwrap().art.clone(); + path_boxes(&d.place_symbol_art(symbol, &art, *xf).unwrap()) + }; + assert_eq!(placed(&back), placed(&doc)); + for bad in [json!([-20.0, 0.25, 0.25, 0.25]), json!([0.8, 0.25, 0.5, 0.25]), json!([0.25, 0.25, 0.25]), json!("x")] { + let mut d = (*doc).clone(); + d.unknown.insert(vectorcraft_doc::SYMBOL_NINE_SLICE.into(), json!({ "Panel": bad })); + let back = vectorcraft_format::load(&vectorcraft_format::save(&d, false)).unwrap(); + assert!(back.symbol_nine_slice("Panel").is_none(), "{bad}"); + let NodeKind::SymbolInstance { symbol, xf } = &back.node(id).unwrap().kind else { panic!("an instance") }; + assert!(back.symbol_slice_map(symbol, *xf).is_none(), "{bad}: scaled as a whole"); + } +} diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 52be19a952..37f8c63acf 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -4318,6 +4318,63 @@ proptest! { survive("style library in an EPS", || vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc))?; } + /// Graphic style libraries whose styles are one paint (`/SimpleStyle`): any paint operators in + /// any order, with any operands or none, `Xd` missing or repeated, and the paint left open. The + /// library is also loaded in the Graphic Style Libraries panel and its styles applied to artwork. + #[test] + fn ai_style_libraries_of_one_paint_styles_never_panic( + // Each operator, and whether it is a paint operator rather than any text. + ops in prop::collection::vec(prop_oneof![ + prop::sample::select(vec![ + "0 R", "0 O", "0 1 1 0 K", "1 0 0 0 k", "0 0 0 0 1 0 0 Xa", "0 0 0 0 1 0 0 XA", "0.5 G", "0 g", "K", "Xa", + "0 J 0 j 2 w 10 M []0 d", "-1 w", "1e400 w", "0 M", "[3 -1]0 d", "[]0 d", + "1 0 Xd", "0 1 Xd", "1 1 Xd", "0 0 Xd", "1 Xd", "Xd", "0 1 0 0 0 Xy", "1 0.5 1 1 0 Xy", "Xy", + "0 Bb", "2 (Sky) 0 0 0 100 1 0 0 1 0 0 Bg", "0 BB", "(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p", + "(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] P", "0 XR", + ]).prop_map(|op| (op.to_string(), true)), + "[ -~]{0,12}".prop_map(|text| (text, false)), + ], 0..12), + closed in any::(), + ) { + use vectorcraft_testkit::ai; + let close = if closed { "/Paint ;\n/Def ;\n" } else { "" }; + // C, a red 2 pt stroke, comes first, so that it reads whatever A holds. + let header = format!( + "%AI9_BeginArtStyles\n/KnownStyle :\n(C) /Name ,\n/SimpleStyle :\n0 R\n0 1 1 0 K\n2 w\n1 0 Xd\n/Paint ;\n/Def ;\n\ + /KnownStyle :\n(A) /Name ,\n/SimpleStyle :\n{}\n{close}/KnownStyle :\n(B) /Name ,\n/SimpleStyle :\n1 0 Xd\n/Paint ;\n/Def ;\n\ + %AI9_EndArtStyles\n%AI9_BeginArtStyleList\n(A)\n(B)\n(C)\n%AI9_EndArtStyleList\n", + ops.iter().map(|(op, _)| op.as_str()).collect::>().join("\n") + ); + let library = ai::editing_data(200.0, 100.0, &header); + survive("one-paint style library", || Some(vectorcraft_eps::layered_ai(library.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; + let file = ai::ai(library.as_bytes(), ai::page_pdf()); + // How many objects C's look reached, what applying it answered, and whether that look is + // C's red 2 pt stroke with no fill. + let (mut styled, mut applied, mut red_stroke) = (0, Value::Null, false); + survive("one-paint styles applied", || { + let mut s = rich_session(); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&file), "name": "fuzz.ai"}); + let library = no_panic(s.execute("graphicStyle.loadLibrary", &p)).ok()?["library"].clone(); + no_panic(s.execute("select.all", &json!({}))).ok()?; + // Every style is added and the first one, A when it reads, applied; then C is applied. + let _ = no_panic(s.execute("graphicStyle.addFromLibrary", &json!({"library": library, "apply": true}))); + applied = no_panic(s.execute("graphicStyle.addFromLibrary", &json!({"library": library, "names": ["C"], "apply": true}))).ok()?; + let d = (*s.doc().ok()?.doc).clone(); + if let Some(look) = applied["applied"].as_str().and_then(|name| d.graphic_style(name)).map(|g| &g.appearance) { + let strokes = look.items.iter().filter(|i| matches!(i, vectorcraft_doc::AppearanceItem::Stroke(_))).count(); + red_stroke = look.fill().is_none() + && strokes == 1 + && look.stroke().is_some_and(|s| (s.paint.color(), s.width) == (Some(vectorcraft_color::Color::cmyk(0.0, 1.0, 1.0, 0.0)), 2.0)); + d.walk(|n| styled += usize::from(n.appearance == *look)); + } + Some(d) + })?; + // Text that isn't a paint operator can leave a string or a comment open over the style list. + if ops.iter().all(|(_, paint)| *paint) { + prop_assert!(applied["applied"].is_string() && red_stroke && styled > 0, "the stroke style wasn't applied: {applied}"); + } + } + /// Objects on Path records of any shape: ids in any order, repeated or missing, any number of /// objects, pivots and angles out of range or not finite, spacings, order tags that disagree, /// groups nested or cut short, and versioned content left open. diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index ed98d620bf..8c4e95f4e6 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -980,6 +980,34 @@ fn a_scaled_nine_slice_symbol_instance_keeps_its_corner_size() { assert!(sizes.contains(&(200, 150)), "the frame is scaled: {sizes:?}"); } +/// A scaled instance of a symbol whose left 9-slice guide lies outside its art is written as the +/// canvas draws it: the corner square is in the center column, which runs 0..75 in the art and +/// 0..175 in the instance, so it is about 23 wide. The editing copy read alone has no guides. +#[test] +fn a_nine_slice_instance_with_a_guide_outside_its_art_is_written_as_drawn() { + let mut doc = Document::new(400.0, 400.0); + let layer = doc.layers[0].id; + let square = |doc: &mut Document, r: Rect| { + Node::path(doc.alloc_id(), shapes::rectangle(r), Appearance::basic(solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0)) + }; + let frame = Arc::new(square(&mut doc, Rect::new(0.0, 0.0, 100.0, 100.0))); + let corner = Arc::new(square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0))); + let art = Node::group(doc.alloc_id(), vec![frame, corner]); + doc.symbols.push(Symbol { dynamic: false, name: "S".into(), art: Arc::new(art) }); + doc.set_symbol_nine_slice("S", vectorcraft_doc::SymbolNineSlice::new(-0.25, 0.25, 0.25, 0.25)); + let xf = Affine::scale_non_uniform(2.0, 1.5); + let instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "S".into(), xf }); + doc.insert(Some(layer), usize::MAX, instance).unwrap(); + let back = read_back(&doc); + let mut all = vec![]; + paths(back.layers[0].children().unwrap(), &mut all); + let sizes: Vec<(i64, i64)> = + all.iter().filter_map(|p| p.geometric_bounds()).map(|b| (b.width().round() as i64, b.height().round() as i64)).collect(); + assert!(sizes.contains(&(23, 10)), "the corner stretches with the center column: {sizes:?}"); + assert!(sizes.contains(&(200, 150)), "the frame is scaled: {sizes:?}"); + assert!(back.symbol_nine_slice("S").is_none()); +} + /// Nested symbols whose instances multiply, written as their art (on a large canvas), stop at /// [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects of symbol art in all, with a warning. #[test] diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index bc58858b91..9f6a1dd6af 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -1231,13 +1231,18 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p /// A graphic style's appearance from art style `st`, on no object: `None` when the style isn't one /// this reads, or paints with a gradient or a pattern (placed on each object as its drawn look has them). +/// A style that is one paint is its fill and stroke ([`crate::import::ai::style::ArtStyle::one_paint`]). pub(super) fn appearance_from_art_style(st: &crate::import::ai::style::ArtStyle) -> Option { use crate::import::ai::style::StyleItem; if !st.plain { return None; } + let style_items = match &st.one_paint { + Some(one) => one.as_ref().ok()?, + None => &st.items, + }; let mut items = vec![]; - for (n, item) in st.items.iter().enumerate() { + for (n, item) in style_items.iter().enumerate() { let mut layer = match item { StyleItem::Fill(paint) => AppearanceItem::Fill(FillLayer::new(paint.clone())), // A graphic style's brush isn't checked against the file's brushes: it is left out. diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs index 6a75837733..482c172386 100644 --- a/crates/eps/src/import/ai/style.rs +++ b/crates/eps/src/import/ai/style.rs @@ -32,6 +32,10 @@ //! gradient (`Bb` … `flag (name) x y angle length … Bg` … `BB`); `stroke fill Xd` says whether it //! paints at all. A blend filter's `mode opacity isolate knockout shape Xy` is its transparency. //! +//! A style with no filters is one paint (`/SimpleStyle :` … `/Paint ;` in place of `/ActiveStyle`): +//! the fill's and stroke's colors and the stroke's style as an object's own paint operators write +//! them, `stroke fill Xd` turning each on, and an `Xy` for its transparency. +//! //! A stroke with a Calligraphic or Art brush is its own basic filter, `(Adobe Calligraphic Brush //! Tool)` or `(Adobe ArtOnPath Brush Tool)`, with its stroke's style and the brush's settings for //! the object as entries (see [`super::brush`]). @@ -206,6 +210,11 @@ pub(super) struct ArtStyle { /// paint is a pattern: its [`StyleItem::Pattern`]. A text document's characters name such /// styles for their fills and strokes (`ate`). `None` for any other paint or style. pub simple_pattern: Option, + /// A style that is one paint: its fill and stroke, bottom first, each there when its + /// `stroke fill Xd` turns it on (none when neither is on). `Err` when it turns on a fill or + /// stroke whose paint isn't read here (a gradient, a pattern, a color that isn't read) or has + /// no `Xd`. `None` for a style with filters, whose paint is [`Self::items`]. + pub one_paint: Option, ()>>, } impl ArtStyle { @@ -412,12 +421,22 @@ pub(super) fn art_styles_in(data: &[u8], names: &mut Names) -> HashMap> = None; - let mut finish = |name: Option, filters: &mut Vec, simple_pattern: Option| { + // The same style's paint operators so far. + let mut one_paint: Option = None; + let mut finish = |name: Option, filters: &mut Vec, simple_pattern: Option, one_paint: Option| { if let Some(name) = name { // Only a style that is one paint holds a pattern for type: one with filters as well // paints with more than that. let simple_pattern = simple_pattern.filter(|_| filters.is_empty()); - styles.insert(name, ArtStyle { simple_pattern, ..style(filters) }); + let mut st = ArtStyle { simple_pattern, ..style(filters) }; + if let Some(one) = one_paint.filter(|_| filters.is_empty()) { + if let Some((mode, opacity)) = one.paint.xy { + let (isolate, knockout) = one.paint.xy_group.unwrap_or((false, Knockout::Off)); + st.transparency = Some((opacity, super::read::blend_mode(mode), isolate, knockout)); + } + st.one_paint = Some(one.items()); + } + styles.insert(name, st); } filters.clear(); }; @@ -454,12 +473,12 @@ pub(super) fn art_styles_in(data: &[u8], names: &mut Names) -> HashMap match n { b"KnownStyle" => { - finish(name.take(), &mut filters, simple.take().flatten()); + finish(name.take(), &mut filters, simple.take().flatten(), one_paint.take()); operands.clear(); open.clear(); (pending, in_basic, style_entry, other_entry) = (None, false, None, None); } - b"SimpleStyle" if filters.is_empty() => simple = Some(None), + b"SimpleStyle" if filters.is_empty() => (simple, one_paint) = (Some(None), Some(OnePaint::default())), b"FillStyle" => style_entry = Some(Kind::Fill), b"StrokeStyle" | b"BlendStyle" => style_entry = Some(Kind::Other), b"Name" if name.is_none() && filters.is_empty() => name = operands.iter().rev().find_map(|v| names.text(v)), @@ -559,7 +578,7 @@ pub(super) fn art_styles_in(data: &[u8], names: &mut Names) -> HashMap HashMap Option<(String, Option<[f6 } /// A paint operator in a style being read: one of the last filter's (`filters`), else one of a style -/// that is one paint (`simple`, while one is read). -fn style_paint_op(filters: &mut [Filter], simple: &mut Option>, op: &str, vals: &[V], names: &mut Names) { +/// that is one paint (`simple` and `one_paint`, while one is read). +fn style_paint_op( + filters: &mut [Filter], + simple: &mut Option>, + one_paint: &mut Option, + op: &str, + vals: &[V], + names: &mut Names, +) { if let Some(f) = filters.last_mut() { paint_op(f, op, vals, names); - } else if let Some(paint) = simple.as_mut() { + return; + } + if let Some(paint) = simple.as_mut() { simple_paint_op(paint, op, vals, names); } + if let Some(one) = one_paint.as_mut() { + one.op(op, vals, names); + } +} + +/// The paint operators of a style that is one paint (`/SimpleStyle :` … `/Paint ;`), read as a +/// fill's or stroke's style reads them. +#[derive(Default)] +struct OnePaint { + paint: Filter, + /// Its `stroke fill Xd` was read. + xd: bool, + /// Its last fill paint is a pattern (`p`) or may be a gradient (`Bg`). + fill_unread: bool, + /// Its last stroke paint is a pattern (`P`) or may be a gradient (`Bg`). + stroke_unread: bool, + /// Inside a gradient instance (`flag Bb` … `BB`): whether it paints the stroke (flag 1). + instance: Option, +} + +impl OnePaint { + fn op(&mut self, op: &str, vals: &[V], names: &mut Names) { + match op { + "Xd" => self.xd |= vals.iter().filter_map(V::num).count() >= 2, + "p" => self.fill_unread = true, + "P" => self.stroke_unread = true, + // The flag of the instance it is in says which one it paints, as an object's does + // (`Instance::begin` in `paint.rs`); outside one it is read as either one's. + "Bb" => self.instance = Some(vals.iter().filter_map(V::num).next_back() == Some(1.0)), + "BB" => self.instance = None, + "Bg" => match self.instance { + Some(true) => self.stroke_unread = true, + Some(false) => self.fill_unread = true, + None => (self.fill_unread, self.stroke_unread) = (true, true), + }, + // A color replaces what came before it; one that isn't read leaves none. + "Xa" | "k" | "g" | "x" | "Xx" | "Xk" | "Xs" | "Xz" | "xa" | "xx" | "xk" | "xs" | "xz" => { + (self.fill_unread, self.paint.fill) = (false, None); + } + "XA" | "K" | "G" | "X" | "XX" | "XK" | "XS" | "XZ" => (self.stroke_unread, self.paint.stroke) = (false, None), + _ => {} + } + paint_op(&mut self.paint, op, vals, names); + } + + /// Its fill and stroke ([`ArtStyle::one_paint`]). + fn items(&self) -> Result, ()> { + let f = &self.paint; + if !self.xd { + return Err(()); + } + let (stroked, filled) = f.paints; + let mut items = vec![]; + if filled { + match &f.fill { + Some(p) if !self.fill_unread => items.push(StyleItem::Fill(p.clone())), + _ => return Err(()), + } + } + if stroked { + match &f.stroke { + Some(p) if !self.stroke_unread => items.push(StyleItem::Stroke { + paint: p.clone(), + width: f.width, + cap: f.cap, + join: f.join, + miter: f.miter, + dash: f.dash.clone(), + profile: None, + align: StrokeAlign::Center, + brush: None, + }), + _ => return Err(()), + } + } + Ok(items) + } } /// A paint operator of a style that is one paint: a pattern (`p`) is kept as its diff --git a/crates/eps/src/import/ai/style/tests.rs b/crates/eps/src/import/ai/style/tests.rs index c6debd42f9..ea8428809c 100644 --- a/crates/eps/src/import/ai/style/tests.rs +++ b/crates/eps/src/import/ai/style/tests.rs @@ -1512,3 +1512,48 @@ fn only_a_style_of_one_pattern_paint_holds_a_pattern_for_type() { assert!(styles(&body).get("S").is_none_or(|s| s.simple_pattern.is_none()), "{body}"); } } + +/// A style that is one paint reads as the fill and stroke its `Xd` turns on, in the paint's colors +/// and the stroke's style; one that turns on a paint not read here, or has no `Xd`, isn't read. +#[test] +fn a_style_of_one_paint_reads_as_the_fill_and_stroke_its_xd_turns_on() { + let one = |paint: &str| { + let data = format!("/KnownStyle :\n(S) /Name ,\n/SimpleStyle :\n{paint}/Paint ;\n/Def ;\n"); + art_styles_in(data.as_bytes(), &mut Names::default()).remove("S").and_then(|s| s.one_paint) + }; + let stroke = "0 R\n0 1 1 0 K\n1 J 2 j 3 w 4 M [2 1]0 d\n"; + let Some(Ok(items)) = one(&format!("0 O\n0 0 1 0 k\n{stroke}1 1 Xd\n")) else { panic!("{:?}", one(stroke)) }; + let [StyleItem::Fill(fill), StyleItem::Stroke { paint, width, cap, join, miter, dash, profile: None, align: StrokeAlign::Center, brush: None }] = + items.as_slice() + else { + panic!("{items:?}") + }; + assert_eq!((fill.color(), paint.color()), (Some(Color::cmyk(0.0, 0.0, 1.0, 0.0)), Some(Color::cmyk(0.0, 1.0, 1.0, 0.0)))); + assert_eq!((*width, *cap, *join, *miter), (3.0, LineCap::Round, LineJoin::Bevel, 4.0)); + assert_eq!(dash.as_ref().map(|d| d.pattern.clone()), Some(vec![2.0, 1.0])); + // Only what `Xd` turns on; nothing when it turns on neither. + assert!(matches!(one(&format!("0 0 1 0 k\n{stroke}1 0 Xd\n")), Some(Ok(i)) if matches!(i.as_slice(), [StyleItem::Stroke { .. }]))); + assert_eq!(one(&format!("0 0 1 0 k\n{stroke}0 0 Xd\n")), Some(Ok(vec![]))); + // The last paint of each one counts: a solid color after a pattern or a gradient replaces it. + let solid_fill = |before: &str| one(&format!("{before}\n0 0 1 0 k\n0 1 Xd\n")); + for before in ["(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p", "0 Bb\n2 (Sky) 0 0 0 100 1 0 0 1 0 0 Bg\n0 BB"] { + assert!(matches!(solid_fill(before), Some(Ok(i)) if matches!(i.as_slice(), [StyleItem::Fill(_)])), "{before}"); + } + let solid_stroke = one("(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] P\n0 1 1 0 K\n1 0 Xd\n"); + assert!(matches!(solid_stroke, Some(Ok(i)) if matches!(i.as_slice(), [StyleItem::Stroke { .. }]))); + // A gradient instance's flag says which one it paints: a stroke gradient leaves a solid fill read. + let fill_and_stroke_gradient = one("0 0 1 0 k\n1 Bb\n2 (Ramp) 0 0 90 1 1 0 0 1 0 0 1 Bg\n0 BB\n0 1 Xd\n"); + assert!(matches!(fill_and_stroke_gradient, Some(Ok(i)) if matches!(i.as_slice(), [StyleItem::Fill(_)]))); + // Not read: no `Xd`, a gradient or pattern fill, a pattern stroke, a gradient stroke after a solid one, a paint + // turned on with no color. + for paint in [ + format!("0 0 1 0 k\n{stroke}"), + "0 Bb\n2 (Sky) 0 0 0 100 1 0 0 1 0 0 Bg\n0 BB\n0 1 Xd\n".to_string(), + "(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n0 1 Xd\n".to_string(), + "(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] P\n1 0 Xd\n".to_string(), + "0 R\n0 1 1 0 K\n1 Bb\n0 0 0 0 Bh\n2 (Ramp) 0 0 90 1 1 0 0 1 0 0 1 Bg\n0 BB\n2 w\n1 0 Xd\n".to_string(), + "0 0 1 0 k\n1 1 Xd\n".to_string(), + ] { + assert_eq!(one(&paint), Some(Err(())), "{paint}"); + } +} diff --git a/crates/svg/tests/it/symbols_layers.rs b/crates/svg/tests/it/symbols_layers.rs index 3e58b02286..8e83b6262e 100644 --- a/crates/svg/tests/it/symbols_layers.rs +++ b/crates/svg/tests/it/symbols_layers.rs @@ -115,6 +115,41 @@ fn a_scaled_nine_slice_instance_is_written_as_the_canvas_draws_it() { assert_similar(&canvas, &resvg_render(&svg, 300, 200), 24.0, 0.002); } +/// A scaled instance of a symbol whose left 9-slice guide lies outside its art is written as the +/// canvas draws it: the corner square is in the stretched center column. Reading the file back +/// gives that art and no 9-slice guides, which SVG has no place for. +#[test] +fn a_nine_slice_instance_with_a_guide_outside_its_art_is_written_as_drawn() { + let mut d = Document::new(300.0, 200.0); + let fill = |c: Color| Appearance::basic(Paint::solid(c), Paint::None, 0.0); + let rects = [(Rect::new(0.0, 0.0, 100.0, 100.0), Color::rgb8(220, 220, 220)), (Rect::new(0.0, 0.0, 10.0, 10.0), Color::BLACK)]; + let art: Vec> = rects.iter().map(|(r, c)| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(*r), fill(*c)))).collect(); + let group = Node::group(d.alloc_id(), art); + d.symbols.push(Symbol { dynamic: false, name: "Panel".into(), art: Arc::new(group) }); + d.set_symbol_nine_slice("Panel", vectorcraft_doc::SymbolNineSlice::new(-0.25, 0.25, 0.25, 0.25)); + instance(&mut d, "Panel", Affine::translate((20.0, 20.0)) * Affine::scale_non_uniform(2.0, 1.5)); + let svg = export(&d, &ExportOptions::default()); + assert_eq!(svg.matches(" Vec, String>> { - inflate_faces(shapes, bounds, options, view, false).map(|r| r.map(|(facets, ..)| facets)).collect() + inflate_each(shapes, bounds, options, view).collect() +} + +/// [`inflate_together`], each solid built only as the iterator reaches it: a caller that stops early +/// builds none of the solids after. +pub fn inflate_each( + shapes: &[(&PathData, FillRule)], + bounds: Rect, + options: Inflate, + view: View, +) -> impl Iterator, String>> + use<> { + inflate_faces(shapes, bounds, options, view, false).map(|r| r.map(|(facets, ..)| facets)) } /// [`inflate_together`], or with `mesh` each solid's faces before projection instead of its facets. diff --git a/crates/three-d/src/solid/rings.rs b/crates/three-d/src/solid/rings.rs index 7aed5e4191..80dc66407c 100644 --- a/crates/three-d/src/solid/rings.rs +++ b/crates/three-d/src/solid/rings.rs @@ -17,7 +17,9 @@ pub(super) const CURVE_PIECES: u32 = 32; pub(super) const MIN_CURVE_PIECES: u32 = 4; const TOO_COMPLEX_SHAPE: &str = "The shape is too complex for a 3D effect"; -pub(super) const TOO_COMPLEX_SURFACE: &str = "The 3D surface is too complex; simplify the shape"; +/// The error a solid past its limits returns, and a 3D effect whose solids together pass +/// [`crate::MAX_OBJECT_FACES`]. +pub const TOO_COMPLEX_SURFACE: &str = "The 3D surface is too complex; simplify the shape"; /// How many straight pieces follow `c` within `tolerance` (Wang's bound on a cubic's distance from /// its chords), 1 to [`CURVE_PIECES`]. diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index 292f1d25e8..3addd48785 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -28,7 +28,7 @@ //! Direct Selection also edits a blend's spine: drag its points (Shift-click picks several, which //! drag together; a key object on a point moves with it) and, once a point is clicked, its //! handles; and the points of selected gradient meshes -//! and mesh envelopes and their handles ([`MeshEdit`]): Shift-clicks and the marquee pick several, +//! and of mesh and warp envelopes and their handles ([`MeshEdit`]): Shift-clicks and the marquee pick several, //! a click on a gradient mesh's line picks its two ends and one inside a patch the four points //! around it, a drag of picked points moves them all, the arrow keys nudge them, and a solid fill //! colour or the Transparency panel's opacity goes to a gradient mesh's picked points. Dragging a diff --git a/crates/tools/src/meshblend.rs b/crates/tools/src/meshblend.rs index d61eb95f5f..21ee30eed6 100644 --- a/crates/tools/src/meshblend.rs +++ b/crates/tools/src/meshblend.rs @@ -21,7 +21,7 @@ use vectorcraft_doc::{NodeId, NodeKind}; use vectorcraft_geom::Point; use crate::blendwidget::{self, BlendWidgetDrag}; -use crate::meshedit::{MeshEdit, grid_of}; +use crate::meshedit::{MeshEdit, grid_of, may_have_grid}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; const FEEDBACK: [u8; 3] = [0x4f, 0x9d, 0xff]; @@ -246,13 +246,13 @@ pub struct MeshTool { } impl MeshTool { - /// Meshes (gradient meshes and mesh envelopes) to consider for point hits: selected ones - /// first, then any in the document. + /// Meshes (gradient meshes, and mesh and warp envelopes) to consider for point hits: selected + /// ones first, then any in the document. fn meshes(cx: &ToolContext) -> Vec { - let mut v: Vec = cx.selection.objects.iter().copied().filter(|id| cx.doc.node(*id).and_then(grid_of).is_some()).collect(); + let mut v: Vec = cx.selection.objects.iter().copied().filter(|id| cx.doc.node(*id).is_some_and(may_have_grid)).collect(); let mut rest = vec![]; cx.doc.walk(|n| { - if grid_of(n).is_some() { + if may_have_grid(n) { rest.push(n.id); } }); diff --git a/crates/tools/src/meshedit.rs b/crates/tools/src/meshedit.rs index c0c1d96231..1069c90eb5 100644 --- a/crates/tools/src/meshedit.rs +++ b/crates/tools/src/meshedit.rs @@ -1,5 +1,5 @@ //! Picking and dragging mesh points and their handles on the canvas, shared by the Mesh tool and -//! Direct Selection: gradient meshes and mesh envelopes alike. A click on a point picks it alone +//! Direct Selection: gradient meshes, mesh envelopes and warp envelopes alike. A click on a point picks it alone //! and focuses it: its handles show and can be dragged too. Shift-clicks add points to the picked //! ones or take them away, and Direct Selection's marquee and its clicks on a gradient mesh's line //! or patch pick points too ([`part_points`]). The picked points show filled; a drag of one of @@ -11,7 +11,7 @@ use std::borrow::Cow; use std::collections::BTreeSet; use serde_json::{Value, json}; -use vectorcraft_doc::live::{GradientMesh, envelope_grid}; +use vectorcraft_doc::live::{GradientMesh, envelope_grid, warp_grid}; use vectorcraft_doc::{EnvelopeKind, Node, NodeId, NodeKind}; use vectorcraft_geom::{Point, Vec2}; @@ -19,19 +19,30 @@ use crate::{Action, Mods, Overlay, ToolContext, ToolKey}; const FEEDBACK: [u8; 3] = [0x4f, 0x9d, 0xff]; -/// The editable grid of `n`: a gradient mesh, or a mesh envelope's grid (not while its contents -/// are being edited). +/// The editable grid of `n`: a gradient mesh, a mesh envelope's grid or a warp envelope's +/// ([`warp_grid`], which its first edit makes a mesh envelope of); not while an envelope's contents +/// are being edited. pub fn grid_of(n: &Node) -> Option> { match &n.kind { NodeKind::Mesh(m) => Some(Cow::Borrowed(m)), NodeKind::Envelope { kind, editing: false, .. } => match &**kind { EnvelopeKind::Mesh { rows, cols, points, handles } => envelope_grid(*rows, *cols, points, handles).map(Cow::Owned), - _ => None, + EnvelopeKind::Warp { .. } => warp_grid(n).map(Cow::Owned), + EnvelopeKind::TopObject { .. } => None, }, _ => None, } } +/// Can `n` have an editable grid ([`grid_of`])? Its kind alone answers, without building the grid. +pub fn may_have_grid(n: &Node) -> bool { + match &n.kind { + NodeKind::Mesh(_) => true, + NodeKind::Envelope { kind, editing: false, .. } => matches!(**kind, EnvelopeKind::Mesh { .. } | EnvelopeKind::Warp { .. }), + _ => false, + } +} + /// The points of gradient mesh `m` a Direct Selection click at `p` picks: the point within /// `point_tol`, else the two ends of the mesh line within `line_tol`, else the four points around /// the patch under `p`. @@ -433,6 +444,55 @@ mod tests { assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 90.0, 210.0)), vec![Action::Commit]); } + /// The rectangle of [`doc_with_rect`] in an arc warp envelope. + fn doc_with_warp() -> (Document, NodeId) { + let (mut d, e) = doc_with_envelope(); + if let Some(NodeKind::Envelope { kind, .. }) = d.node_mut(e).map(|n| &mut n.kind) { + **kind = + EnvelopeKind::Warp { style: "arc".into(), bend: 50.0, h: 0.0, v: 0.0, horizontal: true, version: vectorcraft_doc::live::WARP_NET }; + } + (d, e) + } + + /// The Mesh tool and Direct Selection drag a warp envelope's points (on its grid) and the + /// clicked point's handles, as they do a mesh envelope's; while its contents are edited, its + /// points take no press. + #[test] + fn the_mesh_tool_and_direct_selection_drag_warp_envelope_points() { + let (mut d, e) = doc_with_warp(); + let grid = grid_of(d.node(e).unwrap()).unwrap().into_owned(); + assert_eq!(Some(&grid), warp_grid(d.node(e).unwrap()).as_ref()); + let mut s = Selection::default(); + s.set([e]); + let p = paint(); + let c = cx(&d, &s, &p); + let tools: [(&str, Box); 2] = + [("mesh", crate::meshblend::create("mesh").unwrap()), ("directSelection", Box::new(crate::direct::DirectSelectionTool::new(false)))]; + let (i, q) = (6, grid.points[6].clone()); + for (what, mut t) in tools { + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, q.p.x, q.p.y)), vec![Action::Begin("Move Mesh Point".into())], "{what}"); + assert_eq!( + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, q.p.x + 10.0, q.p.y - 10.0)), + vec![Action::Preview("object.mesh.movePoint".into(), json!({"id": e.0, "index": i, "x": q.p.x + 10.0, "y": q.p.y - 10.0}))], + "{what}" + ); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, q.p.x + 10.0, q.p.y - 10.0)), vec![Action::Commit], "{what}"); + // The clicked point's handle. + let end = q.p + q.handles[0]; + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, end.x, end.y)), vec![Action::Begin("Move Mesh Point".into())], "{what}"); + let drag = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, end.x + 5.0, end.y)); + assert!(matches!(&drag[..], [Action::Preview(id, p)] if id == "object.mesh.movePoint" && p["handle"] == json!(0)), "{what}: {drag:?}"); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, end.x + 5.0, end.y)); + } + if let Some(NodeKind::Envelope { editing, .. }) = d.node_mut(e).map(|n| &mut n.kind) { + *editing = true; + } + assert!(grid_of(d.node(e).unwrap()).is_none(), "Edit Contents: no envelope points"); + let c = cx(&d, &s, &p); + let mut t = crate::meshblend::create("mesh").unwrap(); + assert_ne!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, q.p.x, q.p.y)), vec![Action::Begin("Move Mesh Point".into())]); + } + #[test] fn mesh_drag_honors_measurement_labels() { let (d, _e) = doc_with_envelope(); diff --git a/crates/tools/src/nineslice.rs b/crates/tools/src/nineslice.rs index 61de9e9580..74f40b6bbf 100644 --- a/crates/tools/src/nineslice.rs +++ b/crates/tools/src/nineslice.rs @@ -5,10 +5,15 @@ //! takes the Move cursor, and dragging the guide moves it (`symbol.options`'s //! `nineSliceGuides`), in one undo step. //! -//! VectorCraft's own rules: a guide stays within the art's box and stops short of the opposite -//! guide; the drag does not snap and its modifiers change nothing; a guide within reach takes the -//! press before the art and the bounding box, and of two guides within reach the nearer one, else -//! the first of left, top, right and bottom; Escape during the drag puts the guide back. +//! A guide may be dragged past the art's edges, and the instance still scales by the slices its +//! art falls in. +//! +//! VectorCraft's own rules: a guide stays within 16 times the art's width or height of its edge +//! and stops short of the opposite guide; a guide outside the art is drawn and taken along the +//! art's height or width beside it; the drag does not snap and its modifiers change nothing; a +//! guide within reach takes the press before the art and the bounding box, and of two guides +//! within reach the nearer one, else the first of left, top, right and bottom; Escape during the +//! drag puts the guide back. use serde_json::json; use vectorcraft_doc::{EditedNineSlice, NineSliceGuide}; @@ -203,6 +208,36 @@ mod tests { assert_eq!(preview(&a[1]).1["nineSliceGuides"], json!([0.25, 0.4, 0.25, 0.25])); } + /// A guide outside the art is taken beside the art, along its height, and a drag may take a + /// guide past the art's edge and back; Escape puts it back where it was. + #[test] + fn a_guide_outside_the_art_is_taken_and_dragged_past_the_arts_edge() { + let d = editing(SymbolNineSlice::new(-0.25, 0.25, 0.25, 0.25)); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let at = |x: f64, y: f64| guide_at(&c, Point::new(x, y)).map(|(_, g)| g); + assert_eq!(at(75.0, 150.0), Some(NineSliceGuide::Left), "25 % left of the art at x = 100"); + assert_eq!(at(77.0, 110.0), Some(NineSliceGuide::Left)); + assert_eq!(at(75.0, 95.0), None, "the guide ends with the art's height"); + let mut t = SelectionTool::default(); + assert_eq!(t.cursor(&c, Point::new(75.0, 150.0), Mods::default()), Cursor::Move); + t.pointer(&c, &ev(PointerKind::Down, 75.0, 150.0)); + let a = t.pointer(&c, &ev(PointerKind::Drag, 50.0, 150.0)); + assert_eq!(a[0], Action::Begin("Symbol Options".into())); + assert_eq!(preview(&a[1]).1["nineSliceGuides"], json!([-0.5, 0.25, 0.25, 0.25])); + let (_, v) = preview(&t.pointer(&c, &ev(PointerKind::Drag, 110.0, 150.0))[0]); + assert_eq!(v["nineSliceGuides"], json!([0.1, 0.25, 0.25, 0.25]), "back inside the art"); + assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::Cancel]); + // From inside the art, the default bottom guide passes the art's bottom edge at y = 200. + let d = editing(Some(SymbolNineSlice::default())); + let c = cx(&d, &s, &p); + let mut t = SelectionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, 150.0, 175.0)); + let a = t.pointer(&c, &ev(PointerKind::Drag, 150.0, 250.0)); + assert_eq!(preview(&a[1]).1["nineSliceGuides"], json!([0.25, 0.25, 0.25, -0.5])); + assert_eq!(t.pointer(&c, &ev(PointerKind::Up, 150.0, 250.0)), vec![Action::Commit]); + } + /// Escape during a guide drag cancels it and is the tool's; the release after it commits /// nothing. A double-click on a guide neither edits the art nor leaves the mode. #[test] diff --git a/crates/trace/src/centerline.rs b/crates/trace/src/centerline.rs index 332c4499c3..852bdb1858 100644 --- a/crates/trace/src/centerline.rs +++ b/crates/trace/src/centerline.rs @@ -4,7 +4,10 @@ //! 1. **Distance**: an exact Euclidean distance transform in each blob crop gives each pixel //! its distance to the nearest pixel outside the blob. //! 2. **Lines**: an 8-connected component whose widest point (twice its largest distance, less -//! one) is within the stroke width is a line; wider ones stay filled areas. +//! one) is within the stroke width is a line. A wider one keeps as its area every disc wider +//! than the stroke width that fits in it; each piece outside those discs that reaches out of +//! them at least one and a half times its own width (and 3 px) is a thin feature of it, and a +//! line, whose end at the area goes to the cut, its cap reaching into the area. //! 3. **Skeleton**: Guo–Hall thins the crop to one pixel, preserving diagonal ends, then //! staircase corners that don't connect anything are dropped. //! 4. **Graph**: runs of skeleton pixels between ends and junctions (touching junction pixels @@ -93,20 +96,111 @@ pub(crate) fn lines( cells_left = left; let Some(dt) = distance::squared(&g.on, g.w, g.h) else { continue }; let widest = 2.0 * f64::from(dt.iter().copied().fold(0.0f32, f32::max)).sqrt() - 1.0; - if widest > max_width { - continue; - } - let Some(line) = trace_line(g, &dt, comp.len(), max_width, img, ink, style) else { continue }; - for &i in &comp { - if let Some(v) = thin.get_mut(i) { - *v = true; + let found = if widest > max_width { + // A wider shape keeps its wide part as an area; its thin features are lines. + arm_lines(&g, &dt, w, max_width, img, ink, style, &mut cells_left) + } else { + trace_line(g, &dt, comp.len(), max_width, img, ink, style, None).map(|line| (comp, line)).into_iter().collect() + }; + for (pixels, line) in found { + for &i in &pixels { + if let Some(v) = thin.get_mut(i) { + *v = true; + } } + out.push(line); } - out.push(line); } (thin, out) } +/// The thin features of component `g` (wider than `max_width` somewhere; `dt` its distances), traced +/// as lines, each with its pixels (indices of the `w`-wide image). A feature that cannot be traced, or +/// past the work left in `cells_left`, stays part of the area. +#[allow(clippy::too_many_arguments)] +fn arm_lines( + g: &Grid, + dt: &[f32], + w: usize, + max_width: f64, + img: &Raster, + ink: [f64; 3], + style: &Style, + cells_left: &mut usize, +) -> Vec<(Vec, Line)> { + let mut out = vec![]; + for arm in arms(g, dt, w, max_width).unwrap_or_default() { + let pixels: Vec = arm.iter().map(|&(i, _)| i).collect(); + let Some(ag) = Grid::from_component(&pixels, w) else { continue }; + let Some(left) = cells_left.checked_sub(ag.w.saturating_mul(ag.h)) else { break }; + *cells_left = left; + let mut cut = vec![false; ag.on.len()]; + for &(i, at_cut) in &arm { + if let Some(c) = ag.index(i, w).and_then(|k| cut.get_mut(k)) { + *c = at_cut; + } + } + let Some(adt) = distance::squared(&ag.on, ag.w, ag.h) else { continue }; + if 2.0 * f64::from(adt.iter().copied().fold(0.0f32, f32::max)).sqrt() - 1.0 > max_width { + continue; + } + if let Some(line) = trace_line(ag, &adt, pixels.len(), max_width, img, ink, style, Some(&cut)) { + out.push((pixels, line)); + } + } + out +} + +/// The thin features of component `g`, which is wider than `max_width` somewhere (`dt` its squared +/// distances to the paper): the pieces of it that lie outside every disc wider than `max_width` +/// that fits in it (the component opened by such a disc) and reach out of those discs at least one +/// and a half times their own width (and 3 px). The rest, with the slivers and corners the discs +/// leave, is the area. Each piece is a list of its pixels (indices of the `w`-wide image), each +/// marked when it touches the area (where the line is cut from it). +fn arms(g: &Grid, dt: &[f32], w: usize, max_width: f64) -> Option>> { + let r = (max_width + 1.0) / 2.0; + let seeds: Vec = dt.iter().map(|&d| f64::from(d) > r * r).collect(); + let near = distance::to_seeds(&seeds, g.w, g.h)?; + drop(seeds); + // (Half a pixel more than the discs' radius, so pixels the discs cut through are area.) + let cover = r + 0.5; + let rest = |i: usize| g.on.get(i) == Some(&true) && near.get(i).is_some_and(|&d| f64::from(d) > cover * cover); + let mut seen = vec![false; g.on.len()]; + let (mut out, mut stack) = (vec![], vec![]); + for start in g.interior() { + if !rest(start) || seen.get(start).copied().unwrap_or(true) { + continue; + } + let mut piece = vec![]; + *seen.get_mut(start)? = true; + stack.push(start); + while let Some(i) = stack.pop() { + let mut at_cut = false; + for j in g.neighbours(i) { + if !rest(j) { + at_cut = true; + } else if !seen.get(j).copied().unwrap_or(true) { + *seen.get_mut(j)? = true; + stack.push(j); + } + } + piece.push((i, at_cut)); + } + let deepest = piece.iter().filter_map(|&(i, _)| dt.get(i)).copied().fold(0.0f32, f32::max); + let width = (2.0 * f64::from(deepest).sqrt() - 1.0).max(1.0); + let farthest = piece.iter().filter_map(|&(i, _)| near.get(i)).copied().fold(0.0f32, f32::max); + if f64::from(farthest).sqrt() - cover < (1.5 * width).max(3.0) { + continue; + } + let image = |i: usize| { + let (x, y) = (usize::try_from(g.x0 + (i % g.w) as i64).ok()?, usize::try_from(g.y0 + (i / g.w) as i64).ok()?); + y.checked_mul(w)?.checked_add(x) + }; + out.push(piece.into_iter().map(|(i, at_cut)| Some((image(i)?, at_cut))).collect::>>()?); + } + Some(out) +} + /// The 8 neighbours of pixel `i` inside the `w` × `h` image. fn neighbours(i: usize, w: usize, h: usize) -> impl Iterator { let (x, y) = ((i % w) as i64, (i / w) as i64); @@ -163,6 +257,23 @@ impl Grid { let comp: Vec<_> = mask.iter().enumerate().filter_map(|(i, &on)| on.then_some(i)).collect(); Self::from_component(&comp, w) } + /// The grid index of pixel `i` of the `image_width`-wide image, when the grid holds it. + fn index(&self, i: usize, image_width: usize) -> Option { + let (x, y) = (i64::try_from(i % image_width.max(1)).ok()? - self.x0, i64::try_from(i / image_width.max(1)).ok()? - self.y0); + let (x, y) = (usize::try_from(x).ok()?, usize::try_from(y).ok()?); + (x < self.w && y < self.h).then(|| y * self.w + x) + } + /// Whether a pixel `cut` marks (`cut` is laid out as the grid) has its center within `radius` of + /// `p` (image coordinates). + fn near_cut(&self, cut: &[bool], p: Point, radius: f64) -> bool { + if !p.x.is_finite() || !p.y.is_finite() || !radius.is_finite() { + return false; + } + let (cx, cy) = (p.x - self.x0 as f64 - 0.5, p.y - self.y0 as f64 - 0.5); + let span = |c: f64, n: usize| ((c - radius).floor().max(0.0) as usize, ((c + radius).ceil().max(0.0) as usize).min(n.saturating_sub(1))); + let ((x0, x1), (y0, y1)) = (span(cx, self.w), span(cy, self.h)); + (y0..=y1).any(|y| (x0..=x1).any(|x| (x as f64 - cx).hypot(y as f64 - cy) <= radius && cut.get(y * self.w + x).copied().unwrap_or(false))) + } fn offsets(&self) -> [isize; 8] { let w = self.w as isize; [-w, -w + 1, 1, w + 1, w, w - 1, -1, -w - 1] @@ -193,8 +304,20 @@ impl Grid { } } -/// The centre lines of one line component (pixel indices of the `w`-wide image). -fn trace_line(mut g: Grid, dist: &[f32], pixels: usize, max_width: f64, img: &Raster, ink: [f64; 3], style: &Style) -> Option { +/// The center lines of one line component (pixel indices of the `w`-wide image). `cut`, for a thin +/// feature of a wider shape, marks (in `g`) its pixels that touch the shape's area: an end there is +/// not an end of the ink, and goes to the cut, its cap reaching into the area. +#[allow(clippy::too_many_arguments)] +fn trace_line( + mut g: Grid, + dist: &[f32], + pixels: usize, + max_width: f64, + img: &Raster, + ink: [f64; 3], + style: &Style, + cut: Option<&[bool]>, +) -> Option { thin::thin(&mut g); let mut graph = graph::build(&g, dist)?; graph.simplify(max_width)?; @@ -268,7 +391,9 @@ fn trace_line(mut g: Grid, dist: &[f32], pixels: usize, max_width: f64, img: &Ra // to a few degrees at best, less without anti-aliasing, and an end already on it is // better left where it is.) let before = inner - *r.pts.get(at(2 * back))?; - let wide = width >= 3.0 && n > 2 * back && before.cross(tip - inner).abs() > (0.25 * width).max(1.0) * before.hypot(); + // (At a cut from a wider shape, where the skeleton turns along the cut.) + let joined = cut.is_some_and(|cut| g.near_cut(cut, tip, width / 2.0 + 1.5)); + let wide = width >= 3.0 && n > 2 * back && (joined || before.cross(tip - inner).abs() > (0.25 * width).max(1.0) * before.hypot()); let d = if wide { before } else { tip - inner }; if d.hypot() < 1e-9 { continue; @@ -282,6 +407,11 @@ fn trace_line(mut g: Grid, dist: &[f32], pixels: usize, max_width: f64, img: &Ra } } let tip = on_line(tip); + if joined { + // The skeleton stops about half a width short of the cut. + *r.pts.get_mut(at(0))? = tip + along * (width / 2.0 + 0.5); + continue; + } let reach = ink.beyond(tip, along); if width >= 3.0 { let aside = kurbo::Vec2::new(-along.y, along.x) * (0.35 * width); diff --git a/crates/trace/src/centerline/distance.rs b/crates/trace/src/centerline/distance.rs index d357c7d681..8e7f595dd4 100644 --- a/crates/trace/src/centerline/distance.rs +++ b/crates/trace/src/centerline/distance.rs @@ -40,7 +40,21 @@ pub(super) fn squared(mask: &[bool], w: usize, h: usize) -> Option> { if mask.len() != size || mask.iter().enumerate().any(|(i, &on)| on && (i < w || i >= size - w || i % w == 0 || i % w + 1 == w)) { return None; } - let mut grid: Vec = mask.iter().map(|&on| if on { FAR } else { 0.0 }).collect(); + two_passes(mask.iter().map(|&on| if on { FAR } else { 0.0 }).collect(), w, h) +} + +/// Squared distances from each pixel of a validated crop to the nearest `seeds` pixel (a very large +/// value everywhere when there is none). +pub(super) fn to_seeds(seeds: &[bool], w: usize, h: usize) -> Option> { + let size = super::crop_size(w, h)?; + if seeds.len() != size { + return None; + } + two_passes(seeds.iter().map(|&seed| if seed { 0.0 } else { FAR }).collect(), w, h) +} + +/// The column pass and then the row pass over `grid` (0 at a seed, `FAR` elsewhere). +fn two_passes(mut grid: Vec, w: usize, h: usize) -> Option> { let n = w.max(h); let (mut f, mut d, mut envelope) = (vec![0.0; n], vec![0.0; n], Vec::with_capacity(n)); for x in 0..w { @@ -97,6 +111,38 @@ mod tests { } } + #[test] + fn distances_to_seeds_equal_brute_force() { + let mut seed = 7u64; + let mut rnd = || { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1); + (seed >> 33) as usize + }; + for case in 0..100 { + let (w, h) = (3 + rnd() % 20, 3 + rnd() % 20); + let seeds: Vec = (0..w * h).map(|_| rnd() % 9 == 0).collect(); + let d = to_seeds(&seeds, w, h).unwrap(); + for (i, &actual) in d.iter().enumerate() { + let expected = seeds + .iter() + .enumerate() + .filter(|&(_, &s)| s) + .map(|(j, _)| { + let dx = (i % w).abs_diff(j % w); + let dy = (i / w).abs_diff(j / w); + (dx * dx + dy * dy) as f32 + }) + .min_by(f32::total_cmp); + match expected { + Some(e) => assert_eq!(actual, e, "case {case}, pixel {i}"), + None => assert!(actual > 1e18, "case {case}: no seed, pixel {i} at {actual}"), + } + } + } + assert!(to_seeds(&[true; 8], 3, 3).is_none()); + assert!(to_seeds(&[], 2, 2).is_none()); + } + #[test] fn invalid_crops_are_refused() { assert!(squared(&[], 0, 0).is_none()); diff --git a/crates/trace/src/params.rs b/crates/trace/src/params.rs index 6073fa04fe..a6676cd696 100644 --- a/crates/trace/src/params.rs +++ b/crates/trace/src/params.rs @@ -114,7 +114,8 @@ pub struct TraceParams { pub gradients: bool, /// Create: trace areas as filled shapes. pub fills: bool, - /// Create: trace lines no wider than `stroke_width` as stroked centre lines. + /// Create: trace lines no wider than `stroke_width`, and such thin features of wider shapes, as + /// stroked center lines. pub strokes: bool, /// Stroke: the widest feature (px) traced as a stroke. pub stroke_width: f64, diff --git a/crates/trace/src/tests.rs b/crates/trace/src/tests.rs index f6176cdd6f..d0a589b916 100644 --- a/crates/trace/src/tests.rs +++ b/crates/trace/src/tests.rs @@ -932,6 +932,66 @@ fn wide_areas_stay_filled_and_lines_cross_at_junctions() { assert!(res.paths.iter().any(|p| p.stroke == Some(1.0) && p.path.subpaths[0].closed), "the disc's outline"); } +#[test] +fn thin_features_of_a_wide_shape_are_strokes_and_its_body_a_fill() { + // A disc (r = 20) with a 3 px wide arm from it out to x = 140 and a 5 px wide one up to y = 5. + let img = Raster::from_fn(160, 100, |x, y| { + let (px, py) = (x as f64 + 0.5, y as f64 + 0.5); + let disc = (px - 50.0).hypot(py - 60.0) <= 20.0; + let across = (py - 60.0).abs() <= 1.5 && (50.0..=140.0).contains(&px); + let up = (px - 50.0).abs() <= 2.5 && (5.0..=60.0).contains(&py); + if disc || across || up { BLACK } else { WHITE } + }); + let res = trace(&img, &strokes(true)); + let fills: Vec<_> = res.paths.iter().filter(|p| p.stroke.is_none()).collect(); + assert_eq!(fills.len(), 1, "the disc"); + let a = net_area(&fills[0].path); + assert!((a - std::f64::consts::PI * 400.0).abs() < 90.0, "disc area {a}"); + let b = fills[0].path.bounds().unwrap(); + assert!(b.x1 < 76.0 && b.y0 > 34.0, "the fill stays the disc: {b:?}"); + let lines = stroked(&res); + assert_eq!(lines.len(), 2, "{:?}", lines.iter().map(|(p, s)| (p.stroke, s.anchors.len())).collect::>()); + let ends = |s: &vectorcraft_geom::SubPath| (s.anchors[0].p, s.anchors[s.anchors.len() - 1].p); + let (across, up) = if ends(lines[0].1).0.y.min(ends(lines[0].1).1.y) > 50.0 { (lines[0], lines[1]) } else { (lines[1], lines[0]) }; + // The arm across: its free end where the bar ends (less its cap), its other end at the disc, the + // cap closing the join. + let w = across.0.stroke.unwrap(); + assert!((2.0..=4.0).contains(&w), "width {w}"); + let (p, q) = ends(across.1); + let (near, far) = if p.x < q.x { (p, q) } else { (q, p) }; + assert!(far.distance(Point::new(140.0, 60.0)) < 4.0, "free end {far:?}"); + assert!((60.0..=72.5).contains(&near.x) && (near.y - 60.0).abs() < 1.5 && near.x - w / 2.0 <= 70.5, "joined end {near:?}"); + // The arm up, 5 px wide. + let w = up.0.stroke.unwrap(); + assert!((4.0..=6.0).contains(&w), "width {w}"); + let (p, q) = ends(up.1); + let (top, low) = if p.y < q.y { (p, q) } else { (q, p) }; + assert!(top.distance(Point::new(50.0, 5.0)) < 4.0, "free end {top:?}"); + assert!((38.0..=48.0).contains(&low.y) && (low.x - 50.0).abs() < 1.5 && low.y + w / 2.0 >= 40.0 - 0.5, "joined end {low:?}"); + // Strokes only: the disc is outlined and both arms stay strokes. + let res = trace(&img, &strokes(false)); + assert!(res.paths.iter().all(|p| p.stroke.is_some())); + assert_eq!(res.paths.iter().filter(|p| p.stroke == Some(1.0) && p.path.subpaths[0].closed).count(), 1, "the disc's outline"); + assert_eq!(stroked(&res).iter().filter(|(p, _)| p.stroke.is_some_and(|w| w > 1.5)).count(), 2, "the two arms"); +} + +#[test] +fn wide_shapes_without_thin_features_stay_one_fill() { + // A square, a diamond and a disc: their corners and edges are not thin features. + let img = Raster::from_fn(240, 90, |x, y| { + let (px, py) = (x as f64 + 0.5, y as f64 + 0.5); + let square = (10.0..=70.0).contains(&px) && (15.0..=75.0).contains(&py); + let diamond = (px - 120.0).abs() + (py - 45.0).abs() <= 35.0; + let disc = (px - 200.0).hypot(py - 45.0) <= 30.0; + if square || diamond || disc { BLACK } else { WHITE } + }); + for width in [3.0, 6.0, 12.0] { + let res = trace(&img, &TraceParams { stroke_width: width, ..strokes(true) }); + assert_eq!(res.paths.len(), 3, "width {width}: {:?}", res.paths.iter().map(|p| p.stroke).collect::>()); + assert!(res.paths.iter().all(|p| p.stroke.is_none()), "width {width}"); + } +} + #[test] fn create_settings_parse_with_defaults() { let p: TraceParams = serde_json::from_value(serde_json::json!({ "strokes": true, "strokeWidth": 4 })).unwrap(); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index cfe8b02a03..8597607717 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -3963,6 +3963,16 @@ fn the_edited_symbols_nine_slice_guides_are_drawn_and_dragged_on_the_canvas() { assert_eq!(guides_now(&app).left, 0.25, "one undo step"); app.run("edit.redo", json!({})).unwrap(); assert!((guides_now(&app).left - 0.1).abs() < 1e-3); + // Dragged on past the art's left edge at x = 100, the guide lies outside the art and is drawn + // there, along the art's height. + let (from, to) = (xf.to_screen(Point::new(110.0, 150.0)), xf.to_screen(Point::new(80.0, 150.0))); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from), button(from, true)]); + for k in 1..=4 { + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from + (to - from) * k as f32 / 4.0)]); + } + frame(&mut app, &ctx, vec![button(to, false)]); + assert!((guides_now(&app).left + 0.2).abs() < 1e-3, "{:?}", guides_now(&app)); + assert!(dots(&mut app, Point::new(80.0, 100.0), Point::new(80.0, 200.0)) > 10, "the guide drawn outside the art"); app.run("symbol.exitEditing", json!({})).unwrap(); assert_eq!(dots(&mut app, Point::new(110.0, 100.0), Point::new(110.0, 200.0)), 0, "none outside the mode"); } diff --git a/crates/ui-egui/src/dialogs/envelope.rs b/crates/ui-egui/src/dialogs/envelope.rs index 6c9d95b601..1513efc8f2 100644 --- a/crates/ui-egui/src/dialogs/envelope.rs +++ b/crates/ui-egui/src/dialogs/envelope.rs @@ -497,4 +497,19 @@ mod tests { assert_eq!(bar_of(&app).map(|b| b.1), Some(Bar::Mesh { rows: 3, cols: 2 })); bar_frame(&mut app, &ctx, vec![]); } + + #[test] + fn the_control_bar_shows_mesh_rows_and_columns_after_a_warp_point_is_moved() { + let (mut app, _) = app_with_rect(); + app.run(MAKE_WARP, json!({"style": "arc", "bend": 50})).unwrap(); + assert!(bar_of(&app).is_some_and(|(_, bar)| matches!(bar, Bar::Warp { ref style, .. } if style == "arc"))); + let (id, warp) = envelope(&app); + let grid = vectorcraft_doc::live::warp_grid(&warp).unwrap(); + let p = grid.points[6].p; + app.run("object.mesh.movePoint", json!({"id": id.0, "index": 6, "x": p.x + 10.0, "y": p.y + 10.0})).unwrap(); + assert_eq!(bar_of(&app), Some((false, Bar::Mesh { rows: grid.rows, cols: grid.cols }))); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + bar_frame(&mut app, &ctx, vec![]); + } } diff --git a/crates/ui-egui/src/dialogs/symbol_options.rs b/crates/ui-egui/src/dialogs/symbol_options.rs index 79e26764d0..9e6fa98f82 100644 --- a/crates/ui-egui/src/dialogs/symbol_options.rs +++ b/crates/ui-egui/src/dialogs/symbol_options.rs @@ -4,7 +4,8 @@ //! (`symbol.options`). //! //! Fields: `name`, `nineSlice` (bool) with `sliceLeft` / `sliceTop` / `sliceRight` / `sliceBottom` -//! (percent of the symbol's size), `exportType` (`movieClip` | `graphic`), `type` (`dynamic` | +//! (percent of the symbol's size, -1600..1600: below 0 or above 100 for a guide outside the art), +//! `exportType` (`movieClip` | `graphic`), `type` (`dynamic` | //! `static`; a new symbol is dynamic), `registration` (0..8, the 9-point grid; //! 4 = centre), `__edit` (true when editing an existing symbol). Help: //! . @@ -26,20 +27,39 @@ const SLICE_KEYS: [&str; 4] = ["sliceLeft", "sliceTop", "sliceRight", "sliceBott /// A guide field's value when the dialog has none: a quarter of the symbol's size, in percent. const DEFAULT_SLICE_PERCENT: f64 = 25.0; -/// The 9-slice dialog fields for `guides` (percent of the symbol's size; a quarter each when off). +/// The field that keeps the guides the dialog opened with, as fractions, in `[left, top, right, +/// bottom]` order. +const SLICE_OPENED: &str = "__sliceOpened"; + +/// The range of a guide field, in percent: a guide may lie outside the art, up to +/// [`vectorcraft_doc::MAX_GUIDE_FRACTION`] times its size from its edge. +const SLICE_PERCENT_RANGE: std::ops::RangeInclusive = -vectorcraft_doc::MAX_GUIDE_FRACTION * 100.0..=vectorcraft_doc::MAX_GUIDE_FRACTION * 100.0; + +/// The 9-slice dialog fields for `guides` (percent of the symbol's size, unrounded; a quarter each +/// when off). fn slice_fields(guides: Option) -> Map { let g = guides.unwrap_or_default(); let mut m = Map::new(); m.insert("nineSlice".into(), json!(guides.is_some())); - for (key, v) in SLICE_KEYS.iter().zip([g.left, g.top, g.right, g.bottom]) { - m.insert((*key).to_string(), json!((v * 100.0).round())); + let opened = [g.left, g.top, g.right, g.bottom]; + for (key, v) in SLICE_KEYS.iter().zip(opened) { + m.insert((*key).to_string(), json!(v * 100.0)); } + m.insert(SLICE_OPENED.into(), json!(opened)); m } -/// The guides the dialog's fields describe, as the `nineSlice` / `nineSliceGuides` params. +/// The guides the dialog's fields describe, as the `nineSlice` / `nineSliceGuides` params. A field +/// still showing the guide it opened with gives that guide exactly. fn slice_params(d: &Dialog) -> Value { - let [l, t, r, b] = SLICE_KEYS.map(|key| d.f64(key, DEFAULT_SLICE_PERCENT) / 100.0); + let opened = d.fields.get(SLICE_OPENED).and_then(Value::as_array); + let [l, t, r, b] = std::array::from_fn(|i| { + let percent = d.f64(SLICE_KEYS[i], DEFAULT_SLICE_PERCENT); + match opened.and_then(|a| a.get(i)).and_then(Value::as_f64) { + Some(g) if g * 100.0 == percent => g, + _ => percent / 100.0, + } + }); if d.bool("nineSlice") { json!({ "nineSlice": true, "nineSliceGuides": [l, t, r, b] }) } else { json!({ "nineSlice": false }) } } @@ -134,7 +154,7 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { for (key, text) in SLICE_KEYS.into_iter().zip([tl!("Left:"), tl!("Top:"), tl!("Right:"), tl!("Bottom:")]) { label(ui, text); let v = d.f64(key, DEFAULT_SLICE_PERCENT); - if let Some(n) = widgets::range_field(ui, ("dlg-field", key), v, 0.0..=100.0, "%", 0, 64.0) { + if let Some(n) = widgets::range_field(ui, ("dlg-field", key), v, SLICE_PERCENT_RANGE, "%", 3, 64.0) { d.fields.insert(key.into(), json!(n)); } ui.end_row(); diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 1afed73418..9aa4bd7b99 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7139,7 +7139,7 @@ antiAlias Sharp शार्प @msg needs points जरूरत अंक @msg New Window isn't available yet: a document opens in one window नई विंडो अभी तक उपलब्ध नहीं है: एक डॉक्यूमेंट एक विंडो में खुलता है @msg nineSlice must be true or false nineSlice को true या false होना चाहिए -@msg nineSliceGuides must be [left, top, right, bottom], each 0..1, with left + right < 1 and top + bottom < 1 nineSliceGuides को [left, top, right, bottom] होना चाहिए, हर मान 0..1, और left + right < 1 तथा top + bottom < 1 +@msg nineSliceGuides must be [left, top, right, bottom], each -16..16, with left + right < 1 and top + bottom < 1 nineSliceGuides को [left, top, right, bottom] होना चाहिए, हर मान -16..16, और left + right < 1 तथा top + bottom < 1 @msg no action set is current कोई कार्रवाई सेट चालू नहीं है @msg no action set to save बचाने के लिए कोई कार्रवाई सेट नहीं @msg no active data set कोई सक्रिय डेटा सेट नहीं diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 86b9ba6580..8a8f8453b6 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3538,11 +3538,11 @@ digits Malayalam Malayalam Tate-chu-yoko Tate-chu-yoko Tate-chu-yoko Settings… Inställningar för Tate-chu-yoko… Tate-chu-yoko Settings Inställningar för Tate-chu-yoko - Composite Fonts… Sammansatta teckensnitt… - Composite Fonts Sammansatta teckensnitt - Export Composite Fonts Exportera sammansatta teckensnitt - Import Composite Fonts Importera sammansatta teckensnitt - Delete Font Ta bort teckensnitt + Composite Fonts… Sammansatta typsnitt… + Composite Fonts Sammansatta typsnitt + Export Composite Fonts Exportera sammansatta typsnitt + Import Composite Fonts Importera sammansatta typsnitt + Delete Font Ta bort typsnitt Kanji Kanji Kana Kana Numerals Siffror @@ -5386,7 +5386,7 @@ lighting Light Ljus @msg {_1}: the clipping path is too complex to cut the art with {_1}: urklippsbanan är för komplex för att klippa teckningen med @msg {_1} takes at most {MAX_MEMBERS} objects {_1} tar högst {MAX_MEMBERS} objekt @msg {_1} can't build solids from art nested more than {MAX_DEPTH} levels deep {_1} kan inte bygga solider av teckning som är kapslad mer än {MAX_DEPTH} nivåer djupt -@msg Revolve paint is too complex for this surface; reduce Segments or simplify the gradient Färgen för Rotera runt axel är för komplex för den här ytan; minska Segment eller förenkla övertoningen +@msg Revolve paint is too complex for this surface; reduce Segments or simplify the gradient Färgen för Rotera runt axel är för komplex för den här ytan; minska Segment eller förenkla gradienten @msg Revolve edge must be left or right Rotera runt axel: edge måste vara left eller right @msg Revolve cap must be a boolean Rotera runt axel: cap måste vara ett booleskt värde @msg the revolved object has no fill or stroke det roterade objektet har ingen fyllning eller linje @@ -6473,8 +6473,8 @@ axis Y Axis Y-axel @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it behörigheten `{shown}` är reserverad för ett senare plugin-API; den här värden beviljar den inte @msg unknown permission `{shown}` okänd behörighet `{shown}` @msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants ”{name}” begär behörigheterna {asked}: en person måste godkänna dem i skrivbordsappen, eller skicka `grant` i en session som startats med --allow-plugin-grants -@msg `grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app `grant` och `allowHeavy` gäller bara i en session som startats med --allow-plugin-grants: godkänn insticksprogrammet i skrivbordsappen -@msg Only the person at the keyboard can approve installing a plug-in Bara personen vid tangentbordet kan godkänna installationen av ett insticksprogram +@msg `grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app `grant` och `allowHeavy` gäller bara i en session som startats med --allow-plugin-grants: godkänn pluginet i skrivbordsappen +@msg Only the person at the keyboard can approve installing a plug-in Bara personen vid tangentbordet kan godkänna installationen av ett plugin @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed ”{name}” beviljades inte `{p}`, som dess utdata behöver: ingenting ändrades @msg a heavy filter runs in the background, so it can't declare `commands` ett tungt filter körs i bakgrunden, så det kan inte deklarera `commands` @msg at most {MAX_COMMANDS} `commands` högst {MAX_COMMANDS} `commands` @@ -6579,7 +6579,7 @@ axis Y Axis Y-axel Skill Icons Färdighetsikoner Attack Attack Defend Försvar - Heal Läkning + Heal Retuschering Buff Buff Ult Ult Sword Svärd @@ -8097,7 +8097,7 @@ digits Hindi Hindi @msg need at least two points minst två punkter krävs @msg needs points punkter krävs @msg nineSlice must be true or false nineSlice måste vara true eller false -@msg nineSliceGuides must be [left, top, right, bottom], each 0..1, with left + right < 1 and top + bottom < 1 nineSliceGuides måste vara [left, top, right, bottom], vart och ett 0..1, med left + right < 1 och top + bottom < 1 +@msg nineSliceGuides must be [left, top, right, bottom], each -16..16, with left + right < 1 and top + bottom < 1 nineSliceGuides måste vara [left, top, right, bottom], vart och ett -16..16, med left + right < 1 och top + bottom < 1 @msg no action set is current ingen åtgärdsuppsättning är aktuell @msg no active data set ingen aktiv datauppsättning @msg no appearance item {index} inget utseendeobjekt {index} @@ -8802,3 +8802,40 @@ digits Hindi Hindi Margin Marginal Box Ram Swatch Färgruta + Duplicate Effects Duplicera effekter + Remove Effects Ta bort effekter + Add art with Add as Single Graphic, or drop art here. Lägg till grafik med Lägg till som enkel grafik, eller släpp grafik här. + Add as Single Graphic Lägg till som enkel grafik + Add to Custom Dictionary Lägg till i egen ordlista + Assamese assamesiska + Bulgarian bulgariska + Cancel Opening Avbryt öppning + Change in Custom Dictionary Ändra i egen ordlista + Delete from Custom Dictionary Radera från egen ordlista + Delete SVG Filter Radera SVG-filter + Edit SVG Filter Redigera SVG-filter + Expand as Wireframes Expandera som trådmodeller + Face Yta + Graphics map onto planar faces: pick the Plane or Extrude object type. Grafik mappas på plana ytor: välj objekttypen Plan eller Extrudera. + Import SVG Filter Importera SVG-filter + Import SVG Filter… Importera SVG-filter… + Line Gap Radmellanrum + List Installed Scripts Lista installerade skript + Manage Profiles Hantera profiler + Mapped graphics Mappad grafik + Materials Material + Move Type Path Handle Flytta handtag för textbana + NEW DOCUMENT PROFILES PROFILER FÖR NYTT DOKUMENT + New SVG Filter Nytt SVG-filter + Pick a graphic above to map it onto the object. Välj en grafik ovan för att mappa den på objektet. + Reading the file… Läser filen… + Remove Graphic Ta bort grafik + Replace the selected 3D objects with the edges of their faces, as stroked paths. Ersätt de markerade 3D-objekten med kanterna på deras ytor, som banor med kontur. + Sanskrit sanskrit + Select a 3D object to map the graphic onto it. Markera ett 3D-objekt för att mappa grafiken på det. + Select Symbol Instance Part Markera del av symbolinstans + Spelling Suggestions Stavningsförslag + Stroke Weight Down Minska konturtjocklek + Stroke Weight Up Öka konturtjocklek + The selected objects have different graphics. De markerade objekten har olika grafik. + Word Gap Ordmellanrum diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 460ad52a70..66caa1c3a4 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -2058,7 +2058,7 @@ fn three_d_refusals_translate_with_their_values() { vectorcraft_engine::EngineError::BadParams { cmd: "effect.apply".into(), msg: e }.to_string() }; let errors = [ - (refuse(vectorcraft_effects::validate_three_d_at(&group, EXTRUDE, &json!({}), Some((0, 0)))), "goes on the group itself", vec![]), + (refuse(vectorcraft_effects::validate_three_d_at(&group, EXTRUDE, &json!({}), (Some(0), 0))), "goes on the group itself", vec![]), ( refuse(vectorcraft_effects::validate_three_d(&rect, EXTRUDE, &json!({"lights": [{"intensity": 500}]}))), "must be a number from", diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index 0c702636ec..fe38851b44 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -465,9 +465,18 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let sel = selected(ui.ctx(), &doc); let view: View = pstate(ui.ctx(), "gs-view"); let mut ev = Events::default(); + // In a sized panel the list fills the space above the footer (#2992), as the Artboards list + // does; elsewhere it keeps its 220 pt. + let fixed = widgets::panel_footer_bottom(ui).is_some(); + let list_height = widgets::panel_list_height(ui, 220.0, 2.0 + ui.spacing().item_spacing.y); widgets::list_box(ui, |ui| { - let out = egui::ScrollArea::vertical().id_salt("gs-scroll").max_height(220.0).show(ui, |ui| { - ui.set_min_height(120.0); + let scroll = egui::ScrollArea::vertical() + .id_salt("gs-scroll") + .max_height(list_height) + .min_scrolled_height(list_height.min(64.0)) + .auto_shrink([false, !fixed]); + let out = scroll.show(ui, |ui| { + ui.set_min_height(if fixed { list_height.min(120.0) } else { 120.0 }); ui.set_width(ui.available_width()); if doc.graphic_styles.is_empty() { super::empty_state(ui, "dc-graphic-styles", tl!("No graphic styles"), tl!("Select styled art and click New Graphic Style.")); @@ -847,6 +856,36 @@ mod tests { app.session.active().unwrap().doc.graphic_styles.iter().map(|g| g.name.clone()).collect() } + /// In a panel made taller the list fills the space above its footer instead of staying 220 pt + /// tall with blank space below it (#2992); outside a sized panel it keeps that height. + #[test] + fn the_list_fills_a_tall_panel_above_its_footer() { + let mut app = app(); + for i in 0..30 { + app.session.execute("graphicStyle.new", &json!({"name": format!("Style {i:02}")})).unwrap(); + } + let ctx = egui::Context::default(); + set_pstate(&ctx, "gs-view", View::LargeList); + // The clip rect of the first style's name: the list's visible area. + let mut list = |bottom: Option| { + let mut clip = None; + for _ in 0..3 { + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(260.0, 700.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + let info = egui::UiStackInfo::default().with_tag_value(widgets::PANEL_FOOTER, bottom); + ui.scope_builder(egui::UiBuilder::new().ui_stack_info(info), |ui| show(&mut app, ui)); + }); + out.textures_delta.clear(); + clip = out.shapes.iter().find(|c| matches!(&c.shape, egui::Shape::Text(t) if t.galley.text() == "Style 00")).map(|c| c.clip_rect); + } + clip.expect("the first style's row is drawn") + }; + let tall = list(Some(650.0)); + assert!(tall.height() > 400.0 && tall.bottom() <= 650.0 - 31.0, "the list fills the panel above its footer: {tall:?}"); + let loose = list(None); + assert!(loose.height() <= 220.5, "unsized, the list keeps its height: {loose:?}"); + } + #[test] fn list_view_names_the_styles_and_deletes_the_selected_ones_after_asking() { let mut app = app(); diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index c9dd29efbb..04f99c3c1f 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -837,6 +837,23 @@ mod tests { app.run("ui.symbolOptions", json!({"edit": true, "name": "Mark"})).unwrap(); assert!(app.ui.dialog.as_ref().unwrap().bool("nineSlice")); assert_eq!(app.ui.dialog.as_ref().unwrap().f64("sliceLeft", 0.0), 20.0); + app.ui.dialog = None; + // Guides outside the art, and ones that are not whole percents, open as they are and come + // back unchanged from OK; a field changed to a value past 100 % puts that guide outside. + let guides = [-0.123456789, 1.5, 0.013, -2.75]; + app.run("symbol.options", json!({"name": "Mark", "nineSliceGuides": guides})).unwrap(); + app.run("ui.symbolOptions", json!({"edit": true, "name": "Mark"})).unwrap(); + let dialog = app.ui.dialog.as_ref().unwrap(); + for (key, want) in [("sliceLeft", -12.3456789), ("sliceTop", 150.0), ("sliceRight", 1.3), ("sliceBottom", -275.0)] { + assert!((dialog.f64(key, 0.0) - want).abs() < 1e-9, "{key}: {}", dialog.f64(key, 0.0)); + } + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.run("symbol.list", json!({})).unwrap()["symbols"][1]["nineSlice"], json!(guides)); + app.run("ui.symbolOptions", json!({"edit": true, "name": "Mark"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("sliceRight".into(), json!(-125.5)); + crate::dialogs::confirm(&mut app).unwrap(); + let nine = app.run("symbol.list", json!({})).unwrap()["symbols"][1]["nineSlice"].clone(); + assert_eq!(nine, json!([-0.123456789, 1.5, -1.255, -2.75])); } /// F8 is Symbol Options… (`ui.symbolOptions`) by default, on every platform. Shift+F8 and Cmd+F8 diff --git a/docs/gaps.md b/docs/gaps.md index 060de4e155..3d6f886c0a 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -663,7 +663,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi `graphicStyle.addFromLibrary`). - **Missing:** more built-in brush libraries beyond the eight shipped (and further graphic-style libraries beyond the ten shipped, and further symbol libraries beyond Basic Shapes, UI Frames, Map Markers, Inventory Icons and Skill Icons; original, generated in code, never Adobe's); dynamic symbols' `.ai` read and write; - Global Edit of groups holding type or images, and rotated copies as matches; 9-slice guides outside the symbol's art (a dragged guide stops at the art's edge). + Global Edit of groups holding type or images, and rotated copies as matches. - **Estimate:** 5–15 h. ## G3 3D and Materials diff --git a/docs/mcp.md b/docs/mcp.md index 62a2c2d0ad..274db05a34 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2779,8 +2779,9 @@ already walks Image Trace. Short agent entry points: `static`|`dynamic`), `symbol.new {name?, registration?, exportType?, nineSlice?, nineSliceGuides?, type?, ids?}`, `symbol.options {name?, newName?, registration?, exportType?, nineSlice?, nineSliceGuides?, type?}` (`nineSlice` bool turns - 9-slice guides on or off; `nineSliceGuides` is `[left, top, right, bottom]`, fractions 0..1 of the symbol size, a - quarter each when none are given; rows of `symbol.list` carry `nineSlice`: the guides or `null`; a scaled instance of + 9-slice guides on or off; `nineSliceGuides` is `[left, top, right, bottom]`, fractions of the symbol size in from + each edge, each -16..16 with `left + right < 1` and `top + bottom < 1`, a quarter each when none are given; below 0 + or above 1 puts a guide outside the art, and the art then scales by the cells it falls in; rows of `symbol.list` carry `nineSlice`: the guides or `null`; a scaled instance of a symbol with guides keeps its corners at their size, and `symbol.breakLink` gives its art as it draws; dragging a guide on the canvas in symbol editing mode sends `nineSliceGuides` in one undo step; `type` is Symbol Type, `static` by default for the command and `dynamic` by default in the Symbol Options dialog), @@ -6071,7 +6072,7 @@ while such an image that the art shows has a plate of its name; deleting the swa file's composite is drawn through clips the image (a clipping group, its path under the nonzero fill rule, an even-odd clipping path kept as the same area), and `file.place` answers the image's id as `image`, since the Links commands take the image and not the group. `links.update` and `links.relink` clip the image -by the file's clipping path again (in a new clipping group when none holds it, and inside a clipping mask made in the +by the file's clipping path again (a plain group holding just the image becomes its clipping group, a new clipping group holds it when no group does, and it goes inside a clipping mask made in the document, whose path is kept), unless Placement Options clip the image, the same way for the images in symbols, graph designs, patterns and opacity masks; when the new file has no clipping path, a clipping group holding just the image whose path is the old file's clipping path loses that path and stays as a plain group of the image, with its id, name, visibility and transparency (one whose path was given the @@ -6816,7 +6817,8 @@ DCS Transparency Interactions, off by default) adds `dcsTransparency: true` to t and the panel shows a warning mark on them. VectorCraft's rule for it: the image, or a group or layer holding it, has an opacity below 100%, a blend mode other than Normal, an opacity mask or an effect, or its bounds overlap the bounds of another visible object that has one of those or a gradient with a transparent stop (in a fill, a stroke or -a character's fill or stroke); a DCS image with transparency of its own counts as such an object. The check looks at +a character's fill or stroke); a DCS image with transparency of its own counts as such an object. Bounds are cut to the +bounds of the clipping paths of the clip groups and clipping layers holding an object. The check looks at every object in the layers each time the list is read. A `dcsTransparency` that is not true or false is an error. `links.goTo {id}` selects an image; `links.embed {ids?}` keeps linked files' pixels in the document (an image whose file is missing stays linked: relink it first); `links.unembed {id, path}` writes an embedded image to a file @@ -9927,7 +9929,22 @@ adds a row and a column where it clicks inside. `object.mesh.addLine`, and `obje the mesh's outline (within a millionth of a point) on any side without `tolerance`; a point outside needs `tolerance`. `object.mesh.addLine` at a point that is already a mesh point adds no line and records no undo step unless its `color` changes a gradient mesh's point (a mesh envelope's points have no color). `press_key` Escape during a drag of a point or handle of a mesh -envelope or a gradient mesh cancels it: the point goes back and no undo step is added. The Control bar shows Edit Envelope / Edit Contents, the warp's +envelope or a gradient mesh cancels it: the point goes back and no undo step is added. + +A warp envelope's points can be edited the same way, with the same commands. Its points are those of its surface +sampled on 4×4 patches, with handles along it; where 4×4 patches draw more than 0.1% of the warp's diagonal away from +the warp, on 8×8 or 16×16 patches (these sizes and the 0.1% are VectorCraft's own values). The canvas shows those +points on a selected warp. The first point or handle moved, or the first line added or deleted, makes the warp a mesh +envelope on that grid and applies the edit, as one undo step: Undo, or Escape during the drag, gives back the warp +with its style and bend. From then on the Control bar shows the mesh's rows and columns, Reset with Mesh with Maintain +Shape keeps the edited shape, and Reset with Warp replaces it with the chosen warp style. Release gives back the +edited mesh as the envelope's shape, and Expand keeps the edited distortion. A warp that no grid of up to 16×16 +patches follows that closely (some warps saved before the Bézier warp net existed, `version: 0`) shows no points, and +editing it fails with "this warp's points can't be edited: use Reset with Mesh first" and changes nothing. The help +page on reshaping envelopes: +https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-objects-with-envelopes.html + +The Control bar shows Edit Envelope / Edit Contents, the warp's style, orientation, bend and distortions (or the mesh's rows and columns), Reset (an unbent warp, a flat mesh) and Envelope Options. @@ -9953,7 +9970,8 @@ Color panel, Swatches or the Eyedropper) recolours just the picked points, and w `object.mesh.movePoints {id, points: [index…], dx, dy}` (or `{items: [{id, points}…], dx, dy}` over several meshes) moves points by (dx, dy), their handles with them; `object.mesh.setPointColor` takes `points` or `items` the same way to colour or fade several points at once. An index out of range, an index that is not a whole number ≥ 0, or a -move past the coordinate range fails and changes nothing. +move past the coordinate range fails and changes nothing. A call that changes no point (no points named, a move by +(0, 0), the colour a point already has) changes nothing and records no undo step. ```json {"name":"run_command","arguments":{"command":"object.mesh.movePoints","params":{"id":12,"points":[0,4],"dx":10,"dy":-5}}} diff --git a/docs/roadmap.md b/docs/roadmap.md index c45a6555e3..6f631fe88b 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (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: 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; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; 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 are in; 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; 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; 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; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; 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; 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; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (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: 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; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; 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 are in; 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; 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; 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; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; 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; 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; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). > @@ -52,6 +52,7 @@ M7 type: Touch Type moves a right-to-left character along its line and up from i | Date | Change | Summary | |---|---|---| +| 2026-11-13 | minor | Graphic Styles: in a panel made taller the list fills the space above the footer instead of stopping at 220 pt (#2992; `the_list_fills_a_tall_panel_above_its_footer` in `crates/ui-egui/src/panels/graphic_styles.rs`). Scores and estimates unchanged. | | 2026-11-13 | minor | PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke instead of being left out, adding no text (#6971; `empty_actual_text_keeps_the_glyphs_art` in `crates/pdf/src/tests/actual_text.rs`). Scores and estimates unchanged. | | 2026-11-13 | minor | Library panels (swatch, Color Book, brush, symbol and graphic style libraries): in a panel made taller the list fills the space above the footer instead of scrolling inside 220 or 280 pt (#2992; `the_list_fills_a_tall_panel_above_its_footer` in `crates/ui-egui/src/panels/library_panel/tests.rs`). Scores and estimates unchanged. | | 2026-11-13 | minor | Swatches: in a panel made taller the swatch list fills the space above the footer instead of scrolling inside 150 or 200 pt (#1638; `the_list_fills_a_tall_panel_above_its_footer` in `crates/ui-egui/src/panels/swatches/tests.rs`). Scores and estimates unchanged. | @@ -150,7 +151,7 @@ native wording review, layout checks and a web Devanagari font remain. [Notes](l | M0 | Skeleton + vertical slice | ✅ done | — | | M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them) | 4–6 | | M2 | Drawing tools + smart guides | ✅ mostly done (#3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); no View submenu; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123) | 12–18 | -| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); | Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); 4–8 | +| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); | 4–8 | | M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); 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. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | | M5 | Performance | 🟡 background render + caches + MT done; `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 92e3c54c61..40b94a8cc9 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-13 · **Change:** minor (Outline Stroke is in the canvas context menu (#5267); 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-13 · **Change:** minor (Outline Stroke is in the canvas context menu (#5267; 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) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). > @@ -53,6 +53,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-13 | minor | Graphic Styles: in a panel made taller the list fills the space above the footer instead of stopping at 220 pt (#2992; `the_list_fills_a_tall_panel_above_its_footer` in `crates/ui-egui/src/panels/graphic_styles.rs`). Scores and estimates unchanged. | | 2026-11-13 | minor | PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke instead of being left out, adding no text (#6971; `empty_actual_text_keeps_the_glyphs_art` in `crates/pdf/src/tests/actual_text.rs`). Scores and estimates unchanged. | | 2026-11-13 | minor | Library panels (swatch, Color Book, brush, symbol and graphic style libraries): in a panel made taller the list fills the space above the footer instead of scrolling inside 220 or 280 pt (#2992; `the_list_fills_a_tall_panel_above_its_footer` in `crates/ui-egui/src/panels/library_panel/tests.rs`). Scores and estimates unchanged. | | 2026-11-13 | minor | Swatches: in a panel made taller the swatch list fills the space above the footer instead of scrolling inside 150 or 200 pt (#1638; `the_list_fills_a_tall_panel_above_its_footer` in `crates/ui-egui/src/panels/swatches/tests.rs`). Scores and estimates unchanged. | @@ -499,7 +500,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 86% | Live Paint gap options, Shape Builder gap detection, options (Tool Options dialog, clicking a stroke in merge mode) and Shift-drag marquee | 3–6 | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); freeform gradients in SVG/PDF and mixed spot/process gradients in SVG (exported as stops; PDF export keeps the spot inks in a DeviceN shading, except next to RGB or Lab stops; dithered fills and Perceptual gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve are written as images in process colors), pattern fills in Expand | 2–4; Eyedropper source reads regression-tested (#1251) | | Strokes, brushes, width profiles | 5 | 90% | more built-in brush libraries (nine generated in code including Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media are done; Art brush Overlap and Pattern brush auto corners are done), pen pressure on macOS (the windowing layer reports none there), Stylus Wheel, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | -| Appearance, transparency, graphic styles, masks | 5 | 98% | raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 | +| Appearance, transparency, graphic styles, masks | 5 | 98% | Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 | | Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap (since done: #3061, #3063, #3785), SVG Filters, Transform Patterns and Scale Strokes & Effects on a fill's or stroke's own Transform effect | 6–10 | | 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting; materials, light presets, shadows, ray tracing, Rotate (Classic), Map Art and more complete visibility remain | 25–45 | | Type advanced | 4 | 50% | CJK composition for vertical type (ruby, mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, manual tate-chu-yoko), tab leaders, spell check (its engine, custom dictionary commands, the Edit Custom Dictionary dialog and Auto Spell Check are done, #4936: the Check Spelling dialog remains; a right-click on an underlined word offers its suggestions, Ignore All and Add to Dictionary, and a right-click on type has Spelling › Auto Spell Check), Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 | @@ -883,7 +884,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Dynamic symbol appearance follows what an object draws** (VectorCraft's own rule): `symbol.instance.setAppearance` refuses a fill or stroke for an object of the art that does not draw it (a guide, blend, envelope, Repeat, Intertwine group, gradient mesh or placed document; a nested symbol instance's stroke, and its fill unless a solid color or none, which stains its art; an image's fill or stroke without a Convert to Shape or Outline Object effect) with an error that names the key and the object, and the call changes nothing. Opacity, blend and `null`, which takes a stored change back, are taken for every object. Tests: `crates/engine/src/tests/dynamic_symbols.rs`. - Symbol editing mode keeps every instance in step: instances of a dynamic symbol inside other symbols' art, pattern tiles, graph designs, stored brushes and opacity masks keep their appearance changes on the objects an edit reorders and drop the changes to objects it deletes. The view does not draw the instance the edit was entered from. Area type in the symbol's art takes the text wrap that moving a wrap object gives it. Editing another symbol at a place that fails keeps the current edit open, and only the editing layer or art on it can be isolated. Tests: `crates/engine/src/tests/symboledit.rs`, `isolation::symbol_editing_does_not_draw_the_instance_it_was_entered_from`, `panels::symbols::tests::double_clicking_a_symbol_in_the_panel_edits_it_in_either_view`, `the_panel_menus_edit_symbol_edits_the_instances_symbol_or_the_panels`, `the_control_bars_edit_symbol_edits_the_selected_instances_symbol`, `chrome::tests::the_control_bar_exits_symbol_editing_mode`. - **Dynamic symbol instances on the canvas** ([Symbols, archived copy](https://web.archive.org/web/20240206075757/https://helpx.adobe.com/illustrator/using/symbols.html)): each instance of a dynamic symbol can have an appearance of its own while it shares the symbol's shape. The rest of this entry is VectorCraft's own rules. A Direct Selection click on an instance of a dynamic symbol selects the path, compound path or type object of the symbol's art under the pointer and outlines it (`symbol.instance.selectPart`); the Swatches and Color panels, the Control bar, the Eyedropper and the other fill and stroke controls then change that object's fill or stroke (solid, none, gradient or pattern) for this instance only, each as one undo step, and `transparency.set` changes its opacity and blend the same way; the symbol's art and its other instances stay as they were. Alt or Shift picks the instance whole. An Eyedropper source that is not a path, compound path or type, a click on any other object of the art (a group, image, blend or nested instance) and the commands that change the selected objects (moving, Delete, Group, Hide, Lock, Arrange, Expand, the gradient annotator, isolate/knockout on Transparency, the Appearance panel's rows and others) are refused with a status message. Copy, Export Selection, Fit to Selection, Liquify, Isolate, Add to Library and Save Selection use the whole instance (`docs/mcp.md`), and another selection tool selects the instance whole again. Tests: `crates/engine/src/tests/dynamic_symbols.rs` (`gradients_and_patterns_on_a_picked_object_are_taken`, `opacity_and_blend_on_a_picked_object_go_through_transparency_set`), `direct::tests::a_click_on_a_dynamic_instance_picks_the_object_under_the_pointer`. - - **9-slice guides on the canvas** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/maintain-proportions-while-scaling-symbols.html)): while a symbol with Enable Guides for 9-Slice Scaling on is edited in symbol editing mode, the canvas draws its two horizontal and two vertical guides as dotted lines across its art, with any tool and with ruler guides hidden. With the Selection tool the pointer near a guide shows the Move cursor, and dragging the guide moves it (`symbol.options`'s `nineSliceGuides`) as one undo step; Escape during the drag puts it back. VectorCraft's own rules: a guide within 4 screen pixels takes the press before the art and the bounding box; it stays within the art's box (guides outside the art are not supported yet) and stops short of the opposite guide; the drag does not snap. Tests: `nineslice::tests`, `symbol_nine_slice::tests::the_edited_symbols_guides_cross_its_art_where_the_editing_layer_shows_it`, `a_moved_guide_stays_in_the_art_and_short_of_the_opposite_guide`, `canvas::tests::the_edited_symbols_nine_slice_guides_are_drawn_and_dragged_on_the_canvas`. + - **9-slice guides on the canvas** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/maintain-proportions-while-scaling-symbols.html)): while a symbol with Enable Guides for 9-Slice Scaling on is edited in symbol editing mode, the canvas draws its two horizontal and two vertical guides as dotted lines across its art, with any tool and with ruler guides hidden. With the Selection tool the pointer near a guide shows the Move cursor, and dragging the guide moves it (`symbol.options`'s `nineSliceGuides`) as one undo step; Escape during the drag puts it back. VectorCraft's own rules: a guide within 4 screen pixels takes the press before the art and the bounding box; it may pass the art's edges (see the next entry) and stops short of the opposite guide; the drag does not snap. Tests: `nineslice::tests`, `symbol_nine_slice::tests::the_edited_symbols_guides_cross_its_art_where_the_editing_layer_shows_it`, `a_moved_guide_passes_the_arts_edges_and_stops_short_of_the_opposite_guide`, `canvas::tests::the_edited_symbols_nine_slice_guides_are_drawn_and_dragged_on_the_canvas`. + - **9-slice guides outside the art** ([the help page](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf), Use 9-slice scaling section): a guide may lie outside the symbol's art, set by dragging it past the art's edge in symbol editing mode, by `symbol.options`'s `nineSliceGuides` or by a Symbol Options field below 0% or above 100%, and a scaled instance still scales, by the cells its art falls in. VectorCraft's own rules: each guide lies within 16 times the art's width or height of its edge (`-16..16` as a fraction, `-1600..1600` in percent) and the two guides of an axis keep their order; a guide past an edge of the art cuts the art at that edge, so the outer cell on its side holds no art; with both guides of an axis past opposite edges the art scales as a whole along it; with both past the same edge the art lies in the outer cell at the other edge and keeps its size, from that edge of the instance, or shrinks to the instance's width or height when the instance is smaller than the art; Symbol Options shows and keeps the guides unrounded. Native files keep the guides exactly; SVG and `.ai` write such an instance as its placed art and keep no guides. Tests: `symbol_nine_slice::tests::guides_outside_the_art_are_accepted_in_order_and_within_the_limit`, `art_scales_by_the_cells_it_falls_in_when_guides_lie_outside_it`, `the_map_with_guides_outside_the_art_is_continuous_and_monotone` in `crates/doc`, `guides_outside_the_art_are_set_by_command_and_scale_by_the_cells_that_hold_art`, `a_guide_dragged_past_the_arts_edge_lies_outside_it`, `guides_outside_the_art_survive_saving_and_reopening_a_native_file` in `crates/engine`, `nineslice::tests::a_guide_outside_the_art_is_taken_and_dragged_past_the_arts_edge`, `a_nine_slice_instance_with_a_guide_outside_its_art_is_written_as_drawn` (SVG and `.ai`). - **Delete Symbol asks first** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [symbol libraries](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Alt-click Delete](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)): the Symbols panel's Delete Symbol button and menu item ask "Delete the selected symbol?" with Yes and No for a symbol no instance uses. For a symbol with placed instances they ask with Expand Instances (the instances become ordinary art), Delete Instances and Cancel; either Instances button deletes the symbol in one undo step. Alt-click on the button deletes an unused symbol without asking and still asks about one with instances. A question left open while another document became active deletes nothing. `symbol.delete` itself does not ask. Tests: `panels::symbols::tests::delete_symbol_asks_first_and_alt_click_deletes_an_unused_symbol_at_once`, `the_in_use_question_expands_or_deletes_the_instances`, `a_stale_delete_symbol_question_deletes_nothing`, `the_delete_symbol_questions_show_their_buttons`. - **Symbols › Select All Unused** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), #4918): the Symbols panel menu's Select All Unused shows the symbols nothing places selected (`symbol.unused`): instances in the art (opacity masks included), graph designs, pattern tiles and brush art count, and so do instances in a used symbol's art. Delete Symbol, the button or the menu item, then asks "Delete the selected symbols?" once and deletes those still unused in one undo step (`symbol.delete {names}`); Alt-click on the button deletes them without asking, and a click on a symbol picks just it again. Tests: `tests::brushsym::symbol_unused_lists_the_symbols_nothing_places_and_delete_takes_several`, `panels::symbols::tests::select_all_unused_picks_the_unused_symbols_and_delete_deletes_them`, `dialogs::symbol_delete::tests::several_symbols_get_the_plural_question`. - **Symbols › Sort by Name and the list views** ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Sort by Name puts the symbols in alphabetical order (`symbol.sortByName`), and its Thumbnail View, Small List View and Large List View show them as thumbnails, in a compact list or in a list with larger thumbnails. VectorCraft's own rules: the sort ignores case and keeps names that differ only in case in their order; it changes the document's order, which `symbol.list` reports, as one undo step, keeps the current symbol and adds no undo step when the symbols are already in order; Thumbnail View is the default, Small List View has 18-point rows with 14-point thumbnails and Large List View 26-point rows with 22-point thumbnails, and a click or double-click on a symbol does the same in every view. Tests: `tests::brushsym::symbol_sort_by_name_orders_the_symbols_in_one_undo_step`, `panels::symbols::tests::sort_by_name_and_the_small_and_large_list_views`. @@ -1177,6 +1179,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Extrude & Bevel, Inflate and Rotate apply to type: it makes a solid of its glyph outlines, painted with its own fills and strokes or, when it has none, its characters' colour (the first run's), and stays type, so editing the text reshapes the solid (#4715). - Extrude & Bevel, Inflate and Rotate (Effect › 3D and Materials): live effects in the `three-d` crate with depth, twist, taper, solid or hollow caps, five original bevel shapes (width, height, repeat, spacing, inside, both sides), Inflate's volume, both sides, twist, taper and cap, Rotate's turned fills and strokes, Position presets, the rotation and light gizmos, SVG/PDF vector output and Expand Appearance; one 3D effect per object; covered by geometry, effect, canvas-versus-export, command and dialog tests ([three-d.md](three-d.md)). - Extrude & Bevel and Inflate build detailed shapes: each solid takes up to 65,536 outline points and 163,840 faces (VectorCraft's own limits, was 2,048 points and 32,768 faces), counted before any point is sampled; when the faces do not fit, every curve takes fewer pieces, down to 4. A closed path of 2,000 curves extrudes with a bevel and inflates, and paths of 5,000 and 10,000 curves build at the default settings (`crates/three-d/src/solid/tests_limits.rs`). + - The solids of one Extrude & Bevel (both kinds) or Inflate effect on one object, its fill's, its strokes' and a group's members' together, keep up to 163,840 faces (VectorCraft's own limit). Each solid is built in turn; once their faces pass the limit, no later solid is built, the object draws its source art, and applying or editing the effect, Export 3D Object and Expand as Wireframes report that the 3D surface is too complex. Tests `solids::tests::an_objects_solids_count_their_faces_together`, `a_groups_solids_together_past_the_limit_draw_the_source`, `a_fill_and_strokes_together_past_the_limit_draw_the_source`. - Extrude & Bevel (both kinds) and Rotate keep the art's curves in the faces they draw, export and expand: caps and the edges of walls and bevels where they meet a cap are cubics with smooth anchors where the art's are, fitted within 0.001 pt in perspective and within the sampling tolerance on a bevel's inset. An edge of a twisted wall that is cut into pieces, a piece of curve that does not fit after 8 halvings, and the curves past 1,048,576 for one solid stay straight (VectorCraft's own values; [three-d.md](three-d.md#what-differs-from-the-public-documentation)). Tests `solid::tests::a_cap_keeps_the_curves_of_the_art`, `a_cap_in_perspective_fits_the_projected_curves`, `a_beveled_cap_and_its_walls_share_their_curves`, `twisted_beveled_tiny_and_degenerate_caps_keep_their_curves`. - Export 3D Object (Asset Export's menu): an object with Extrude & Bevel, Revolve, Inflate or Rotate becomes a 3D asset whose Format is USDA (the default), USDZ, glTF or OBJ, and Export writes each of its solids as a mesh with a material in its paint's color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`; [export 3D vector artwork](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)). - Initial live Revolve (#605, #846): a portable geometry and shading crate (`three-d`), editable path and compound profiles, compact options with artboard rotation and light gizmos, SVG/PDF vector output and Expand Appearance that can trim covered faces. Open ends have continuous caps by default, shading is smooth with one to ten colored lights, and intersecting surfaces' visibility is approximate ([revolve.md](revolve.md)). @@ -1341,12 +1344,14 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Window › Blend exposes easing Type, Ramp and independent color Shift through `object.blend.options`. Smooth Color counts the steps of each pair of keys from their color change, or from the distance between their visible bounding-box edges when their colors match or they hold gradients or patterns ([Blend Options](https://web.archive.org/web/20241217212108/https://helpx.adobe.com/illustrator/using/blending-objects.html)); the step counts, their caps and the colors compared are VectorCraft's own. Envelope Options › Anti-Alias off draws an envelope's distorted images without smoothing, and Preserve Shape Using › Transparency gives each piece of a distorted image an opacity mask in its shape instead of a clipping mask ([Envelope panel options](http://web.archive.org/web/20260513013456/https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/envelope-panel-options.html)). + The Mesh tool and Direct Selection drag the points and handles of an envelope made with Warp, as the help page describes for any envelope ([Distort objects with envelopes](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-objects-with-envelopes.html)). A selected warp shows the points of its surface on 4×4 patches (8×8 or 16×16 where 4×4 draws more than 0.1% of its diagonal away from the warp), and the first edit makes it a mesh envelope on that grid in the same undo step; Undo or Escape gives back the warp with its style and bend. The grid sizes, the 0.1% and the change to a mesh envelope are VectorCraft's own rules. Tests: `every_warp_style_has_a_grid_that_keeps_its_shape` in `crates/doc/src/live/envelope.rs`, `moving_a_warp_point_makes_it_a_mesh_envelope_in_one_step` and `an_edited_warp_saves_resets_releases_and_expands_as_edited` in `crates/engine/src/tests/envelope_edit.rs`, `the_mesh_tool_and_direct_selection_drag_warp_envelope_points` in `crates/tools/src/meshedit.rs`. With Envelope Options › Distort Appearance on, type's strokes (its characters' and those on its own appearance) paint along the bent glyph outlines at their own weight instead of bending with the art, as the drawn art of users' `.ai` files strokes type in an envelope. This is VectorCraft's own rule from those files: the public page names applied effects and graphic styles, not strokes. This holds in an envelope inside an envelope too. Paths' strokes, geometry effects (type's included), opacity masks (on type too), linear gradients and pattern fills bend as before; Expand gives type's bent outlines with their strokes on them. The visual bounds of envelopes, blends and repeats, and the reach of symbol art, count type's character strokes as type's own visual bounds do (half the weight of a centred stroke); they left them out, though those strokes already painted past an envelope's grid. Envelopes of stroked type made in VectorCraft before this draw their strokes at their own weight now (#6644; `crates/engine/src/tests/envelope_distort.rs`, `crates/effects/src/bake/tests.rs`). The four polynomial distributions are original approximations of the public description, not measured numeric parity. See [Blend panel overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html). A blend in a `.ai` or EPS opened from its editing data keeps a Specified Distance spacing with its distance ([Blend Options](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-options-overview.html)) where VectorCraft lays out as many steps between each pair of keys as the file draws, in the same places and colors. A Smooth Color blend opens live only where VectorCraft's own Smooth Color step count equals the drawn steps, and VectorCraft often counts a different number. A blend that VectorCraft doesn't lay out as drawn keeps its drawn steps with a note (`import::ai::tests::a_blend_keeps_its_spacing`, `a_blend_of_three_keys_keeps_its_distance_between_each_pair`, `a_blend_whose_spacing_doesnt_lay_out_its_steps_keeps_them`). - Create Strokes uses exact squared Euclidean distances and Guo–Hall thinning in bounded per-blob crops. Maximal-disc pruning, split-crossing merges and degree-two joins simplify its skeleton graph. The whole-blob width rule and ink fitting remain; 46 code-drawn inputs measure ends and junctions in [`image-trace-quality.md`](image-trace-quality.md#centre-lines). Junction degrees measure 44/45 correct in each input variant; remaining spurs are recorded. This is a measured skeleton improvement; the Image Trace score, missing per-feature selection and width controls, and estimates remain unchanged. + - Create Strokes decides stroke or fill per feature, as the [help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/image-trace-panel-options.html) describes the Strokes width: the widest feature of the image that can become a stroke. A shape wider than Stroke somewhere keeps as its area every disc wider than Stroke that fits in it, and each piece outside those discs that reaches out of them at least one and a half times its own width (and 3 px) is traced as a stroked center line, its end at the area carried to the cut so the line's cap closes the join. Corners and edge slivers stay in the area. Which pieces count as features is VectorCraft's own rule. Each line still has one width; without Fills, the area is a 1 px outline as before. Tests: `thin_features_of_a_wide_shape_are_strokes_and_its_body_a_fill`, `wide_shapes_without_thin_features_stay_one_fill` and `distances_to_seeds_equal_brute_force` in `vectorcraft-trace`. The Image Trace score and estimates are unchanged. Object › Live Paint › Merge adds the other selected paths and Live Paint groups to the bottom selected Live Paint group ([Live Paint groups](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/live-paint-groups.html)), which keeps its id, the paint of its faces and edges, and its name, lock, visibility, transparency, appearance, opacity mask and graphic style link. Object › Live Paint › Make with a Live Paint group selected, and a Live Paint Bucket click on a selected path beside a selected Live Paint group, add the paths to that group the same way. Make, Merge and the Live Paint Bucket take paths, compound paths and groups of them; with type, an image or another object among the selection they report that it has to be converted to paths first and change nothing, as type and raster images can't go into a Live Paint group directly ([Create Live Paint groups](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/create-live-paint-groups.html)); before, such an object went among the group's hidden sources and vanished from the canvas. Evidence: `tests_build::live_paint_refuses_type_and_images_and_changes_nothing`. With the Live Paint Bucket selected, Alt-click on vector art samples its fill, stroke and stroke weight into the paint defaults ([Paint with the Live Paint Bucket tool](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html)). On a placed image it samples the image pixel as a solid fill with no stroke. Alt+Shift-click samples only the color under the pointer, including an intermediate gradient color or image pixels, into the active fill or stroke ([Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). Neither click paints or changes the selection or selected art, and the next Bucket click paints with the sampled paint. Evidence: `tests_build::live_paint_bucket_alt_sample_paints_next_face_without_changing_selection`. Double-clicking the Live Paint Bucket opens Live Paint Bucket Options ([Paint with the Live Paint Bucket tool](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html)): Paint Fills (on) and Paint Strokes (off) set whether a click paints faces, edges or both, Highlight turns the outline of the face or edge under the pointer on or off, and Color and Width set it (red and 4 px by default). Faces are outlined at the Width and edges at half of it, as the page says faces are highlighted with a thick line and edges with a thin line. With both on, a click paints the edge within 4 px of the pointer, else the face, and Shift switches to Paint Fills only; with one on, Shift switches to the other. The options last across tool switches and are saved with the preferences (`tool.setOption {tool: "livePaintBucket"}`). Evidence: `builder::tests::{bucket_options_choose_what_a_click_paints, bucket_options_set_the_highlight, bucket_highlights_an_edge_thinner_than_a_face}`, `dialogs::live_paint_bucket::tests::double_clicking_the_tool_opens_its_options_and_ok_sets_them`. diff --git a/docs/three-d.md b/docs/three-d.md index 38b59023dc..c701585b88 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -127,6 +127,11 @@ The rest is our reading: grid stays flat. - A stroke whose outline takes more than 65,536 points, or whose solid takes more than 163,840 faces, is left out, and the fill's solid still draws. +- The solids of one Extrude & Bevel or Inflate effect keep up to 163,840 faces together: the fill's and every + stroke's, and on a group or layer every member's (VectorCraft's own limit). The solids are built in order, and + once their faces pass it no later solid is built: the object draws its source art, and applying or editing the + effect, Export 3D Object and **Expand as Wireframes** report that the 3D surface is too complex. A stroke left + out for its own limits does not count. ## Groups diff --git a/docs/ui-parity.md b/docs/ui-parity.md index ee8a5579b2..0eded20196 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-13 · **Change:** minor (Outline Stroke is in the canvas context menu (#5267; 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-13 · **Change:** minor (Outline Stroke is in the canvas context menu (#5267; 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) > > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > @@ -51,6 +51,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-13 | minor | Graphic Styles: in a panel made taller the list fills the space above the footer instead of stopping at 220 pt (#2992; `the_list_fills_a_tall_panel_above_its_footer` in `crates/ui-egui/src/panels/graphic_styles.rs`). Scores and estimates unchanged. | | 2026-11-13 | minor | Library panels (swatch, Color Book, brush, symbol and graphic style libraries): in a panel made taller the list fills the space above the footer instead of scrolling inside 220 or 280 pt (#2992; `the_list_fills_a_tall_panel_above_its_footer` in `crates/ui-egui/src/panels/library_panel/tests.rs`). Scores and estimates unchanged. | | 2026-11-13 | minor | Swatches: in a panel made taller the swatch list fills the space above the footer instead of scrolling inside 150 or 200 pt (#1638). Scores unchanged. | | 2026-11-08 | minor | Style panels: a double-click on a user character style's row opens its Character Style Options (`ui.charStyleOptions`), and on a paragraph style's row its Paragraph Style Options (rename); the Character Style Options dialog keeps a fixed width and scrolls its sections in a shorter window, so OK and Cancel stay on screen. Tests `panels::text_styles::tests::double_clicking_a_character_style_row_opens_its_options` and `dialogs::char_style_options::tests::the_sections_scroll_in_a_window_shorter_than_the_general_list`. Scores and estimates unchanged. | @@ -167,6 +168,7 @@ tools, never checked side by side) isn't captured row by row. | Curvature tool: click/drag points, double-click or Alt-click for a corner, temporary Direct Selection, point conversion | partial | circular point markers without direction handles or duplicate markers, Anchor Size and Hide Edges regression-tested (#1236, in part); curve geometry: each stretch of three points follows the circle through them (handles along its tangent, chord/(3·cos²(α/2)) long, shorter in a turn tighter than 30°), open ends curving in, the same rule for the rubber band, dragged, inserted and converted points (#1236, in part); neighbours of a point dragged on an existing path keep their tangents, and modifiers requested in #975 remain | | Icon-strip flyout resizing (#5713) | done | Canvas-side edge and bottom; user size persists after reopening and workspace restore; Glyphs and Artboards pointer/cursor regression | | Icon-strip flyout resizing from the top (storytold/craft-libs#1094) | done | Top edge (a 4 pt band over the tab strip) and the canvas-side top corner; the bottom and the icon-column edge stay; the moved top persists after reopening and workspace restore; `an_icon_flyout_grows_upward_from_its_top_edge_and_free_corner` | +| Graphic Styles list fills a taller panel (#2992) | done | Docked, floating or in a resized flyout, the list takes the height above the panel's footer, as the Artboards list does; outside a sized panel it stays 220 pt; `the_list_fills_a_tall_panel_above_its_footer` | | Library panels' lists fill a taller panel (#2992) | done | Swatch (Color Books among them), brush, symbol and graphic style library panels: docked, floating or in a resized flyout, the list takes the height above the panel's footer; outside a sized panel it stays 220 pt (280 pt for large thumbnails); `the_list_fills_a_tall_panel_above_its_footer` in `panels/library_panel/tests.rs` | | Swatches list fills a taller panel (#1638) | done | Docked, floating or in a resized flyout, the swatch list takes the height above the panel's footer, as the Artboards list does; outside a sized panel it stays 150 pt (200 pt for large thumbnails); `the_list_fills_a_tall_panel_above_its_footer` in `panels/swatches/tests.rs` | | Layers panel lists a blend's spine (#4820) | done | an open blend shows a `` row below its key objects, where Release leaves the spine; a click selects the blend (Shift/Cmd toggles it) so Direct Selection edits the spine; a locked blend's row selects nothing; no row while searching or filtering (`a_blends_spine_is_a_row_below_its_keys_that_selects_the_blend`) |