diff --git a/ASSETS.md b/ASSETS.md index 5658882d48..dbdd8b84d8 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -20,7 +20,7 @@ Every non-code asset in this repository (icons, images, fonts, example art, colo **Policy (mandatory):** VectorCraft contains **no Adobe iconography, images, artwork, presets, swatch/brush/symbol/pattern libraries or ICC profiles**. Every asset is either original work by VectorCraft contributors, or third-party material under an open licence (OSI open source, public domain / CC0, or Creative Commons that allows redistribution), and it is attributed below. Screenshots of Adobe software are never committed. The one exception is the ArtCraft name, wordmark and logos in `docs/brand/`: ArtCraft trademarks, not open source, usable only under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt). -Generated-in-code art is original and has no file to list. This covers the default swatches, brushes, symbols, patterns, graphic styles, image-trace presets and the vector tool cursors (`crates/ui-egui/src/cursors.rs`). +Generated-in-code art is original and has no file to list. This covers the default swatches, brushes, symbols, patterns, graphic styles, image-trace presets, the vector tool cursors (`crates/ui-egui/src/cursors.rs`) and the Learn panel's practice samples (`crates/ui-egui/src/panels/learn/samples.rs`). **Font files are never committed here.** Fonts shared by the Crafting Apps live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts). The small Latin UI/document fonts below predate that rule and stay. diff --git a/crates/color/src/recolor.rs b/crates/color/src/recolor.rs index 93c0ad0f37..05c386e405 100644 --- a/crates/color/src/recolor.rs +++ b/crates/color/src/recolor.rs @@ -567,6 +567,112 @@ pub fn theme_palette(samples: &[(Color, f32)], n: usize) -> Vec { groups.into_iter().map(|g| g.2).collect() } +/// Colors that [`weigh`] moves from one row to another as one: a color they are shown by, how +/// often the art uses them and the row they are in. A fixed unit (such as the color a row is +/// shown by) stays in its row. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct WeighUnit { + pub color: Color, + pub uses: f64, + pub row: usize, + pub fixed: bool, +} + +/// The unit-by-row comparisons one [`weigh`] makes, at most. +const WEIGH_WORK: usize = 50_000_000; + +/// The uses of `u` that count: a positive finite number, else 0. +fn unit_uses(u: &WeighUnit) -> f64 { + if u.uses.is_finite() && u.uses > 0.0 { u.uses } else { 0.0 } +} + +/// Each row's share of the uses of `units`, in percent (0 for every row when nothing is used). +/// Units whose row is past `rows`, or whose uses are not a positive finite number, count nothing. +pub fn row_shares(units: &[WeighUnit], rows: usize) -> Vec { + let mut sums = vec![0.0; rows]; + for u in units { + if let Some(s) = sums.get_mut(u.row) { + *s += unit_uses(u); + } + } + let total: f64 = sums.iter().sum(); + if total <= 0.0 { + return vec![0.0; rows]; + } + sums.iter().map(|s| s / total * 100.0).collect() +} + +/// For Recolor Artwork's Prominent Colors (our own rule): the row each of `units` goes to so that +/// each row's share of the uses comes as near its share of `weights` as whole units allow. One +/// unit moves at a time, while a move brings the rows' shares nearer their weights (the sum of +/// every row's distance from its weight falls); of those moves, the one taken is the unit nearest +/// in Lab (CIEDE2000) to the color of the row it goes to (`anchors`), compared with the row it +/// leaves; on a tie, the move that brings the shares nearest. Fixed units, units in a row past +/// `anchors` and units used no times stay where they are. Weights that are negative or not finite +/// count as 0; when no weight is positive, every unit stays. The moves stop after +/// [`WEIGH_WORK`] comparisons of a unit with a row, and when the movable units times the rows pass +/// it, every unit stays. +pub fn weigh(units: &[WeighUnit], anchors: &[Color], weights: &[f64]) -> Vec { + let mut row: Vec = units.iter().map(|u| u.row).collect(); + let n = anchors.len(); + let given = |r: usize| weights.get(r).copied().filter(|x| x.is_finite() && *x > 0.0).unwrap_or(0.0); + // Scaled by the largest weight first, so the sum stays finite. + let top = (0..n).map(given).fold(0.0, f64::max); + let w = |r: usize| if top > 0.0 { given(r) / top } else { 0.0 }; + let sum_w: f64 = (0..n).map(w).sum(); + let movable: Vec = (0..units.len()).filter(|&i| !units[i].fixed && units[i].row < n && unit_uses(&units[i]) > 0.0).collect(); + let per_pass = movable.len().saturating_mul(n); + if sum_w <= 0.0 || n < 2 || movable.is_empty() || per_pass > WEIGH_WORK { + return row; + } + let mut sums = vec![0.0; n]; + for u in units.iter().filter(|u| u.row < n) { + sums[u.row] += unit_uses(u); + } + let total: f64 = sums.iter().sum(); + let target: Vec = (0..n).map(|r| w(r) / sum_w * total).collect(); + let anchor_labs: Vec = anchors.iter().map(|c| c.to_lab()).collect(); + // Each movable unit's distance to each row's color. + let dist: Vec> = movable + .iter() + .map(|&i| { + let l = units[i].color.to_lab(); + anchor_labs.iter().map(|a| delta_e2000(*a, l)).collect() + }) + .collect(); + // A move must bring the shares nearer by more than rounding. + let eps = total * 1e-9; + for _ in 0..WEIGH_WORK / per_pass { + let mut best: Option<(f32, f64, usize, usize)> = None; + for (m, &i) in movable.iter().enumerate() { + let (a, x) = (row[i], unit_uses(&units[i])); + let before_a = (sums[a] - target[a]).abs(); + let after_a = (sums[a] - x - target[a]).abs(); + for b in (0..n).filter(|&b| b != a) { + let gain = before_a + (sums[b] - target[b]).abs() - after_a - (sums[b] + x - target[b]).abs(); + if gain <= eps { + continue; + } + let cost = dist[m][b] - dist[m][a]; + let better = match best { + None => true, + Some((c, g, ..)) => cost < c || (cost == c && gain > g), + }; + if better { + best = Some((cost, gain, m, b)); + } + } + } + let Some((_, _, m, b)) = best else { break }; + let i = movable[m]; + let x = unit_uses(&units[i]); + sums[row[i]] -= x; + sums[b] += x; + row[i] = b; + } + row +} + /// A set of colours to snap to (Limit to Library), with their Lab values cached. #[derive(Clone, Debug, Default)] pub struct Palette(Vec<(Color, Lab)>); @@ -911,4 +1017,55 @@ mod tests { assert!(matches!(Rng::new(3).saturation_brightness(Color::lab(50.0, 40.0, 20.0)), Color::Lab { .. })); assert_eq!(Rng::new(3).saturation_brightness(Color::gray(0.4)).to_hsb()[1], 0.0, "greys stay grey"); } + + fn unit(color: Color, uses: f64, row: usize, fixed: bool) -> WeighUnit { + WeighUnit { color, uses, row, fixed } + } + + #[test] + fn row_shares_are_percent_of_the_uses() { + let units = [unit(Color::rgb(1.0, 0.0, 0.0), 3.0, 0, true), unit(Color::rgb(0.0, 0.0, 1.0), 1.0, 1, true), unit(Color::WHITE, 5.0, 4, false)]; + assert_eq!(row_shares(&units, 2), vec![75.0, 25.0]); + assert_eq!(row_shares(&[], 2), vec![0.0, 0.0]); + assert_eq!(row_shares(&[unit(Color::WHITE, f64::NAN, 0, false)], 1), vec![0.0]); + } + + #[test] + fn weigh_moves_the_nearest_colors_toward_the_weights() { + let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)); + let units = [ + unit(red, 1.0, 0, true), + unit(Color::rgb(0.9, 0.1, 0.3), 1.0, 0, false), + unit(Color::rgb(0.5, 0.0, 0.8), 1.0, 0, false), + unit(blue, 1.0, 1, true), + ]; + // Equal weights: the reddish purple, nearer blue than the red-pink is, moves. + assert_eq!(weigh(&units, &[red, blue], &[1.0, 1.0]), vec![0, 0, 1, 1]); + // Most of the weight on blue: both movable colors go, the row's own color stays. + assert_eq!(weigh(&units, &[red, blue], &[0.0, 1.0]), vec![0, 1, 1, 1]); + // Weights already met, or none positive: nothing moves. + assert_eq!(weigh(&units, &[red, blue], &[3.0, 1.0]), vec![0, 0, 0, 1]); + assert_eq!(weigh(&units, &[red, blue], &[0.0, f64::NAN]), vec![0, 0, 0, 1]); + assert_eq!(weigh(&units, &[red, blue], &[1e308, 1e308]), vec![0, 0, 1, 1], "huge weights act as equal ones"); + assert_eq!(weigh(&units, &[red], &[1.0]), vec![0, 0, 0, 1], "a row past the anchors keeps its units"); + } + + #[test] + fn weigh_takes_whole_units_and_stops_when_no_move_helps() { + let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)); + // A heavy unit: moving it would overshoot by more than staying misses. + let units = [unit(red, 1.0, 0, true), unit(Color::rgb(0.8, 0.0, 0.2), 10.0, 0, false), unit(blue, 10.0, 1, true)]; + assert_eq!(weigh(&units, &[red, blue], &[1.0, 1.4]), vec![0, 0, 1]); + assert_eq!(weigh(&units, &[red, blue], &[1.0, 20.0]), vec![0, 1, 1]); + // Many units: the result still follows the weights. + let many: Vec = (0..400).map(|i| unit(Color::rgb(i as f32 / 400.0, 0.2, 1.0 - i as f32 / 400.0), 1.0, 0, i == 0)).collect(); + let rows = weigh(&many, &[Color::rgb(0.0, 0.2, 1.0), Color::rgb(1.0, 0.2, 0.0)], &[1.0, 3.0]); + assert_eq!(rows.iter().filter(|r| **r == 1).count(), 300); + assert!(rows[399] == 1 && rows[1] == 0, "the reddest colors go to the red row"); + // Past the work limit (8,000 units by 7,000 rows) nothing moves. + let units: Vec = (0..8_000).map(|i| unit(Color::WHITE, 1.0, 0, i == 0)).collect(); + let anchors = vec![Color::BLACK; 7_000]; + let weights = vec![1.0; 7_000]; + assert!(weigh(&units, &anchors, &weights).iter().all(|r| *r == 0)); + } } diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index d9e179286f..f4877b0a49 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -1326,27 +1326,39 @@ impl Spine { let s = if s.is_finite() { s.clamp(0.0, self.length()) } else { 0.0 }; let sp = &self.subpath; let n = sp.segment_count(); - let mut start = 0.0; - for i in 0..n { - let c = sp.segment(i); - let end = self.anchor_length(i + 1).unwrap_or(self.length()); - if s <= end || i + 1 == n { - let local_s = (s - start).max(0.0) / (end - start).max(1e-12) * c.arclen(1e-9); - let t = c.inv_arclen(local_s, 1e-9).clamp(0.0, 1.0); - let e = c.eval(t); - let tv = c.deriv().eval(t).to_vec2(); - // Where a handle sits on its anchor the derivative vanishes there: take the - // direction between points a little before and after instead. - let tv = if tv.hypot2() < 1e-24 { c.eval((t + 1e-3).min(1.0)) - c.eval((t - 1e-3).max(0.0)) } else { tv }; - return (Point::new(e.x, e.y), tv.y.atan2(tv.x)); - } - start = end; + if n == 0 { + return (self.pts.first().copied().unwrap_or_default(), 0.0); } - // Only a spine without segments gets here: the loop returns at the last one. - (self.pts.first().copied().unwrap_or_default(), 0.0) + let i = segment_at(&self.anchors, n, s, || {}); + let c = sp.segment(i); + let start = if i == 0 { 0.0 } else { self.anchor_length(i).unwrap_or(0.0) }; + let end = self.anchor_length(i + 1).unwrap_or(self.length()); + let local_s = (s - start).max(0.0) / (end - start).max(1e-12) * c.arclen(1e-9); + let t = c.inv_arclen(local_s, 1e-9).clamp(0.0, 1.0); + let e = c.eval(t); + let tv = c.deriv().eval(t).to_vec2(); + // Where a handle sits on its anchor the derivative vanishes there: take the + // direction between points a little before and after instead. + let tv = if tv.hypot2() < 1e-24 { c.eval((t + 1e-3).min(1.0)) - c.eval((t - 1e-3).max(0.0)) } else { tv }; + (Point::new(e.x, e.y), tv.y.atan2(tv.x)) } } +/// The segment of a spine with `n` segments (`n > 0`) that holds arc length `s`: the first one whose +/// end is at or past `s`, or the last one when none is. `anchors` holds the arc length at each +/// anchor, so segment `i` ends at `anchors[i + 1]`, and the last segment of a closed spine, which has +/// no entry for its end, ends at the spine's length. The lengths never decrease (each is a sum of +/// distances that are not negative, at most `+inf` and never NaN), so a binary search finds the +/// segment in about `log2(n)` comparisons. `probe` is called once for each comparison. +fn segment_at(anchors: &[f64], n: usize, s: f64, mut probe: impl FnMut()) -> usize { + let ends = anchors.get(1..n.min(anchors.len())).unwrap_or_default(); + ends.partition_point(|&end| { + probe(); + end < s + }) + .min(n.saturating_sub(1)) +} + /// The anchor of the first subpath each key sits on, when they are all valid for `n` anchors. fn pinned(spec: &BlendSpec, keys: usize, n: usize) -> Option> { (spec.key_anchors.len() == keys && keys >= 2 && spec.key_anchors.iter().all(|a| (*a as usize) < n)) @@ -1891,6 +1903,76 @@ mod tests { assert!(end.is_finite(), "{end}"); } + /// [`Spine::at_length`] by walking the segments from the first, as a reference for the search. + fn walked_at_length(sp: &Spine, s: f64) -> (Point, f64) { + let s = if s.is_finite() { s.clamp(0.0, sp.length()) } else { 0.0 }; + let n = sp.subpath.segment_count(); + let mut start = 0.0; + for i in 0..n { + let c = sp.subpath.segment(i); + let end = sp.anchor_length(i + 1).unwrap_or(sp.length()); + if s <= end || i + 1 == n { + let local_s = (s - start).max(0.0) / (end - start).max(1e-12) * c.arclen(1e-9); + let t = c.inv_arclen(local_s, 1e-9).clamp(0.0, 1.0); + let e = c.eval(t); + let tv = c.deriv().eval(t).to_vec2(); + let tv = if tv.hypot2() < 1e-24 { c.eval((t + 1e-3).min(1.0)) - c.eval((t - 1e-3).max(0.0)) } else { tv }; + return (Point::new(e.x, e.y), tv.y.atan2(tv.x)); + } + start = end; + } + panic!("a spine without segments") + } + + /// The search picks the same segment as walking them in order, so points and tangents stay the + /// same: on open and closed spines, one segment, curves, and zero-length segments whose anchors + /// share an arc length; at every anchor, between anchors, at both ends, past them, and for + /// values that are not finite. + #[test] + fn spine_lookup_matches_walking_the_segments() { + let p = Point::new; + let bow = SubPath::new( + vec![Anchor::smooth(p(0.0, 0.0), p(50.0, 50.0)), Anchor::smooth(p(100.0, 0.0), p(150.0, -50.0)), Anchor::corner(p(200.0, 0.0))], + false, + ); + let spines = [ + SubPath::polyline(&[p(0.0, 0.0), p(10.0, 0.0), p(10.0, 0.0), p(10.0, 0.0), p(30.0, 5.0), p(30.0, 5.0)], false), + SubPath::polyline(&[p(0.0, 0.0), p(0.0, 0.0), p(40.0, 0.0), p(40.0, 30.0)], true), + SubPath::polyline(&[p(0.0, 0.0), p(40.0, 0.0), p(40.0, 30.0), p(0.0, 0.0)], true), + SubPath::polyline(&[p(0.0, 0.0), p(25.0, 25.0)], false), + SubPath::polyline(&[p(0.0, 0.0), p(25.0, 25.0)], true), + bow.clone(), + SubPath { closed: true, ..bow }, + ]; + for sub in spines { + let sp = Spine::new(&PathData::single(sub)).unwrap(); + let len = sp.length(); + let mut lengths = vec![0.0, len, -1.0, len + 1.0, -len, f64::NAN, f64::INFINITY, f64::NEG_INFINITY, f64::MAX, f64::MIN]; + lengths.extend(sp.anchors.iter().flat_map(|&a| [a, a - 1e-9, a + 1e-9])); + lengths.extend((0..=400).map(|k| len * k as f64 / 400.0)); + for s in lengths { + assert_eq!(sp.at_length(s), walked_at_length(&sp, s), "s = {s} on {:?}", sp.anchors); + } + } + } + + /// Finding the segment for an arc length on a spine of thousands of segments takes a few + /// comparisons, not one for each segment before it. + #[test] + fn spine_lookup_compares_a_few_segment_ends() { + let pts: Vec = (0..=4096).map(|i| Point::new(i as f64, if i % 2 == 0 { 0.0 } else { 1.0 })).collect(); + let sp = Spine::new(&PathData::single(SubPath::polyline(&pts, false))).unwrap(); + let n = sp.subpath.segment_count(); + assert_eq!(n, 4096); + for s in [sp.length() - 0.5, sp.length(), sp.length() / 2.0, 0.25] { + let mut compared = 0; + let i = segment_at(&sp.anchors, n, s, || compared += 1); + assert!(compared <= 13, "{compared} comparisons at {s}"); + assert_eq!(sp.at_length(s), walked_at_length(&sp, s)); + assert!(sp.anchors[i] <= s && (i + 1 == n || s <= sp.anchors[i + 1]), "segment {i} at {s}"); + } + } + #[test] fn easing_keeps_the_ends_and_stays_monotone() { use crate::live::{BlendEase, BlendEaseType as K}; diff --git a/crates/doc/src/cmyk.rs b/crates/doc/src/cmyk.rs index ea2c44215e..391fc39633 100644 --- a/crates/doc/src/cmyk.rs +++ b/crates/doc/src/cmyk.rs @@ -140,6 +140,21 @@ pub fn tiff_orientation(bytes: &[u8]) -> Option { d.find_tag_unsigned::(tiff::tags::Tag::Orientation).ok().flatten() } +/// The EXIF orientation of encoded image `bytes` when it turns or flips the pixels; `None` when +/// it leaves them as stored, or the image has none. A TIFF the image decoder can't open (one with +/// extra samples) has its Orientation tag read from its first image ([`tiff_orientation`]). Reads +/// only the image's header and metadata; `None` for an [`oversized_tiff`], which no decoder opens. +pub fn exif_orientation(bytes: &[u8]) -> Option { + use image::ImageDecoder as _; + use image::metadata::Orientation; + if oversized_tiff(bytes).is_some() { + return None; + } + let decoded = || image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_decoder().ok()?.orientation().ok(); + let tagged = || tiff_orientation(bytes).and_then(|v| Orientation::from_exif(u8::try_from(v).ok()?)); + decoded().or_else(tagged).filter(|o| *o != Orientation::NoTransforms) +} + /// Does the TIFF `d` reads store one plane per channel (PlanarConfiguration 2)? fn planar(d: &mut tiff::decoder::Decoder>) -> bool { d.find_tag_unsigned::(tiff::tags::Tag::PlanarConfiguration).ok().flatten().is_some_and(|p| p != 1) diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 708d0aee03..057a9df6a6 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -286,7 +286,9 @@ impl Document { self.next_id = self.next_id.max(id); } - /// Ensure `next_id` is above every id in the tree (after deserializing foreign data). + /// Ensure `next_id` is above every id in the tree (after deserializing foreign data), then give + /// the objects outside the layer tree (opacity-mask art, symbols, graph designs and patterns) + /// whose id is missing or already taken a new one, so each stored object has an id of its own. pub fn fix_next_id(&mut self) { // Ids from [`MAX_NEXT_ID`] up (a damaged or hand-made file: #1718) are left out, as is a // counter up there: new ids start under them and never reach them, where counting on from @@ -297,13 +299,12 @@ impl Document { max = max.max(id); } }; - for l in &self.layers { - l.walk(&mut |n| see(n.id.0)); - } + self.visit_stored(|n, _| see(n.id.0)); self.slices.iter().for_each(|s| see(s.id.0)); self.assets.iter().for_each(|a| see(a.id)); let counter = Some(self.next_id).filter(|n| *n <= MAX_NEXT_ID).unwrap_or(0); self.next_id = counter.max(max.saturating_add(1)); + self.renumber_stored_duplicates(); } /// Find a node anywhere in the tree. diff --git a/crates/doc/src/document_guides.rs b/crates/doc/src/document_guides.rs index 4ec7aab1f6..14d0404bfc 100644 --- a/crates/doc/src/document_guides.rs +++ b/crates/doc/src/document_guides.rs @@ -554,6 +554,13 @@ impl Document { t.cached_baselines.clear(); t.cached_ink = None; } + // Opacity-mask art is stored art too: the copy's gets ids of its own. + if let Some(art) = n.extras().mask.as_ref().map(|m| Arc::clone(&m.art)) { + let art = Arc::new(self.reid(&art)); + if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) { + m.art = art; + } + } let on_path = n.extras().objects_on_path.is_some(); let mut renamed = std::collections::HashMap::new(); if let Some(ch) = n.children_mut() { diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index a1122e5a7c..63a2676f77 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -142,6 +142,7 @@ mod graphic_style; mod guides; mod limits; mod records; +mod stored_art; mod units; pub use artboard::{ARTBOARD_GAP, Artboard, ArtboardSide, LockedArtboards, RetiredArtboardId, VIDEO_PIXEL_ASPECT_RANGE, VIDEO_SAFE_INSETS}; @@ -154,6 +155,7 @@ pub use guides::{GridPrefs, Guide, RulerMode}; use limits::MAX_NEXT_ID; pub use limits::{DocError, FORMAT_VERSION, MAX_COORD}; pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, SvgFilter, Symbol, SymbolEdit}; +pub use stored_art::{StoredPlace, StoredRoot}; pub use units::{ColorMode, Unit, parse_number}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] diff --git a/crates/doc/src/live.rs b/crates/doc/src/live.rs index 39fe8cbc43..cf7a4d2fa0 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -568,23 +568,167 @@ mod tests { } } + /// The outline of a 200 × 100 box whose top side is `pieces`, end to end from (0, 0) to + /// (200, 0), and whose other sides are straight. + fn top_of_pieces(pieces: &[CubicBez]) -> PathData { + let pt = |p: Point| (p.x, p.y); + let mut knots: Vec = vec![]; + for (k, c) in pieces.iter().enumerate() { + let h_in = if k == 0 { pt(c.p0) } else { pt(pieces[k - 1].p2) }; + knots.push((pt(c.p0), h_in, pt(c.p1))); + } + let last = pieces.last().unwrap(); + knots.push(((200.0, 0.0), pt(last.p2), (200.0, 0.0))); + knots.extend([((200.0, 100.0), (200.0, 100.0), (200.0, 100.0)), ((0.0, 100.0), (0.0, 100.0), (0.0, 100.0))]); + outline(&knots) + } + + /// A top curve whose parameter runs fast at its start and slow at its end. + const UNEVEN_TOP: CubicBez = + CubicBez { p0: Point::new(0.0, 0.0), p1: Point::new(120.0, -60.0), p2: Point::new(190.0, -30.0), p3: Point::new(200.0, 0.0) }; + #[test] - fn a_split_curve_moves_the_top_object_share_to_its_new_anchor() { - // Splitting the top curve at t = 0.3 keeps its shape but changes the polygon shares: the - // new anchor lands at the first piece's share, not at u = 0.3. - let top = CubicBez::new((0.0, 0.0), (40.0, -40.0), (160.0, -40.0), (200.0, 0.0)); - let (a, b) = (top.subsegment(0.0..0.3), top.subsegment(0.3..1.0)); - let path = outline(&[ - ((0.0, 0.0), (0.0, 0.0), a.p1.into()), - (a.p3.into(), a.p2.into(), b.p1.into()), - ((200.0, 0.0), b.p2.into(), (200.0, 0.0)), - ((200.0, 100.0), (200.0, 100.0), (200.0, 100.0)), - ((0.0, 100.0), (0.0, 100.0), (0.0, 100.0)), - ]); - let c = Coons::from_top_object(&path, None).unwrap(); + fn a_split_curve_keeps_the_top_object_patch() { + // Splitting the top curve at t = 0.3, or into thirds, keeps its shape, and the patch stays + // the unsplit curve's: the new anchors land at u = 0.3, 1/3 and 2/3 (to within how finely + // the side is sampled), where the pieces' control polygons would have put them several + // points away. + let whole = Coons::from_top_object(&top_of_pieces(&[UNEVEN_TOP]), None).unwrap(); + for cuts in [vec![0.3], vec![1.0 / 3.0, 2.0 / 3.0]] { + let ends: Vec = std::iter::once(0.0).chain(cuts.iter().copied()).chain([1.0]).collect(); + let pieces: Vec = ends.windows(2).map(|w| UNEVEN_TOP.subsegment(w[0]..w[1])).collect(); + let c = Coons::from_top_object(&top_of_pieces(&pieces), None).unwrap(); + let total: f64 = pieces.iter().map(|p| polygon(*p)).sum(); + for (k, t) in cuts.iter().enumerate() { + let anchor = pieces[k].p3; + assert!(c.eval(*t, 0.0).distance(anchor) < 0.02, "{cuts:?}: u {t} → {:?}, want {anchor:?}", c.eval(*t, 0.0)); + let share: f64 = pieces[..=k].iter().map(|p| polygon(*p)).sum::() / total; + assert!(c.eval(share, 0.0).distance(anchor) > 2.0, "{cuts:?}: the polygon share {share} lands on the anchor"); + } + for (u, v) in [(0.1, 0.0), (0.3, 0.2), (0.5, 0.5), (0.62, 0.0), (0.9, 0.7), (0.97, 1.0)] { + let (p, q) = (c.eval(u, v), whole.eval(u, v)); + assert!(p.distance(q) < 1e-9, "{cuts:?}: ({u}, {v}) → {p:?}, unsplit {q:?}"); + } + } + } + + #[test] + fn a_split_curve_keeps_the_top_object_patch_when_split_at_a_cusp() { + // The top curve stops at t = 0.25 (a cusp), and an anchor splits it there: both handles at + // the split lie on the anchor, and the patch with the corners given stays the unsplit + // curve's. + let cusp = CubicBez::new((0.0, 0.0), (30.0, -40.0), (-58.0, 24.0), (200.0, 0.0)); + let pieces = [cusp.subsegment(0.0..0.25), cusp.subsegment(0.25..1.0)]; + assert!(pieces[0].p2.distance(pieces[0].p3) < 1e-9 && pieces[1].p1.distance(pieces[1].p0) < 1e-9); + let whole = Coons::from_top_object(&top_of_pieces(&[cusp]), Some([0, 1, 2, 3])).unwrap(); + let c = Coons::from_top_object(&top_of_pieces(&pieces), Some([0, 2, 3, 4])).unwrap(); + for (u, v) in [(0.1, 0.0), (0.25, 0.0), (0.3, 0.2), (0.5, 0.5), (0.62, 0.0), (0.9, 0.7), (0.97, 1.0)] { + let (p, q) = (c.eval(u, v), whole.eval(u, v)); + assert!(p.distance(q) < 1e-6, "({u}, {v}) → {p:?}, unsplit {q:?}"); + } + } + + #[test] + fn a_split_curve_keeps_the_top_object_patch_where_it_barely_moves_and_runs_straight() { + // A straight top curve that barely moves at t = 0.25 and doesn't bend there: split there, + // the handles at the split are a few thousandths of a point long and the pieces don't bend + // at all, and the patch with the corners given stays the unsplit curve's. + let slow = CubicBez::new((0.0, 0.0), (28.578125, 0.0), (-57.109375, 0.0), (200.0, 0.0)); + let pieces = [slow.subsegment(0.0..0.25), slow.subsegment(0.25..1.0)]; + let (into, out) = (pieces[0].p3.distance(pieces[0].p2), pieces[1].p0.distance(pieces[1].p1)); + assert!(into > 0.0 && out > 0.0 && into.max(out) < 0.01, "{into} {out}"); + let whole = Coons::from_top_object(&top_of_pieces(&[slow]), Some([0, 1, 2, 3])).unwrap(); + let c = Coons::from_top_object(&top_of_pieces(&pieces), Some([0, 2, 3, 4])).unwrap(); + for (u, v) in [(0.1, 0.0), (0.25, 0.0), (0.3, 0.2), (0.5, 0.5), (0.62, 0.0), (0.9, 0.7), (0.97, 1.0)] { + let (p, q) = (c.eval(u, v), whole.eval(u, v)); + assert!(p.distance(q) < 1e-6, "({u}, {v}) → {p:?}, unsplit {q:?}"); + } + } + + #[test] + fn a_top_object_joins_a_split_curve_saved_with_rounded_coordinates() { + // A file saves the pieces of a curve split into thirds, or into tenths, with its + // coordinates rounded to 0.001 pt, on an outline 5, 200 or 5,000 pt wide: the side is + // still that curve, to within 0.02 pt. + let round = |p: Point| Point::new((p.x * 1000.0).round() / 1000.0, (p.y * 1000.0).round() / 1000.0); + for cuts in [3u32, 10] { + let pieces: Vec = + (0..cuts).map(|k| UNEVEN_TOP.subsegment(f64::from(k) / f64::from(cuts)..f64::from(k + 1) / f64::from(cuts))).collect(); + for scale in [0.025, 1.0, 25.0] { + let mut split = top_of_pieces(&pieces); + split.transform(Affine::scale(scale)); + for a in split.subpaths.iter_mut().flat_map(|sp| sp.anchors.iter_mut()) { + (a.p, a.h_in, a.h_out) = (round(a.p), round(a.h_in), round(a.h_out)); + } + let mut whole = top_of_pieces(&[UNEVEN_TOP]); + whole.transform(Affine::scale(scale)); + let (c, whole) = (Coons::from_top_object(&split, None).unwrap(), Coons::from_top_object(&whole, None).unwrap()); + for (u, v) in [(1.0 / 6.0, 0.0), (1.0 / 3.0, 0.0), (0.45, 0.0), (0.5, 0.5), (2.0 / 3.0, 0.0), (0.9, 0.3)] { + let (p, q) = (c.eval(u, v), whole.eval(u, v)); + assert!(p.distance(q) < 0.02, "{cuts} pieces at {scale}x: ({u}, {v}) → {p:?}, unsplit {q:?}"); + } + } + } + } + + #[test] + fn a_top_object_keeps_smoothly_joined_curves_apart() { + // The top side's second piece leaves the split anchor in line with the first piece's + // handle, but its far handle is 1 pt off the split curve's: the pieces are two curves, and + // each takes the share of its control polygon. + let (a, b) = (UNEVEN_TOP.subsegment(0.0..0.3), UNEVEN_TOP.subsegment(0.3..1.0)); + let b = CubicBez::new(b.p0, b.p1, b.p2 + Vec2::new(0.0, 1.0), b.p3); + let c = Coons::from_top_object(&top_of_pieces(&[a, b]), None).unwrap(); let share = polygon(a) / (polygon(a) + polygon(b)); assert!(c.eval(share, 0.0).distance(a.p3) < 1e-9, "{:?}", c.eval(share, 0.0)); - assert!((share - 0.3).abs() > 0.01, "{share}"); + assert!((share - 0.3).abs() > 0.02, "{share}"); + } + + #[test] + fn a_top_object_side_partly_of_one_curve_keeps_the_polygon_shares() { + // The top side is a curve split at t = 0.3, then a straight segment: not all of it is one + // curve, so each piece keeps the share of its control polygon. + let curve = CubicBez::new((0.0, 0.0), (90.0, -45.0), (142.5, -22.5), (150.0, 0.0)); + let (a, b) = (curve.subsegment(0.0..0.3), curve.subsegment(0.3..1.0)); + let line = CubicBez::new((150.0, 0.0), (150.0 + 50.0 / 3.0, 0.0), (200.0 - 50.0 / 3.0, 0.0), (200.0, 0.0)); + let c = Coons::from_top_object(&top_of_pieces(&[a, b, line]), None).unwrap(); + let share = polygon(a) / (polygon(a) + polygon(b) + polygon(line)); + assert!(c.eval(share, 0.0).distance(a.p3) < 1e-9, "{:?}", c.eval(share, 0.0)); + // Joined into their curve, the two pieces would have put the anchor 0.3 of the way along + // their part of the side. + let joined = 0.3 * (polygon(a) + polygon(b)) / (polygon(a) + polygon(b) + polygon(line)); + assert!(c.eval(joined, 0.0).distance(a.p3) > 1.0, "{share} vs {joined}"); + } + + #[test] + fn a_top_object_side_of_many_arcs_stays_on_them() { + // A 120° arc of radius 500 drawn as `n` circular arcs, each close to a piece of one cubic + // while the whole arc is not one: the side stays on the circle, and the content's middle + // stays on the middle anchor, as the arcs' polygon shares put it. + let centre = Point::new(300.0, 600.0); + for n in [64u32, 128, 256] { + let step = 120f64.to_radians() / f64::from(n); + let reach = 500.0 * 4.0 / 3.0 * (step / 4.0).tan(); + let on = |a: f64| centre + Vec2::new(a.cos(), a.sin()) * 500.0; + let tangent = |a: f64| Vec2::new(-a.sin(), a.cos()) * reach; + let mut anchors: Vec = (0..=n) + .map(|i| { + let a = (-150f64).to_radians() + step * f64::from(i); + let p = on(a); + let h_in = if i == 0 { p } else { p - tangent(a) }; + let h_out = if i == n { p } else { p + tangent(a) }; + Anchor { p, h_in, h_out, ..Anchor::corner(p) } + }) + .collect(); + let (start, end) = (on((-150f64).to_radians()), on((-30f64).to_radians())); + anchors.extend([Anchor::corner(Point::new(end.x, 800.0)), Anchor::corner(Point::new(start.x, 800.0))]); + let path = PathData::single(SubPath::new(anchors, true)); + let c = Coons::from_top_object(&path, Some([0, n, n + 1, n + 2])).unwrap(); + let off = (0..=4000).map(|k| (c.eval(f64::from(k) / 4000.0, 0.0).distance(centre) - 500.0).abs()).fold(0.0, f64::max); + assert!(off < 0.001, "{n} arcs: the side lies {off} pt off the circle"); + let mid = c.eval(0.5, 0.0); + assert!(mid.distance(Point::new(300.0, 100.0)) < 0.001, "{n} arcs: the middle lands at {mid:?}"); + } } #[test] diff --git a/crates/doc/src/live/mesh.rs b/crates/doc/src/live/mesh.rs index d912479464..b6d5bbc88d 100644 --- a/crates/doc/src/live/mesh.rs +++ b/crates/doc/src/live/mesh.rs @@ -147,14 +147,18 @@ impl Coons { /// The patch of a top object's outline (the largest subpath of `path`), split into four sides /// at its corners. Each piece of a side between two anchors or corners takes a share of `u` or /// `v` in proportion to the length of its control polygon, spread along the piece by its own - /// curve parameter. A segment without handles counts as a cubic with its handles a third of - /// the way along, so the content spreads evenly along it. `corners` are the anchors (indices - /// into the outline, in its own order) at the top left, top right, bottom right and bottom - /// left, as a saved file gives them. They stay on those anchors when they run the way the - /// outline does or the opposite way, so a reflected outline keeps them; without them, or when - /// they don't fit the outline, each corner is found from the outline ([`top_object_corner`]). - /// A straight segment closes an open subpath, and segments of no length are left out. A top - /// object's envelope maps onto this patch. + /// curve parameter. A side whose pieces, from corner to corner, are all one cubic curve split at + /// anchors (each within 0.02 pt of that curve's piece) runs along that curve instead, by its + /// parameter: splitting the curve of such a side at more anchors, without changing its shape, + /// leaves how the side shares out the content as it was (corners found from the outline can + /// still move). A segment without handles counts as a cubic with its handles a third of the way + /// along, so the content spreads evenly along it. `corners` are the anchors (indices into the + /// outline, in its own order) at the top left, top right, bottom right and bottom left, as a + /// saved file gives them. They stay on those anchors when they run the way the outline does or + /// the opposite way, so a reflected outline keeps them; without them, or when they don't fit + /// the outline, each corner is found from the outline ([`top_object_corner`]). A straight + /// segment closes an open subpath, and segments of no length are left out. A top object's + /// envelope maps onto this patch. pub fn from_top_object(path: &PathData, corners: Option<[u32; 4]>) -> Option { let sp = path.subpaths.iter().filter(|s| s.anchors.len() >= 2).max_by(|a, b| a.area().abs().total_cmp(&b.area().abs()))?; let mut sp = sp.clone(); @@ -212,11 +216,12 @@ impl Coons { segs.get(i).map_or(Point::ZERO, |(c, _)| c.eval((s - i as f64).clamp(0.0, 1.0))) }; // The side from `a` to `b`: its points, and where along it (0 to 1) each lies. It runs - // through pieces of segments, split at `a` and `b`. Each piece takes its share of the side - // by the length of its control polygon and holds points at even steps of its parameter - // (at least 16, and at least `SIDE` points on the side), its ends included. A side of - // many pieces takes fewer points in each, so it holds at most `MAX_SIDE_POINTS` points, - // or one for each piece when it has more pieces than that. + // through pieces of segments, split at `a` and `b`; when all of them are one curve split + // at anchors ([`one_curve`]), it runs along that curve instead. Each piece takes its share + // of the side by the length of its control polygon and holds points at even steps of its + // parameter (at least 16, and at least `SIDE` points on the side), its ends included. A + // side of many pieces takes fewer points in each, so it holds at most `MAX_SIDE_POINTS` + // points, or one for each piece when it has more pieces than that. let side = |a: f64, b: f64| { let span = (b - a).rem_euclid(n); if !(span.is_finite() && span > 0.0) { @@ -232,8 +237,11 @@ impl Coons { } s = next; } - let polygon = |c: &CubicBez| c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3); - let mut weights: Vec = pieces.iter().map(polygon).collect(); + let pieces = match one_curve(&pieces) { + Some(one) => vec![one], + None => pieces, + }; + let mut weights: Vec = pieces.iter().map(control_polygon).collect(); let mut total: f64 = weights.iter().sum(); if !(total.is_finite() && total > 0.0) { weights.iter_mut().for_each(|w| *w = 1.0); @@ -336,6 +344,76 @@ impl Coons { /// anchors. const MAX_SIDE_POINTS: usize = 1 << 16; +/// How far, in points, each control point of each piece of a top object's side may lie from the +/// matching piece of one cubic curve for the side to run along that curve ([`one_curve`]); the side +/// then lies within this of the pieces it is drawn with. A curve split into thirds or tenths and +/// saved with its coordinates rounded to 0.001 pt stays within it, on outlines from 5 to 5,000 pt +/// wide; coarser rounding, or a piece of a much smaller share of the curve, can take it past this. +/// A smooth side that isn't one curve, such as an arc of a circle drawn in many pieces, lies +/// further off as a whole, even where each pair of its pieces would not. +const ONE_CURVE: f64 = 0.02; + +/// The length of `c`'s control polygon. +fn control_polygon(c: &CubicBez) -> f64 { + c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3) +} + +/// The cubic curve that `pieces`, two or more end to end, are all pieces of, split at the anchors +/// between them, when each control point of each piece lies within [`ONE_CURVE`] of the matching +/// piece of that curve; `None` otherwise. Split at parameter `t`, a curve's handles on either side +/// of the split lie in line, their lengths in proportion to the spans of its parameter the two +/// pieces take; split where the curve stops (a cusp), both handles lie on the anchor, and the +/// pieces' second derivatives there, in proportion to the squares of the spans, give the proportion +/// instead (whichever of the two pairs is the longer). Those proportions give each piece's span, and the curve follows from the first +/// piece's start and its handle, and the last piece's end and its handle, scaled up by their spans. +/// Every piece is then checked against that curve's piece over its span, so error can't build up +/// from one split to the next (the first piece's start and handle, and the last piece's end and +/// handle, match by construction). +fn one_curve(pieces: &[CubicBez]) -> Option { + let (first, last) = (pieces.first()?, pieces.last()?); + if pieces.len() < 2 { + return None; + } + let mut spans = Vec::with_capacity(pieces.len()); + spans.push(1.0); + for pair in pieces.windows(2) { + let [a, b] = pair else { return None }; + let (into, out) = (a.p3.distance(a.p2), b.p0.distance(b.p1)); + // How far each piece bends away from the anchor goes with the squares of the spans. Split + // where the curve stops (a cusp), both handles lie on the anchor and say nothing of the + // spans, and the bends say it; where the curve runs straight through the split, the bends + // are nothing and the handles say it. Whichever pair is the longer is the one to go by. + let bend_in = ((a.p3 - a.p2) - (a.p2 - a.p1)).hypot(); + let bend_out = ((b.p2 - b.p1) - (b.p1 - b.p0)).hypot(); + let ratio = if into.min(out) >= bend_in.min(bend_out) { out / into } else { (bend_out / bend_in).sqrt() }; + let next = spans.last().copied().unwrap_or(1.0) * ratio; + if !(next.is_finite() && next > 0.0) { + return None; + } + spans.push(next); + } + let total: f64 = spans.iter().sum(); + let (head, tail) = (spans.first().copied().unwrap_or(1.0) / total, spans.last().copied().unwrap_or(1.0) / total); + if !(total.is_finite() && head > 0.0 && tail > 0.0) { + return None; + } + let one = CubicBez::new(first.p0, first.p0 + (first.p1 - first.p0) / head, last.p3 + (last.p2 - last.p3) / tail, last.p3); + if ![one.p1, one.p2].iter().all(|p| p.is_finite()) { + return None; + } + let near = |p: Point, q: Point| p.distance(q) <= ONE_CURVE; + let mut from = 0.0; + for (k, (piece, span)) in pieces.iter().zip(&spans).enumerate() { + let to = if k + 1 == pieces.len() { 1.0 } else { (from + span / total).min(1.0) }; + let part = one.subsegment(from..to); + if !(near(part.p0, piece.p0) && near(part.p1, piece.p1) && near(part.p2, piece.p2) && near(part.p3, piece.p3)) { + return None; + } + from = to; + } + Some(one) +} + /// How far into the outline's bounding box, as a share of its width and of its height, a corner /// of a top object looks for an anchor. const CORNER_REACH: f64 = 0.475; diff --git a/crates/doc/src/selection.rs b/crates/doc/src/selection.rs index 6f0db556e0..4ef6446247 100644 --- a/crates/doc/src/selection.rs +++ b/crates/doc/src/selection.rs @@ -144,6 +144,25 @@ impl Selection { self.key = None; } } + /// [`Self::remove`] for each of `ids`, going through the selected objects once. + pub fn remove_all(&mut self, ids: impl IntoIterator) { + let ids: HashSet = ids.into_iter().collect(); + if ids.is_empty() { + return; + } + self.target = None; + self.slices.clear(); + self.symbol_part = None; + self.on_path_member = None; + self.objects.retain(|x| !ids.contains(x)); + for id in &ids { + self.anchors.remove(id); + self.segments.remove(id); + } + if self.key.is_some_and(|k| ids.contains(&k)) { + self.key = None; + } + } /// Select slices `ids` (see [`Selection::slices`]) and nothing else. pub fn set_slices(&mut self, ids: impl IntoIterator) { self.clear(); diff --git a/crates/doc/src/selection/tests.rs b/crates/doc/src/selection/tests.rs index d9df845129..b6090f8993 100644 --- a/crates/doc/src/selection/tests.rs +++ b/crates/doc/src/selection/tests.rs @@ -16,6 +16,35 @@ fn basic_ops() { assert!(s.is_empty()); } +#[test] +fn remove_all_does_what_removing_each_does() { + let mut s = Selection::default(); + for i in 1..=6 { + s.add(NodeId(i)); + } + for i in [2, 4, 5] { + s.anchors.insert(NodeId(i), BTreeSet::from([(0, 1)])); + s.segments.insert(NodeId(i), BTreeSet::from([(0, 0)])); + } + s.key = Some(NodeId(4)); + s.target = Some(NodeId(3)); + s.slices = vec![NodeId(9)]; + s.guides = vec![NodeId(10)]; + s.on_path_member = Some(NodeId(11)); + let mut one_by_one = s.clone(); + for id in [NodeId(4), NodeId(1), NodeId(4), NodeId(7)] { + one_by_one.remove(id); + } + let mut all = s.clone(); + all.remove_all([NodeId(4), NodeId(1), NodeId(4), NodeId(7)]); + assert_eq!(all, one_by_one); + assert_eq!(all.objects, [NodeId(2), NodeId(3), NodeId(5), NodeId(6)]); + // Removing nothing leaves the selection as it was. + let mut none = s.clone(); + none.remove_all([]); + assert_eq!(none, s); +} + #[test] fn guides_are_selected_on_their_own() { let mut s = Selection::default(); diff --git a/crates/doc/src/stored_art.rs b/crates/doc/src/stored_art.rs new file mode 100644 index 0000000000..e623e0ed0e --- /dev/null +++ b/crates/doc/src/stored_art.rs @@ -0,0 +1,376 @@ +//! Every object a document stores, wherever it is kept: in the layers, in opacity-mask art, and in +//! the art of symbols, graph designs and pattern swatches. [`Document::node`] finds objects in the +//! layer tree only; the lookups here find the others by their ids too, which +//! [`Document::fix_next_id`] keeps unique across all of them. + +use std::collections::HashSet; +use std::sync::Arc; + +use super::limits::MAX_NEXT_ID; +use super::{Document, Node, NodeId}; + +/// The art a stored object belongs to. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum StoredRoot { + /// Layer `index` of [`Document::layers`]. + Layer(usize), + /// Symbol `index` of [`Document::symbols`]. + Symbol(usize), + /// Graph design `index` of [`Document::graph_designs`]. + GraphDesign(usize), + /// Object `art` of pattern swatch `pattern` of [`Document::patterns`]. + Pattern { pattern: usize, art: usize }, +} + +/// Where a stored object is: its root and, inside opacity-mask art, the object that mask belongs +/// to (the innermost one when masks hold masks). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct StoredPlace { + pub root: StoredRoot, + pub mask_of: Option, +} + +impl StoredPlace { + /// Is the object in the layer tree itself, where [`Document::node`] finds it and the canvas + /// draws it as itself? + pub fn in_layers(self) -> bool { + matches!(self.root, StoredRoot::Layer(_)) && self.mask_of.is_none() + } +} + +/// One step down from a node: to its child at an index, or to its opacity-mask art. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Step { + Child(usize), + Mask, +} + +/// `n` and everything below it with its place, the opacity-mask art right after the object it +/// masks, then the children. +fn visit<'a>(n: &'a Arc, place: StoredPlace, f: &mut dyn FnMut(&'a Arc, StoredPlace)) { + f(n, place); + if let Some(m) = &n.extras().mask { + visit(&m.art, StoredPlace { mask_of: Some(n.id), ..place }, f); + } + for c in n.children().into_iter().flatten() { + visit(c, place, f); + } +} + +/// The steps from `n` to the first node in [`visit`] order with id `id`, and the object whose mask +/// holds it last on the way. +fn find(n: &Node, id: NodeId, steps: &mut Vec, mask_of: &mut Option) -> bool { + if n.id == id { + return true; + } + if let Some(m) = &n.extras().mask { + steps.push(Step::Mask); + let before = *mask_of; + *mask_of = Some(n.id); + if find(&m.art, id, steps, mask_of) { + return true; + } + *mask_of = before; + steps.pop(); + } + for (i, c) in n.children().into_iter().flatten().enumerate() { + steps.push(Step::Child(i)); + if find(c, id, steps, mask_of) { + return true; + } + steps.pop(); + } + false +} + +/// The node `steps` below `n`. +fn at<'a>(mut n: &'a Arc, steps: &[Step]) -> Option<&'a Arc> { + for s in steps { + n = match s { + Step::Mask => &n.extras().mask.as_ref()?.art, + Step::Child(i) => n.children()?.get(*i)?, + }; + } + Some(n) +} + +/// The node `steps` below `n` to change, the nodes on the way copied when shared. +fn at_mut<'a>(mut n: &'a mut Arc, steps: &[Step]) -> Option<&'a mut Node> { + for s in steps { + let node = Arc::make_mut(n); + n = match s { + Step::Mask => &mut node.extras_if_any()?.mask.as_mut()?.art, + Step::Child(i) => node.children_mut()?.get_mut(*i)?, + }; + } + Some(Arc::make_mut(n)) +} + +/// Gives every node from `n` down that `fresh` names a new id from `next`, counting nodes in +/// [`visit`] order from `*count`; only the nodes on the way to one are copied. Each part below is +/// renumbered through a second handle, so a new pointer marks a change. +fn renumber(n: &mut Arc, fresh: &HashSet, count: &mut usize, next: &mut u64) { + let own = fresh.contains(count); + *count += 1; + let mask = n.extras().mask.as_ref().and_then(|m| { + let mut art = Arc::clone(&m.art); + renumber(&mut art, fresh, count, next); + (!Arc::ptr_eq(&art, &m.art)).then_some(art) + }); + let mut slots = vec![]; + // Children's new ids by their old ones, for an Objects on Path group, which names its path and + // members by id. An id another child keeps still names that child. + let mut renamed = std::collections::HashMap::new(); + let mut kept = HashSet::new(); + for (i, c) in n.children().into_iter().flatten().enumerate() { + let mut new = Arc::clone(c); + renumber(&mut new, fresh, count, next); + if new.id == c.id { + kept.insert(c.id); + } else { + renamed.insert(c.id, new.id); + } + if !Arc::ptr_eq(&new, c) { + slots.push((i, new)); + } + } + renamed.retain(|old, _| !kept.contains(old)); + if !own && mask.is_none() && slots.is_empty() { + return; + } + let node = Arc::make_mut(n); + if own { + node.id = NodeId(*next); + *next += 1; + } + if let (Some(art), Some(m)) = (mask, node.extras_if_any().and_then(|e| e.mask.as_mut())) { + m.art = art; + } + if let Some(children) = node.children_mut() { + for (i, c) in slots { + if let Some(slot) = children.get_mut(i) { + *slot = c; + } + } + } + if !renamed.is_empty() + && let Some(on_path) = node.extras_if_any().and_then(|e| e.objects_on_path.as_mut()) + { + on_path.rename(&renamed); + } +} + +impl Document { + /// The roots of the art kept outside the layers, each with its [`StoredRoot`]. + fn definition_roots(&self) -> impl Iterator, StoredRoot)> { + let symbols = self.symbols.iter().enumerate().map(|(i, s)| (&s.art, StoredRoot::Symbol(i))); + let designs = self.graph_designs.iter().enumerate().map(|(i, g)| (&g.art, StoredRoot::GraphDesign(i))); + let patterns = self + .patterns + .iter() + .enumerate() + .flat_map(|(p, def)| def.art.iter().enumerate().map(move |(a, n)| (n, StoredRoot::Pattern { pattern: p, art: a }))); + symbols.chain(designs).chain(patterns) + } + + /// Every root of stored art: the layers, then the art of symbols, graph designs and patterns. + fn stored_roots(&self) -> impl Iterator, StoredRoot)> { + self.layers.iter().enumerate().map(|(i, l)| (l, StoredRoot::Layer(i))).chain(self.definition_roots()) + } + + /// The root `root` names, to change. + fn stored_root_mut(&mut self, root: StoredRoot) -> Option<&mut Arc> { + match root { + StoredRoot::Layer(i) => self.layers.get_mut(i), + StoredRoot::Symbol(i) => self.symbols.get_mut(i).map(|s| &mut s.art), + StoredRoot::GraphDesign(i) => self.graph_designs.get_mut(i).map(|g| &mut g.art), + StoredRoot::Pattern { pattern, art } => self.patterns.get_mut(pattern)?.art.get_mut(art), + } + } + + /// Visit every stored object with its place: the layer tree with the opacity-mask art of its + /// objects, then the art of symbols, graph designs and pattern swatches (their definitions, + /// once each, never the copies instances and tiles draw). + pub fn visit_stored<'a>(&'a self, mut f: impl FnMut(&'a Node, StoredPlace)) { + self.visit_stored_arcs(|n, place| f(n, place)); + } + + /// [`Self::visit_stored`] with each object's shared handle, which keeps its identity from one + /// look to the next while the object is unchanged (for caches such as thumbnails). + pub fn visit_stored_arcs<'a>(&'a self, mut f: impl FnMut(&'a Arc, StoredPlace)) { + for (root, r) in self.stored_roots() { + visit(root, StoredPlace { root: r, mask_of: None }, &mut f); + } + } + + /// Where object `id` is stored: the root, and the steps from it. + fn stored_path(&self, id: NodeId) -> Option<(StoredPlace, Vec)> { + if let Some(path) = self.index_path(id) { + let (first, rest) = path.split_first()?; + return Some((StoredPlace { root: StoredRoot::Layer(*first), mask_of: None }, rest.iter().map(|i| Step::Child(*i)).collect())); + } + // Not in the layer tree: in mask art (in the layers too) or in a definition's art. + for (root, r) in self.stored_roots() { + let (mut steps, mut mask_of) = (vec![], None); + if find(root, id, &mut steps, &mut mask_of) { + return Some((StoredPlace { root: r, mask_of }, steps)); + } + } + None + } + + /// Stored object `id` (see [`Self::visit_stored`]) with its place: one in the layer tree as + /// [`Self::node`] finds it, else the first in visiting order. + pub fn stored_node(&self, id: NodeId) -> Option<(&Arc, StoredPlace)> { + let (place, steps) = self.stored_path(id)?; + let root = self.stored_roots().find(|(_, r)| *r == place.root)?.0; + Some((at(root, &steps)?, place)) + } + + /// [`Self::stored_node`] to change; the nodes on the way are copied when shared. + pub fn stored_node_mut(&mut self, id: NodeId) -> Option<&mut Node> { + let (place, steps) = self.stored_path(id)?; + at_mut(self.stored_root_mut(place.root)?, &steps) + } + + /// Gives the objects outside the layer tree (in opacity-mask art and in the art of symbols, + /// graph designs and patterns) whose id is 0, past the id range, or already taken by an object + /// visited before them (the layer tree's own objects first) a new id, so every stored object + /// can be named by its id. Returns how many changed; the id counter then stands above them. + pub(crate) fn renumber_stored_duplicates(&mut self) -> usize { + let mut seen: HashSet = HashSet::new(); + for l in &self.layers { + l.walk(&mut |n| { + seen.insert(n.id); + }); + } + self.slices.iter().for_each(|s| { + seen.insert(s.id); + }); + // Per root, the visiting indices of the nodes that take a new id. + let mut fresh: Vec<(StoredRoot, HashSet)> = vec![]; + for (root, r) in self.stored_roots() { + let (mut i, mut here) = (0, HashSet::new()); + visit(root, StoredPlace { root: r, mask_of: None }, &mut |n, place| { + if !place.in_layers() && (n.id.0 == 0 || n.id.0 >= MAX_NEXT_ID || !seen.insert(n.id)) { + here.insert(i); + } + i += 1; + }); + if !here.is_empty() { + fresh.push((r, here)); + } + } + let total = fresh.iter().map(|(_, f)| f.len()).sum(); + if total == 0 { + return 0; + } + // No id left to give: the objects keep theirs rather than share one given out later. + if self.peek_next_id().saturating_add(total as u64) > MAX_NEXT_ID { + return 0; + } + let mut next = self.peek_next_id(); + for (r, f) in fresh { + if let Some(root) = self.stored_root_mut(r) { + renumber(root, &f, &mut 0, &mut next); + } + } + self.raise_next_id(next); + total + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{GraphDesign, OpacityMask, PatternDef, Symbol}; + use vectorcraft_geom::Rect; + + fn rect(id: u64) -> Node { + Node::path(NodeId(id), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), crate::Appearance::default_art()) + } + + fn masked(id: u64, art: Node) -> Node { + rect(id).with_mask(Some(Box::new(OpacityMask::new(art, true)))) + } + + /// A document with object 10 in its layer, mask art 11 on it, and one object in a symbol, + /// a graph design and a pattern (ids `defs`). + fn doc(defs: [u64; 3]) -> Document { + let mut d = Document::new(100.0, 100.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, masked(10, rect(11))).unwrap(); + d.symbols.push(Symbol { name: "S".into(), art: Arc::new(rect(defs[0])), dynamic: false }); + d.graph_designs.push(GraphDesign { name: "G".into(), art: Arc::new(rect(defs[1])) }); + d.patterns.push(PatternDef::new("P", vec![Arc::new(rect(defs[2]))])); + d.raise_next_id(20); + d + } + + #[test] + fn stored_objects_are_found_in_every_art() { + let d = doc([12, 13, 14]); + let place = |id: u64| d.stored_node(NodeId(id)).map(|(n, p)| (n.id.0, p)); + assert!(place(10).unwrap().1.in_layers()); + assert_eq!(place(11).unwrap().1, StoredPlace { root: StoredRoot::Layer(0), mask_of: Some(NodeId(10)) }); + assert_eq!(place(12).unwrap().1.root, StoredRoot::Symbol(0)); + assert_eq!(place(13).unwrap().1.root, StoredRoot::GraphDesign(0)); + assert_eq!(place(14).unwrap().1.root, StoredRoot::Pattern { pattern: 0, art: 0 }); + assert!(d.node(NodeId(11)).is_none() && d.node(NodeId(12)).is_none(), "the layer lookup stays the layer tree's"); + assert!(d.stored_node(NodeId(99)).is_none()); + let mut seen = vec![]; + d.visit_stored(|n, _| seen.push(n.id.0)); + assert_eq!(seen, [d.layers[0].id.0, 10, 11, 12, 13, 14]); + } + + #[test] + fn stored_objects_change_by_id() { + let mut d = doc([12, 13, 14]); + let before = d.clone(); + d.stored_node_mut(NodeId(13)).unwrap().name = Some("changed".into()); + assert_eq!(d.graph_designs[0].art.name.as_deref(), Some("changed")); + assert!(Arc::ptr_eq(&d.symbols[0].art, &before.symbols[0].art), "other art is not copied"); + assert_eq!(before.graph_designs[0].art.name, None, "the earlier document is unchanged"); + d.stored_node_mut(NodeId(11)).unwrap().name = Some("mask".into()); + assert_eq!(d.stored_node(NodeId(11)).unwrap().0.name.as_deref(), Some("mask")); + } + + #[test] + fn fix_next_id_gives_nested_duplicates_new_ids() { + // The symbol's object repeats the layer's object, the design's has no id, and the pattern's + // repeats the mask art's. + let mut d = doc([10, 0, 11]); + d.next_id = 1; + d.fix_next_id(); + let mut ids = vec![]; + d.visit_stored(|n, _| ids.push(n.id.0)); + let unique: HashSet = ids.iter().copied().collect(); + assert_eq!(unique.len(), ids.len(), "{ids:?}"); + assert!(!ids.contains(&0)); + assert_eq!(&ids[..3], &[d.layers[0].id.0, 10, 11], "the layer tree and the first mask art keep theirs"); + assert!(ids.iter().all(|id| *id < d.peek_next_id()), "{ids:?} {}", d.peek_next_id()); + // Ids already unique are kept, and a second pass changes nothing. + let again = d.clone(); + assert_eq!(d.renumber_stored_duplicates(), 0); + assert_eq!(d, again); + } + + #[test] + fn renumbered_objects_on_path_keep_their_path_and_members() { + // A symbol's Objects on Path group whose path repeats the layer's object 10 and whose + // member has no id. + let mut d = doc([12, 13, 14]); + let (path, member) = (rect(10), rect(0)); + let rec = crate::objects_on_path::ObjectsOnPath::new(path.id, &[&member], crate::objects_on_path::CENTER, 0.0); + let mut g = Node::new(NodeId(15), crate::NodeKind::Group { children: vec![Arc::new(path), Arc::new(member)], clip: false }); + g.extras_mut().objects_on_path = Some(Box::new(rec)); + d.symbols[0].art = Arc::new(g); + d.fix_next_id(); + let art = &d.symbols[0].art; + let kids: Vec = art.children().unwrap().iter().map(|c| c.id).collect(); + assert!(kids.iter().all(|id| id.0 != 10 && id.0 != 0), "{kids:?}"); + let on_path = art.extras().objects_on_path.as_ref().unwrap(); + assert_eq!(on_path.path, kids[0]); + assert_eq!(on_path.members.iter().map(|m| m.id).collect::>(), [kids[1]]); + } +} diff --git a/crates/doc/src/symbols.rs b/crates/doc/src/symbols.rs index 2cf260cbec..dde6621993 100644 --- a/crates/doc/src/symbols.rs +++ b/crates/doc/src/symbols.rs @@ -87,6 +87,8 @@ pub struct SymbolBoxes<'a> { sliced_placed: Cell, /// The most objects of symbol art [`Self::sliced_visual`] places: [`MAX_SYMBOL_NODES`]. sliced_most: u64, + /// The widths [`Self::measured_width`] has measured, by kind and symbol name. + widths: RefCell>>, } impl Document { @@ -107,6 +109,7 @@ impl Document { sliced: RefCell::default(), sliced_placed: Cell::new(0), sliced_most: MAX_SYMBOL_NODES, + widths: RefCell::default(), } } } @@ -247,6 +250,18 @@ impl<'a> SymbolBoxes<'a> { self.art(name)?.brush } + /// The width `measure` gives for the symbol named `name`, measured once for these boxes for each + /// `kind`, which names what `measure` measures. `measure` may call this again for other names. + pub fn measured_width(&self, kind: &'static str, name: &str, measure: impl FnOnce() -> Option) -> Option { + let key = (kind, name.to_string()); + if let Some(w) = self.widths.borrow().get(&key) { + return *w; + } + let w = measure(); + self.widths.borrow_mut().insert(key, w); + w + } + /// How far the visual box of an instance of the symbol named `name` grows in boxes made by /// [`Self::with_brush_art`]: `16 × max(w, 1) + 8` for the widest stroke `w` that /// [`Self::brush_width`] finds, as far as the renderer grows the cull bounds of a brushed path diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index 2b4953d151..b77f804de7 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -424,6 +424,8 @@ fn container_keeping_type(d: &Document, n: &Node) -> Option { if !kept { return None; } + // The members' own effects run first, as on the canvas. + crate::group::members_as_drawn(Some(d), &mut m); reshape_leaves(&mut m, &fx, &n.appearance.effects, Some(d)); m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects); m.appearance.effects.retain(|e| !is_pathfinder(&e.id)); diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index 959bd5e857..a6581fa449 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -209,6 +209,8 @@ fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option, nod Some(area) => Some(reshaped(&area, n, doc)), None => { let mut m = crate::reshape::outlined_members_with(None, doc, n, outline, nodes); + // The members' own effects run first, as on the canvas. + members_as_drawn(doc, &mut m); let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc); // The group's own fills and strokes follow the effects as its members do. if carry.moves(&m.appearance) { @@ -225,6 +227,7 @@ fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option, nod let art = h(n).filter(|art| nodes.charge(art))?; let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol); crate::reshape::outline_nested_text(doc, &mut art, false); + members_as_drawn(doc, &mut art); let carry = crate::reshape::reshape_leaves_carrying(&mut art, &fx, &n.appearance.effects, doc); // The art's own fills and strokes follow the effects as its members do. if carry.moves(&art.appearance) { @@ -754,7 +757,8 @@ fn take_sublayer_guides(n: &mut Node, out: &mut Vec>, hidden: bool, lo } /// `n`, a group or layer, as plain art: its Pathfinder effects evaluated, its geometry effects -/// reshaping all its members as one piece (the whole art's bounds as their reference box), and its +/// reshaping all its members as one piece (the whole art's bounds as their reference box) after +/// the members' own geometry and Pathfinder effects ([`members_as_drawn`]), and its /// own fills and strokes turned into art painting the members' geometry ([`member_shapes`]) below /// the members (after a clipping path) or above them, as its contents slot says. Its /// transparency, opacity mask and raster effects stay. `None` when it has none of these. Live @@ -790,6 +794,7 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { } if !fx.is_empty() { m = crate::reshape::outlined_members(doc, &m); + members_as_drawn(doc, &mut m); let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc); // The group's own fills and strokes paint the members as a whole: their gradients follow // the effects as the members' do. @@ -821,5 +826,83 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { Some(m) } +/// Replace each visible member of `n` with geometry or Pathfinder effects of its own, at every +/// depth of its groups and layers, by the art it draws ([`evaluate_container`], +/// [`crate::reshape::own_effects_art`]), so the geometry effects of `n` reshape what its members +/// draw. A clip group's clipping path stays as it is, and so do images, symbol instances and the +/// other objects that `own_effects_art` leaves alone, and a group or layer with a 3D effect with +/// everything in it. Calls nested in one another, through the +/// groups and layers it walks and the art it evaluates (symbol art and Pathfinder members +/// included), stop at [`vectorcraft_doc::depth::MAX_DEPTH`] deep, and together they replace at +/// most [`crate::SYMBOL_ART_MAX_NODES`] members: past either limit, members stay as they are. +pub(crate) fn members_as_drawn(doc: Option<&Document>, n: &mut Node) { + let Some(_frame) = DrawnFrame::enter() else { return }; + let clip = usize::from(n.clips()); + let Some(ch) = n.children_mut() else { return }; + for c in ch.iter_mut().skip(clip).filter(|c| c.visible) { + if !DrawnFrame::take_member() { + return; + } + // A group or layer with a 3D effect stays whole: the geometry effects listed after its 3D + // effect reshape its 3D art. + if is_container(c) && (crate::has_solid(c) || crate::has_revolve(c)) { + continue; + } + let art = if !is_container(c) { + crate::reshape::own_effects_art(doc, c) + } else if has_pathfinder(c) || !crate::reshape::geometry_effects(c).is_empty() { + evaluate_container(doc, c) + } else { + None + }; + match art { + Some(a) => *c = Arc::new(a), + None if is_container(c) => members_as_drawn(doc, Arc::make_mut(c)), + None => {} + } + } +} + +thread_local! { + /// How many [`members_as_drawn`] calls are running, one inside another, and how many members + /// they have visited since the outermost one started. + static DRAWN: std::cell::Cell<(usize, u64)> = const { std::cell::Cell::new((0, 0)) }; +} + +/// One running [`members_as_drawn`] call, counted in [`DRAWN`] until it is dropped. +struct DrawnFrame; + +impl DrawnFrame { + /// Count one more call; `None` when [`vectorcraft_doc::depth::MAX_DEPTH`] are running. The + /// outermost call starts the count of members again. + fn enter() -> Option { + let (frames, members) = DRAWN.with(|d| d.get()); + if frames >= vectorcraft_doc::depth::MAX_DEPTH { + return None; + } + DRAWN.with(|d| d.set((frames + 1, if frames == 0 { 0 } else { members }))); + Some(DrawnFrame) + } + + /// Count one more member visited; `false` once [`crate::SYMBOL_ART_MAX_NODES`] have been. + fn take_member() -> bool { + let (frames, members) = DRAWN.with(|d| d.get()); + if members >= crate::SYMBOL_ART_MAX_NODES { + return false; + } + DRAWN.with(|d| d.set((frames, members + 1))); + true + } +} + +impl Drop for DrawnFrame { + fn drop(&mut self) { + DRAWN.with(|d| { + let (frames, members) = d.get(); + d.set((frames.saturating_sub(1), members)); + }); + } +} + #[cfg(test)] mod tests; diff --git a/crates/effects/src/group/tests.rs b/crates/effects/src/group/tests.rs index c169c807b2..c6e2a78c73 100644 --- a/crates/effects/src/group/tests.rs +++ b/crates/effects/src/group/tests.rs @@ -555,6 +555,298 @@ fn a_nested_groups_own_gradient_follows_the_outer_groups_transform_and_free_dist assert!(near(s, Point::new(0.0, 5.0)) && near(e, Point::new(20.0, 5.0)), "{s:?} {e:?}"); } +/// The bounds of what `n` draws, as the renderer draws it: a group or layer with an appearance of +/// its own as the art [`evaluate_container`] makes of it, and each visible path and compound path +/// with the geometry effects still on it applied, then those of each visible fill and stroke that +/// has some. +fn drawn_bounds(n: &Node) -> Option { + if !n.visible { + return None; + } + if let Some(m) = evaluate_container(None, n) { + return drawn_bounds(&m); + } + if let Some(ch) = n.children() + && !matches!(n.kind, NodeKind::Compound { .. }) + { + return ch.iter().filter_map(|c| drawn_bounds(c)).reduce(|a, b| a.union(b)); + } + let (path, _) = crate::reshape::leaf_geometry(n)?; + let geometry = |fx: &[Effect]| -> Vec { fx.iter().filter(|e| e.visible && crate::is_geometry(&e.id)).cloned().collect() }; + let apply = |fx: &[Effect], p: &PathData| crate::apply_geometry(&geometry(fx), p, p.bounds().unwrap()); + let g = apply(&n.appearance.effects, &path); + let items: Vec<&AppearanceItem> = n.appearance.items.iter().filter(|i| paints(i) && !geometry(i.effects()).is_empty()).collect(); + if items.is_empty() { + return g.bounds(); + } + items.iter().filter_map(|i| apply(i.effects(), &g).bounds()).reduce(|a, b| a.union(b)) +} + +fn black() -> Appearance { + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0) +} + +/// A black 100 pt square from (100, 100). +fn square_at_100() -> Node { + Node::path(NodeId(1), shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)), black()) +} + +fn effect(id: &str, params: serde_json::Value) -> Effect { + Effect { id: id.into(), params, visible: true } +} + +fn offset_10() -> Effect { + effect("path.offsetPath", serde_json::json!({"offset": 10})) +} + +fn scaled(s: f64) -> Effect { + effect("distort.transform", serde_json::json!({"scaleH": s, "scaleV": s})) +} + +fn with_effect(mut n: Node, e: Effect) -> Node { + n.appearance.effects.push(e); + n +} + +/// The width that a group with `e` holding `member` draws at. +fn drawn_width(member: Node, e: Effect) -> f64 { + let g = with_effect(Node::group(NodeId(10), vec![Arc::new(member)]), e); + drawn_bounds(&g).unwrap().width() +} + +/// A member's own Offset Path runs before its group's Transform: the square offset by 10 pt to +/// 120 pt, then scaled by half, is 60 pt wide (70 pt the other way round). +#[test] +fn a_members_own_offset_runs_before_its_groups_scale() { + let w = drawn_width(with_effect(square_at_100(), offset_10()), scaled(50.0)); + assert!((w - 60.0).abs() < 1e-6, "{w}"); +} + +/// A member's own Transform runs before its group's Offset Path: the square scaled to 200 pt, then +/// offset by 10 pt, is 220 pt wide (240 pt the other way round). +#[test] +fn a_members_own_scale_runs_before_its_groups_offset() { + let w = drawn_width(with_effect(square_at_100(), scaled(200.0)), offset_10()); + assert!((w - 220.0).abs() < 1e-6, "{w}"); +} + +/// A member inside a plain group inside the group takes its own effects first too. +#[test] +fn a_member_of_a_plain_nested_group_takes_its_own_effects_first() { + let w = drawn_width(Node::group(NodeId(5), vec![Arc::new(with_effect(square_at_100(), offset_10()))]), scaled(50.0)); + assert!((w - 60.0).abs() < 1e-6, "{w}"); +} + +/// A nested group's own geometry effects run before the outer group's. +#[test] +fn a_nested_groups_own_effects_run_before_its_groups() { + let w = drawn_width(with_effect(Node::group(NodeId(5), vec![Arc::new(square_at_100())]), offset_10()), scaled(50.0)); + assert!((w - 60.0).abs() < 1e-6, "{w}"); +} + +/// A nested group's Pathfinder effect runs before the outer group's geometry effects: the back +/// square minus the front one is 50 pt wide, and offset by 10 pt it is 70 pt (offsetting the +/// squares first leaves 50 pt). +#[test] +fn a_nested_groups_pathfinder_runs_before_its_groups_effects() { + let back = square_at_100(); + let front = Node::path(NodeId(2), shapes::rectangle(Rect::new(150.0, 100.0, 250.0, 200.0)), black()); + let nested = with_effect(Node::group(NodeId(5), vec![Arc::new(back), Arc::new(front)]), effect("pathfinder.subtract", serde_json::json!({}))); + let w = drawn_width(nested, offset_10()); + assert!((w - 70.0).abs() < 1e-6, "{w}"); +} + +/// The geometry effects of a member's own fill run before its group's: 60 pt, as for the +/// member's own effect. +#[test] +fn a_members_fill_effects_run_before_its_groups() { + let mut member = square_at_100(); + member.appearance.items[0].effects_mut().push(offset_10()); + let w = drawn_width(member, scaled(50.0)); + assert!((w - 60.0).abs() < 1e-6, "{w}"); +} + +/// A member whose fills have geometry effects stays one element of a knockout group: its fills do +/// not knock each other out. +#[test] +fn a_member_drawn_as_its_fills_stays_one_knockout_element() { + let mut member = square_at_100(); + member.appearance.items.push(AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0))))); + member.appearance.items[0].effects_mut().push(offset_10()); + let mut g = with_effect(Node::group(NodeId(10), vec![Arc::new(member)]), scaled(50.0)); + g.knockout = vectorcraft_doc::Knockout::On; + let art = evaluate_container(None, &g).unwrap(); + let elements = Node::knockout_elements(art.children().unwrap()); + assert_eq!(elements.len(), 1, "{:?}", elements.iter().map(|e| (e.id, &e.kind)).collect::>()); +} + +/// The art a Pathfinder operation or compound shape takes from a group with geometry effects has +/// the members' own effects applied first, as the canvas draws it. +#[test] +fn shape_art_of_a_group_applies_its_members_effects_first() { + let g = with_effect(Node::group(NodeId(10), vec![Arc::new(with_effect(square_at_100(), offset_10()))]), scaled(50.0)); + let art = shape_art(None, &g, None).unwrap(); + let w = drawn_bounds(&art).unwrap().width(); + assert!((w - 60.0).abs() < 1e-6, "{w}"); + let leaves = member_leaves(None, &g, None); + let w = leaves.iter().filter_map(drawn_bounds).reduce(|a, b| a.union(b)).unwrap().width(); + assert!((w - 60.0).abs() < 1e-6, "leaves: {w}"); +} + +/// A symbol instance's own geometry effects run after those of its symbol's members, as the canvas +/// draws it and in the art a Pathfinder operation takes from it. +#[test] +fn a_symbol_instances_effects_run_after_its_symbols_members_own() { + let art = Node::group(NodeId(20), vec![Arc::new(with_effect(square_at_100(), offset_10()))]); + let instance = + with_effect(Node::new(NodeId(6), NodeKind::SymbolInstance { symbol: "s".into(), xf: vectorcraft_geom::Affine::IDENTITY }), scaled(50.0)); + let drawn = crate::reshape(None, &instance, Some(&art)).unwrap(); + let w = drawn_bounds(&drawn).unwrap().width(); + assert!((w - 60.0).abs() < 1e-6, "drawn: {w}"); + let hook = move |_: &Node| Some(art.clone()); + let w = drawn_bounds(&shape_art(None, &instance, Some(&hook)).unwrap()).unwrap().width(); + assert!((w - 60.0).abs() < 1e-6, "shape art: {w}"); +} + +/// Export bakes the group as the canvas draws it. +#[test] +fn a_baked_group_applies_its_members_effects_first() { + let mut d = Document::new(800.0, 800.0); + let layer = d.layers[0].id; + let g = with_effect(Node::group(NodeId(10), vec![Arc::new(with_effect(square_at_100(), offset_10()))]), scaled(50.0)); + d.insert(Some(layer), 0, g).unwrap(); + let baked = crate::bake_document(&d).unwrap(); + let w = baked.node(NodeId(10)).unwrap().geometric_bounds().unwrap().width(); + assert!((w - 60.0).abs() < 1e-6, "{w}"); +} + +/// A group whose Transform effect only moves and copies keeps its type when baked; a nested +/// group's own Transform still runs before the copies: the nested square scaled by half to 50 pt +/// and copied 200 pt to the right spans 250 pt (copying first, then scaling both copies about +/// their middle, spans 150 pt). +#[test] +fn a_baked_group_that_keeps_its_type_applies_its_members_effects_first() { + if skip_without_craft_fonts() { + return; + } + let style = CharStyle { size: 24.0, fill: Paint::solid(Color::BLACK), ..Default::default() }; + let text = Node::new(NodeId(3), NodeKind::Text(Box::new(TextObject::point(Point::new(20.0, 60.0), "Type", style)))); + let nested = with_effect(Node::group(NodeId(5), vec![Arc::new(square_at_100())]), scaled(50.0)); + let g = with_effect( + Node::group(NodeId(10), vec![Arc::new(text), Arc::new(nested)]), + effect("distort.transform", serde_json::json!({"moveH": 200, "copies": 1})), + ); + let mut d = Document::new(800.0, 800.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, g).unwrap(); + let baked = crate::bake_document(&d).unwrap(); + let mut text = 0; + baked.walk(|n| text += usize::from(matches!(n.kind, NodeKind::Text(_)))); + assert_eq!(text, 2, "the type stays type, copied"); + let w = baked.node(NodeId(5)).unwrap().geometric_bounds().unwrap().width(); + assert!((w - 250.0).abs() < 1e-6, "{w}"); +} + +/// A clip group's clipping path keeps its own effects; the clipped members take theirs first. +#[test] +fn a_clipping_path_keeps_its_own_effects_under_a_groups_effects() { + let mut clip = with_effect(square_at_100(), offset_10()); + clip.id = NodeId(2); + if let NodeKind::Path { clipping, .. } = &mut clip.kind { + *clipping = true; + } + let clipped = + Node::new(NodeId(5), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(with_effect(square_at_100(), offset_10()))], clip: true }); + let g = with_effect(Node::group(NodeId(10), vec![Arc::new(clipped)]), scaled(50.0)); + let art = evaluate_container(None, &g).unwrap(); + let clip_group = art.children().unwrap()[0].clone(); + let ch = clip_group.children().unwrap(); + assert!(matches!(ch[0].kind, NodeKind::Path { clipping: true, .. }), "{:?}", ch[0].kind); + assert_eq!(crate::reshape::geometry_effects(&ch[0]).len(), 1, "the clipping path keeps its Offset Path"); + assert!(matches!(ch[1].kind, NodeKind::Group { .. }) && crate::reshape::geometry_effects(&ch[1]).is_empty(), "the member is drawn as its art"); +} + +/// A member with a linked opacity mask keeps its own effects on it, so its mask moves with it +/// under the group's Transform; so does a member with a 3D effect, whose later geometry effects +/// apply to its 3D art. +#[test] +fn members_with_linked_masks_or_3d_effects_keep_their_own_effects() { + let mut masked = with_effect(square_at_100(), offset_10()); + masked.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new( + Node::path(NodeId(2), shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)), black()), + true, + ))); + let mut solid = with_effect(square_at_100(), effect(crate::solids::EXTRUDE, serde_json::json!({}))); + solid.id = NodeId(3); + solid.appearance.effects.push(scaled(50.0)); + let moved = effect("distort.transform", serde_json::json!({"moveH": 50, "strokes": true})); + let g = with_effect(Node::group(NodeId(10), vec![Arc::new(masked), Arc::new(solid)]), moved); + let art = evaluate_container(None, &g).unwrap(); + let ch = art.children().unwrap(); + assert!(matches!(ch[0].kind, NodeKind::Path { .. }) && crate::reshape::geometry_effects(&ch[0]).len() == 1, "{:?}", ch[0].kind); + let mask = ch[0].extras().mask.as_deref().unwrap().art.geometric_bounds().unwrap(); + assert!((mask.x0 - 150.0).abs() < 1e-6, "the mask moves with the square: {mask:?}"); + assert!(matches!(ch[1].kind, NodeKind::Path { .. }) && ch[1].appearance.effects.len() == 2, "{:?}", ch[1].kind); +} + +/// A nested group with a 3D effect stays as it is, with its members: the Transform listed after +/// its Extrude still applies to its 3D art. +#[test] +fn a_nested_group_with_a_3d_effect_keeps_its_own_effects() { + let inner = with_effect(square_at_100(), offset_10()); + let mut solid = with_effect(Node::group(NodeId(5), vec![Arc::new(inner)]), effect(crate::solids::EXTRUDE, serde_json::json!({}))); + solid.appearance.effects.push(scaled(50.0)); + let moved = effect("distort.transform", serde_json::json!({"moveH": 50})); + let g = with_effect(Node::group(NodeId(10), vec![Arc::new(solid)]), moved); + let art = evaluate_container(None, &g).unwrap(); + let ch = art.children().unwrap(); + assert!( + matches!(ch[0].kind, NodeKind::Group { .. }) && ch[0].id == NodeId(5) && ch[0].appearance.effects.len() == 2, + "{:?}", + ch[0].appearance.effects + ); + let member = &ch[0].children().unwrap()[0]; + assert!(matches!(member.kind, NodeKind::Path { .. }) && crate::reshape::geometry_effects(member).len() == 1, "{:?}", member.kind); +} + +/// Members nested deeper than the depth limit keep their own effects as they are. +#[test] +fn members_past_the_depth_limit_stay_as_they_are() { + let mut n = with_effect(square_at_100(), offset_10()); + for i in 0..vectorcraft_doc::depth::MAX_DEPTH { + n = Node::group(NodeId(100 + i as u64), vec![Arc::new(n)]); + } + let g = with_effect(Node::group(NodeId(10), vec![Arc::new(n)]), scaled(50.0)); + let art = evaluate_container(None, &g).unwrap(); + let mut deepest = None; + art.walk(&mut |c: &Node| { + if c.id == NodeId(1) { + deepest = Some(c.clone()); + } + }); + let deepest = deepest.unwrap(); + assert!(matches!(deepest.kind, NodeKind::Path { .. }), "{:?}", deepest.kind); + assert_eq!(crate::reshape::geometry_effects(&deepest).len(), 1); +} + +/// The depth limit counts nested groups with effects of their own too. +#[test] +fn nested_groups_with_effects_count_toward_the_depth_limit() { + let mut n = with_effect(square_at_100(), offset_10()); + for i in 0..vectorcraft_doc::depth::MAX_DEPTH { + n = with_effect(Node::group(NodeId(100 + i as u64), vec![Arc::new(n)]), effect("distort.transform", serde_json::json!({"moveH": 1}))); + } + let g = with_effect(Node::group(NodeId(10), vec![Arc::new(n)]), scaled(50.0)); + let art = evaluate_container(None, &g).unwrap(); + let mut deepest = None; + art.walk(&mut |c: &Node| { + if c.id == NodeId(1) && matches!(c.kind, NodeKind::Path { .. }) { + deepest = Some(c.clone()); + } + }); + assert!(deepest.is_some_and(|d| crate::reshape::geometry_effects(&d).len() == 1), "the deepest member keeps its effect"); +} + /// An image or a symbol instance that a group's Transform effect moves takes the placed gradients /// of its own fills along, as a path does, and each copy takes them as many times as it takes the /// transform. diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 2bda0aa88f..c5aaed7309 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -524,9 +524,10 @@ fn with_id(art: &Node, id: NodeId) -> Node { /// `n` as plain art that geometry effects can reshape, without its transparency and object /// effects: type outlined ([`outline_text`]), live objects evaluated (type inside them outlined), /// a symbol instance as `symbol_art` (the symbol's art, stained as the caller draws it) placed by -/// the instance's transform (through the symbol's 9-slice guides in `doc`, when it has them), its -/// fills and strokes carrying the geometry effects of the instance's active fill and stroke -/// ([`add_instance_row_effects`]). +/// the instance's transform (through the symbol's 9-slice guides in `doc`, when it has them), as +/// the art its members draw when the instance has geometry effects of its own +/// ([`crate::group::members_as_drawn`]), its fills and strokes carrying the geometry effects of the +/// instance's active fill and stroke ([`add_instance_row_effects`]). /// `None` for other kinds (images, paths, containers), and for an instance whose art placed /// through the guides could hold more than [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects. A Repeat counts the Repeats in the art of /// `doc`'s symbols that its instances show toward its instance budget. @@ -562,20 +563,16 @@ fn outline_art_with( Node::group(n.id, vec![Arc::new(a)]) } // The object as the one piece the copies of its Transform effect are made from. - _ if has_transform_art(n) || (apart && has_transform_copies(n)) => { - let mut one = n.clone(); - one.opacity = 1.0; - one.blend = Default::default(); - one.isolate = false; - one.extras_mut().mask = None; - one.appearance.effects.clear(); - Node::group(n.id, vec![Arc::new(one)]) - } + _ if has_transform_art(n) || (apart && has_transform_copies(n)) => one_piece(n), _ if vectorcraft_doc::live::is_live(n) => evaluated_with(symbols, n, outline, nodes), _ => return None, }; outline_nested_text(paint_doc, &mut art, false); if matches!(n.kind, NodeKind::SymbolInstance { .. }) { + // The instance's own geometry effects reshape what the symbol's members draw. + if !geometry_effects(n).is_empty() { + crate::group::members_as_drawn(paint_doc, &mut art); + } add_instance_row_effects(symbols, n, &mut art); } art.opacity = 1.0; @@ -843,18 +840,64 @@ fn as_art_opts( } // The art is a group with `n`'s id (for an image without fills or strokes that paint, a clip // group). - let mut out = art; - out.name = n.name.clone(); - out.visible = n.visible; - out.opacity = n.opacity; - out.blend = n.blend; - out.isolate = n.isolate; + Some(dressed(art, n)) +} + +/// `art`, the art made of `n`, with `n`'s name, visibility, transparency, opacity mask and +/// remaining (raster) effects. +fn dressed(mut art: Node, n: &Node) -> Node { + art.name = n.name.clone(); + art.visible = n.visible; + art.opacity = n.opacity; + art.blend = n.blend; + art.isolate = n.isolate; // One element: its pieces never knock each other out. - out.knockout = vectorcraft_doc::Knockout::Off; - out.knockout_shape = n.knockout_shape; - out.extras_mut().mask = n.extras().mask.clone(); - out.appearance.effects = crate::raster::without_geometry(&n.appearance.effects); - Some(out) + art.knockout = vectorcraft_doc::Knockout::Off; + art.knockout_shape = n.knockout_shape; + art.extras_mut().mask = n.extras().mask.clone(); + art.appearance.effects = crate::raster::without_geometry(&n.appearance.effects); + art +} + +/// A group with `n`'s id holding `n` without its transparency, opacity mask and effects: the one +/// piece that `n`'s own geometry effects reshape. +fn one_piece(n: &Node) -> Node { + let mut one = n.clone(); + one.opacity = 1.0; + one.blend = Default::default(); + one.isolate = false; + one.extras_mut().mask = None; + one.appearance.effects.clear(); + Node::group(n.id, vec![Arc::new(one)]) +} + +/// Path or compound path `n` with its own geometry effects applied, as the art it draws: with +/// geometry effects in a visible fill or stroke of its own, a group of one path for each fill and +/// stroke, its effects and that fill's or stroke's applied ([`crate::bake_type_appearance`]); +/// otherwise a group with `n`'s id holding the path reshaped by its effects ([`reshape_leaves`]). +/// The art keeps `n`'s id, name, visibility, transparency, opacity mask and raster effects. `None` +/// for a guide, for other kinds of objects, for a path with a linked opacity mask or a 3D effect, +/// and when `n` has no visible geometry effect of its own or in a visible fill or stroke. +pub(crate) fn own_effects_art(doc: Option<&Document>, n: &Node) -> Option { + if !matches!(n.kind, NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. }) + || n.extras().mask.as_ref().is_some_and(|m| m.linked) + || crate::has_solid(n) + || crate::has_revolve(n) + { + return None; + } + if n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects())) { + // One element: its pieces never knock each other out. + return crate::bake_type_appearance(doc, n).map(|art| Node { knockout: vectorcraft_doc::Knockout::Off, ..art }); + } + let fx = geometry_effects(n); + if fx.is_empty() { + return None; + } + let mut art = one_piece(n); + reshape_leaves(&mut art, &fx, &n.appearance.effects, doc); + transform_items(&mut art, doc); + Some(dressed(art, n)) } /// Map every path under `art` (and its gradients), and every path in the art of the linked opacity diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index e9d64864d0..1677937f17 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -27,7 +27,7 @@ pub fn is_revolve(id: &str) -> bool { /// Most bytes the copies of the object's paint in the faces may take together. Each face and the /// seam stroke around it gets a copy of the paint, so a gradient of many stops times tens of /// thousands of faces took gigabytes; past this the source path is drawn. -const MAX_PAINT_COPIES: usize = 256 << 20; +pub(crate) const MAX_PAINT_COPIES: usize = 256 << 20; /// The most face and box tests a group's transparent members' faces take together to rejoin their /// members' last runs; past them each starts a run of its own. diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 52739983a5..aeec471bcd 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -5,8 +5,9 @@ use std::sync::Arc; 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, MAX_OBJECT_FACES, Mesh, PlanarFace, View}; +use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect, Vec2}; +use vectorcraft_pathops::BoolOp; +use vectorcraft_three_d::{Bevel, BevelShape, DepthPlane, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, PlanarFace, View}; #[cfg(test)] use vectorcraft_doc::color::Color; @@ -678,7 +679,8 @@ fn built_solids<'a>( /// 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 -/// strokes that covers the fill's whole edge. +/// strokes that covers the fill's whole edge. A face that [`convex_face`] takes also keeps its +/// polygon and plane, for [`local_order`]; every other face has an empty `outline` and no `plane`. struct Placed { depth: f64, side: bool, @@ -686,6 +688,8 @@ struct Placed { bounds: Rect, member: usize, paints: Paints, + outline: Vec, + plane: Option, } /// The part of its shape a face's solid is built from ([`Placed`]). @@ -694,13 +698,22 @@ enum Paints { Fill, /// A stroke whose solid holds the fill's whole edge and hides it: one with a width, without /// dashes, a width profile or a brush, painted with a solid color or a gradient without - /// transparent stops, on a shape whose subpaths are all closed. + /// transparent stops, on a shape whose subpaths are all closed, extruded (an inflated fill can + /// rise in front of its stroke). Stroke, Other, } +/// Can a stroke's solid on a shape with outline `path` hold the fill's edge ([`Paints::Stroke`]) +/// under the effect `effect`? Only when the subpaths are all closed and the effect extrudes: an +/// inflated fill can rise in front of its stroke. +fn holds_edge(effect: &str, path: &PathData) -> bool { + effect != INFLATE && path.subpaths.iter().all(|p| p.closed) +} + impl Paints { - /// What `item` of a shape is, the shape's subpaths all closed when `closed`. + /// What `item` of a shape is, its stroke's solid able to hold the fill's edge when `closed` + /// ([`holds_edge`]). fn of(item: &AppearanceItem, closed: bool) -> Self { match item { AppearanceItem::Fill(_) => Paints::Fill, @@ -729,10 +742,446 @@ impl Placed { fn of(f: &Facet, member: usize, paints: Paints) -> Self { let mut points = f.contours.iter().flatten(); let bounds = points.next().map_or(Rect::ZERO, |p| points.fold(Rect::from_points(*p, *p), |r, q| r.union_pt(*q))); - Placed { depth: f.depth, side: f.side, away: f.away, bounds, member, paints } + let local = convex_face(f).is_some(); + let outline = f.contours.first().filter(|_| local).cloned().unwrap_or_default(); + let plane = f.plane.filter(|_| local); + Placed { depth: f.depth, side: f.side, away: f.away, bounds, member, paints, outline, plane } } } +/// The most pairs of faces [`local_order`] compares, and the most [`cut_stroke_faces`] compares; +/// the pairs they have not reached by then keep the order of their depths. +const MAX_LOCAL_CHECKS: usize = 4_000_000; + +/// The polygon of `f` and the sign of its turns, when `f` is a face turned toward the viewer other +/// than a planar end, with a plane and one convex contour: a face [`local_order`] and +/// [`cut_stroke_faces`] work on. +fn convex_face(f: &Facet) -> Option<(&[Point], f64)> { + if f.away || f.end.is_some() || f.plane.is_none() || f.contours.len() != 1 { + return None; + } + let c = f.contours.first()?; + Some((c, convex(c)?)) +} + +/// The bounds of polygon `p` (`Rect::ZERO` when it has no points). +fn polygon_bounds(p: &[Point]) -> Rect { + let mut points = p.iter(); + points.next().map_or(Rect::ZERO, |q| points.fold(Rect::from_points(*q, *q), |r, q| r.union_pt(*q))) +} + +/// Do rectangles `a` and `b` overlap (more than along an edge)? +fn rects_overlap(a: Rect, b: Rect) -> bool { + a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1 +} + +/// How many faces [`cut_stroke_faces`] may add to solids painted by `items` that hold `faces` faces +/// and whose paint copies take `paint_bytes` so far: as many as keep the faces within +/// [`MAX_OBJECT_FACES`] and the copies within the allowance, each added face counted as six copies +/// of the costliest stroke's paint. +fn cut_room<'a>(items: impl Iterator, faces: usize, paint_bytes: usize) -> usize { + let per_face = items + .filter(|item| matches!(item, AppearanceItem::Stroke(_))) + .map(|item| { + let mut copies = 0usize; + crate::revolve::paint_copies_add(&mut copies, 6, paint_ref(item)); + copies + }) + .max() + .unwrap_or(0) + .max(1); + let affordable = crate::revolve::MAX_PAINT_COPIES.saturating_sub(paint_bytes) / per_face; + MAX_OBJECT_FACES.saturating_sub(faces).min(affordable) +} + +/// In `solids`, each solid's part ([`Paints`]), its shape's index and its faces, cut each face of a +/// stroke that does not cover the fill's edge ([`Paints::Other`]) that passes through the plane of a +/// face of the same shape's fill, or of a face of another of the shape's strokes, where the two +/// overlap on the drawing ([`cut_through`]). Of two such strokes, the later one's faces are cut +/// against the earlier one's; a covering stroke's faces ([`Paints::Stroke`]) are never cut, and an +/// other stroke's faces are cut against them. At most `room` pieces are added, the object's solids +/// together. +fn cut_stroke_faces(solids: &mut [(Paints, usize, &mut Vec)], mut room: usize) { + let mut checks = 0usize; + for k in 0..solids.len() { + let Some((Paints::Other, shape)) = solids.get(k).map(|(p, s, _)| (*p, *s)) else { continue }; + let walls: Vec = (0..solids.len()) + .filter(|&j| { + solids.get(j).is_some_and(|(p, s, _)| { + *s == shape + && match p { + Paints::Fill | Paints::Stroke => true, + Paints::Other => j < k, + } + }) + }) + .collect(); + for j in walls { + let (wall, stroke) = if j < k { + let (before, from) = solids.split_at_mut(k); + (&**before[j].2, &mut *from[0].2) + } else { + let (before, from) = solids.split_at_mut(j); + (&**from[0].2, &mut *before[k].2) + }; + cut_through(wall, stroke, &mut room, &mut checks); + } + } +} + +/// Cut each face of `stroke` that passes through the plane of a face of `solid` (the fill's or +/// another stroke's) where their polygons overlap on the drawing, along the line where their depths +/// meet, so that each piece is wholly in front of or behind that face there ([`local_order`] can +/// then order them). A dash's end, which crosses the edge of the fill it is drawn on, is cut into its +/// part outside the fill, in front of the fill's wall, and its part inside, behind it. A piece keeps +/// the part of the face's curved outline on its side of the cut. The first piece of a face takes its +/// place, the others go at the end. Each cut adds a face out of `room`, and each pair compared counts +/// in `checks` ([`MAX_LOCAL_CHECKS`]); cutting stops when either runs out. +fn cut_through(solid: &[Facet], stroke: &mut Vec, room: &mut usize, checks: &mut usize) { + // The faces from left to right: a face is compared with those that start left of its end. + let mut walls: Vec<(&Facet, &[Point], f64, Rect)> = + solid.iter().filter_map(|f| convex_face(f).map(|(c, turn)| (f, c, turn, polygon_bounds(c)))).collect(); + if walls.is_empty() { + return; + } + walls.sort_by(|a, b| a.3.x0.total_cmp(&b.3.x0)); + let mut k = 0; + while k < stroke.len() { + let mut extent = stroke.get(k).and_then(convex_face).map(|(c, _)| polygon_bounds(c)); + for &(wall, outline, turn, bounds) in &walls { + let Some(at) = extent.filter(|e| bounds.x0 < e.x1) else { break }; + if *checks >= MAX_LOCAL_CHECKS || *room == 0 { + return; + } + *checks += 1; + if !rects_overlap(at, bounds) { + continue; + } + let Some(s) = stroke.get(k) else { break }; + let Some((c, _)) = convex_face(s) else { break }; + if let Some((near, far)) = cut(s, c, wall, outline, turn) { + *room -= 1; + extent = convex_face(&near).map(|(c, _)| polygon_bounds(c)); + stroke[k] = near; + stroke.push(far); + } + } + k += 1; + } +} + +/// Face `s` (polygon `c`) cut where its depth meets that of face `wall` (convex polygon `outline`, +/// turning with sign `turn`): its piece nearer the viewer than the wall's plane and its piece +/// farther. `None` when the two do not overlap on the drawing or `s` is on one side of the wall's +/// plane wherever they do. +fn cut(s: &Facet, c: &[Point], wall: &Facet, outline: &[Point], turn: f64) -> Option<(Facet, Facet)> { + let ahead = |p: Point| Some(s.depth_at(p)? - wall.depth_at(p)?); + let overlap = clip_convex(c, outline, turn); + centroid(&overlap)?; + let tolerance = 1e-6; + let (mut nearer, mut farther) = (false, false); + for p in &overlap { + let d = ahead(*p)?; + nearer |= d > tolerance; + farther |= d < -tolerance; + } + if !(nearer && farther) { + return None; + } + let (a, b) = (s.plane?, wall.plane?); + let values: Vec = match (a.eye, b.eye) { + (Some(e), Some(f)) if e == f && a.center == b.center => { + // With perspective the depths themselves are not linear on the drawing, but where they + // meet is a line: (dA - aA e)(nzB - aB) = (dB - aB e)(nzA - aA), with aX = (nX · p) / e, + // whose difference is linear. Its sign is that of the depths' difference over the + // product of the two denominators, taken at the middle of the face. + let at = |p: Point| { + let (x, y) = (p.x - a.center.x, p.y - a.center.y); + let (aa, ab) = ((a.normal[0] * x + a.normal[1] * y) / e, (b.normal[0] * x + b.normal[1] * y) / e); + let (da, db) = (a.normal[2] - aa, b.normal[2] - ab); + ((a.offset - aa * e) * db - (b.offset - ab * e) * da, da * db) + }; + let sign = at(centroid(c)?).1.signum(); + c.iter().map(|p| at(*p).0 * sign).collect() + } + _ => c.iter().map(|p| ahead(*p)).collect::>()?, + }; + let piece = |sign: f64| { + let points = half(c, &values, sign); + let mid = centroid(&points)?; + let mut f = s.clone(); + f.depth = s.depth_at(mid).unwrap_or(s.depth); + f.contours = vec![points]; + f.outline = s.outline.as_ref().and_then(|o| clip_to_side(o, c, &values, sign)); + Some(f) + }; + Some((piece(1.0)?, piece(-1.0)?)) +} + +/// Curved outline `outline` of a face with polygon `c`, cut along the line where `values` (one per +/// point of `c`, varying linearly along each edge) is 0, keeping the side where `sign` times them is +/// at least 0. `None` when the line does not cross `c` at two points or nothing is left. +fn clip_to_side(outline: &PathData, c: &[Point], values: &[f64], sign: f64) -> Option { + let mut crossings = vec![]; + for (j, (&a, &va)) in c.iter().zip(values).enumerate() { + let k = (j + 1) % c.len(); + let (Some(&b), Some(&vb)) = (c.get(k), values.get(k)) else { continue }; + if (va >= 0.0) != (vb >= 0.0) { + crossings.push(a.lerp(b, va / (va - vb))); + } + } + let &[q0, q1] = crossings.as_slice() else { return None }; + let along = q1 - q0; + let length = along.hypot(); + if length.is_nan() || length <= 1e-9 { + return None; + } + let along = along / length; + let (inside, _) = c.iter().zip(values).find(|(_, v)| **v * sign > 0.0)?; + let mut across = Vec2::new(-along.y, along.x); + if (*inside - q0).dot(across) < 0.0 { + across = -across; + } + let bounds = outline.bounds()?.union(polygon_bounds(c)); + let reach = 2.0 * (bounds.width() + bounds.height() + (q0 - bounds.center()).hypot()) + 1.0; + let mut side = BezPath::new(); + side.move_to(q0 - along * reach); + side.line_to(q0 + along * reach); + side.line_to(q0 + along * reach + across * reach); + side.line_to(q0 - along * reach + across * reach); + side.close_path(); + let kept = vectorcraft_pathops::boolean(outline, FillRule::NonZero, &PathData::from_bezpath(&side), FillRule::NonZero, BoolOp::Intersect); + kept.bounds().is_some().then_some(kept) +} + +/// The part of polygon `p` where `sign` times `values` (one per point, varying linearly along each +/// edge) is at least 0. +fn half(p: &[Point], values: &[f64], sign: f64) -> Vec { + let mut out = vec![]; + for (j, (&a, &va)) in p.iter().zip(values).enumerate() { + let k = (j + 1) % p.len(); + let (Some(&b), Some(&vb)) = (p.get(k), values.get(k)) else { continue }; + let (sa, sb) = (va * sign, vb * sign); + if sa >= 0.0 { + out.push(a); + } + if (sa >= 0.0) != (sb >= 0.0) { + out.push(a.lerp(b, sa / (sa - sb))); + } + } + out +} + +/// `order` (back to front), when it draws a face of one of a shape's strokes and an overlapping face +/// of the same shape's fill or strokes the wrong way round for their depths where they overlap on +/// the drawing, with every pair of overlapping faces that keep a polygon and a plane +/// ([`convex_face`]: turned toward the viewer, not a planar end), of any shape, put in the order of +/// their depths where they overlap: the face nearer the viewer there goes after the other. A fill +/// wall and a face of the same shape's covering stroke ([`Paints::Stroke`]) keep their order. Each +/// face otherwise keeps its place in `order`, so a fill wall in the gap between two dashes stays +/// where its depth puts it. A cycle of such pairs is broken at the face that comes first in `order`. +/// A face drawn last (a planar end turned toward the viewer, at depth `f64::MAX`) keeps its place: +/// no face moves across it. Otherwise `order` as it is. +fn local_order(faces: &[Placed], order: Vec) -> Vec { + use std::cmp::Reverse; + // The faces of each shape that take part, from left to right for a sweep along x. + let mut shapes: Vec> = vec![]; + for (k, f) in faces.iter().enumerate() { + if f.outline.len() < 3 || f.plane.is_none() { + continue; + } + if shapes.len() <= f.member { + shapes.resize_with(f.member + 1, Vec::new); + } + shapes[f.member].push(k); + } + if !shapes.iter().any(|list| list.iter().any(|&k| faces[k].paints != Paints::Fill)) { + return order; + } + for list in &mut shapes { + list.sort_by(|&a, &b| faces[a].bounds.x0.total_cmp(&faces[b].bounds.x0)); + } + // A fill wall and a face of the same shape's covering stroke keep the order [`draw_order`] gave + // them: the stroke's solid holds the wall, which never shows. + let covered = |f: &Placed, s: &Placed| f.paints == Paints::Fill && f.side && s.paints == Paints::Stroke && f.member == s.member; + // Is there a face of a shape's strokes and a face of the same shape's fill or strokes that the + // order of their depths draws the wrong way round where they overlap? + let mut position = vec![0usize; faces.len()]; + for (at, &k) in order.iter().enumerate() { + position[k] = at; + } + let mut checks = 0usize; + let mut misordered = false; + 'shapes: for list in &shapes { + for (i, &f) in list.iter().enumerate() { + let a = &faces[f]; + for &s in list.iter().skip(i + 1).take_while(|&&s| faces[s].bounds.x0 < a.bounds.x1) { + if checks >= MAX_LOCAL_CHECKS { + break 'shapes; + } + checks += 1; + let b = &faces[s]; + if (a.paints == Paints::Fill && b.paints == Paints::Fill) || covered(a, b) || covered(b, a) || !rects_overlap(a.bounds, b.bounds) { + continue; + } + if nearer_where_overlapping(a, b).is_some_and(|a_nearer| a_nearer != (position[f] > position[s])) { + misordered = true; + break 'shapes; + } + } + } + } + if !misordered { + return order; + } + // Moving those faces must not carry them past any other face they overlap, so every pair of + // faces with a polygon and a plane that overlap goes in the order of their depths there. + let mut sweep: Vec = (0..faces.len()).filter(|&k| faces[k].outline.len() >= 3 && faces[k].plane.is_some()).collect(); + sweep.sort_by(|&a, &b| faces[a].bounds.x0.total_cmp(&faces[b].bounds.x0)); + // For each face, the faces drawn after it, and for each, how many go before it. + let mut after: Vec> = vec![vec![]; faces.len()]; + let mut waits = vec![0usize; faces.len()]; + 'pairs: for (i, &k) in sweep.iter().enumerate() { + let a = &faces[k]; + for &j in sweep.iter().skip(i + 1).take_while(|&&j| faces[j].bounds.x0 < a.bounds.x1) { + if checks >= MAX_LOCAL_CHECKS { + break 'pairs; + } + checks += 1; + let b = &faces[j]; + if !rects_overlap(a.bounds, b.bounds) { + continue; + } + let a_later = if covered(a, b) || covered(b, a) { + position[k] > position[j] + } else { + let Some(a_nearer) = nearer_where_overlapping(a, b) else { continue }; + a_nearer + }; + let (back, front) = if a_later { (j, k) } else { (k, j) }; + after[back].push(front); + waits[front] += 1; + } + } + // Each step draws the face that comes first in `order` of those whose faces before are drawn. + let mut ready: std::collections::BinaryHeap> = + (0..faces.len()).filter(|&k| waits[k] == 0).map(|k| Reverse((position[k], k))).collect(); + // The faces drawn last, in `order`: each goes only after every face before it in `order`. + let last: Vec = order.iter().copied().filter(|&k| faces[k].depth >= f64::MAX).collect(); + let mut next_last = 0usize; + let mut drawn = vec![false; faces.len()]; + let mut out = Vec::with_capacity(order.len()); + let mut first = 0usize; + while out.len() < order.len() { + while last.get(next_last).is_some_and(|&k| drawn[k]) { + next_last += 1; + } + let limit = last.get(next_last).map_or(usize::MAX, |&k| position[k]); + let k = match ready.peek() { + Some(&Reverse((at, k))) if at < limit => { + ready.pop(); + k + } + _ => { + // A cycle, or the faces left to draw before a face drawn last wait for faces after + // it: the first face in `order` not drawn yet goes next. + while order.get(first).is_some_and(|&k| drawn[k]) { + first += 1; + } + let Some(&k) = order.get(first) else { break }; + k + } + }; + if drawn[k] { + continue; + } + drawn[k] = true; + out.push(k); + for &j in &after[k] { + waits[j] = waits[j].saturating_sub(1); + if waits[j] == 0 && !drawn[j] { + ready.push(Reverse((position[j], j))); + } + } + } + out +} + +/// Whether face `a` is nearer the viewer than face `b` where their polygons overlap on the drawing, +/// measured at the middle of the overlap. `None` when they do not overlap, when either polygon is +/// not convex, or when they are at the same depth there. +fn nearer_where_overlapping(a: &Placed, b: &Placed) -> Option { + let (pa, pb) = (a.plane?, b.plane?); + let turn = convex(&b.outline)?; + convex(&a.outline)?; + let overlap = clip_convex(&a.outline, &b.outline, turn); + let mid = centroid(&overlap)?; + let (da, db) = (pa.depth_at(mid)?, pb.depth_at(mid)?); + let tolerance = 1e-6 * (1.0 + da.abs().max(db.abs())); + ((da - db).abs() > tolerance).then_some(da > db) +} + +/// The sign of the turns of convex polygon `p` (`None` when it is not convex or has no area). +fn convex(p: &[Point]) -> Option { + let n = p.len(); + let mut sign = 0.0; + for i in 0..n { + let (a, b, c) = (p[i], p[(i + 1) % n], p[(i + 2) % n]); + let cross = (b - a).cross(c - b); + if cross.abs() <= 1e-12 { + continue; + } + if sign == 0.0 { + sign = cross.signum(); + } else if cross.signum() != sign { + return None; + } + } + (sign != 0.0).then_some(sign) +} + +/// The part of polygon `subject` inside convex polygon `clip`, whose turns have sign `turn` +/// (Sutherland–Hodgman). +fn clip_convex(subject: &[Point], clip: &[Point], turn: f64) -> Vec { + let mut out = subject.to_vec(); + for i in 0..clip.len() { + if out.is_empty() { + break; + } + let (e0, e1) = (clip[i], clip[(i + 1) % clip.len()]); + let side = |p: Point| (e1 - e0).cross(p - e0) * turn; + let input = std::mem::take(&mut out); + for j in 0..input.len() { + let (p, q) = (input[j], input[(j + 1) % input.len()]); + let (sp, sq) = (side(p), side(q)); + if sp >= 0.0 { + out.push(p); + } + if (sp >= 0.0) != (sq >= 0.0) { + let t = sp / (sp - sq); + out.push(p.lerp(q, t)); + } + } + } + out +} + +/// The centroid of polygon `p`, `None` when it has (almost) no area. It is measured from the +/// polygon's first point, so a small polygon far from the origin keeps its area. +fn centroid(p: &[Point]) -> Option { + let origin = *p.first()?; + let n = p.len(); + let (mut area, mut cx, mut cy) = (0.0, 0.0, 0.0); + for i in 0..n { + let (a, b) = (p[i] - origin, p[(i + 1) % n] - origin); + let cross = a.x * b.y - b.x * a.y; + area += cross; + cx += (a.x + b.x) * cross; + cy += (a.y + b.y) * cross; + } + (area.abs() > 1e-9).then(|| origin + Vec2::new(cx / (3.0 * area), cy / (3.0 * area))) +} + /// The most bounds comparisons [`draw_order`] makes; the fill walls it has not reached by then keep /// their depths. const MAX_OVERLAP_CHECKS: usize = 4_000_000; @@ -742,7 +1191,8 @@ const MAX_OVERLAP_CHECKS: usize = 4_000_000; /// of a shape's fill turned toward the viewer is drawn before each face of the same shape's /// covering strokes ([`Paints::Stroke`]), turned toward the viewer, whose bounds overlap its own. /// Such a stroke's closed solid holds the fill's walls, so they never show and can be drawn under -/// any other face. +/// any other face. A shape's fill faces and the faces of its other strokes then go in the order of +/// their depths where they overlap ([`local_order`]). fn draw_order(faces: &[Placed], sealed: bool) -> Vec { // Each face's depth to sort by, and whether it was moved before a stroke face at that depth. let mut keys: Vec<(f64, bool)> = faces.iter().map(|f| (f.depth, false)).collect(); @@ -781,7 +1231,7 @@ fn draw_order(faces: &[Placed], sealed: bool) -> Vec { // A stable sort: faces at the same depth keep the order of the appearance, and a fill's side // face moved to a stroke face's depth goes before it. order.sort_by(|&a, &b| keys[a].0.total_cmp(&keys[b].0).then(keys[b].1.cmp(&keys[a].1))); - order + local_order(faces, order) } /// `shapes`, the members of group or layer `n`, reshaped by the visible geometry effects `before` @@ -806,7 +1256,9 @@ type ShadowAndSurfaces = (Vec>, Vec>); /// each in its own paint. When every one is opaque with normal blending and no colored light makes /// a surface one composite, their faces are drawn in one back-to-front order (where depths tie, as /// for the caps turned toward the viewer, in the order of the appearance, and with caps, a shape's -/// fill walls before the faces of its covering strokes that overlap them: [`draw_order`]), the +/// fill walls before the faces of its covering strokes that overlap them, and its fill's faces and +/// its other strokes' faces, cut where they pass through each other ([`cut_stroke_faces`]), in the +/// order of their depths where they overlap: [`draw_order`]), the /// faces of a solid in a gradient with transparent stops in runs that carry its opacity mask /// ([`in_runs`]); /// otherwise each solid is a surface of its own, in that order. A member's opacity mask and @@ -995,18 +1447,22 @@ type BuiltSurface<'s> = (Vec, Node, &'s [Scope], Vec> /// [`with_graphics`] of built surfaces, each drawn whole. fn whole_surfaces<'s>(surfaces: Vec>, arts: &[(usize, PlanarFace, Arc)]) -> Vec<(&'s [Scope], Arc)> { - with_graphics(surfaces.into_iter().map(|(_, s, scopes, _)| (scopes, Arc::new(s))).collect(), arts) + with_graphics(surfaces.into_iter().map(|(_, s, scopes, _)| (scopes, Arc::new(s))).collect(), 0, arts) } -/// `surfaces` drawn whole, each with its scopes, and the graphics `arts` ([`placed_graphics`]) each -/// right after its surface, with that surface's scopes and its opacity mask (a gradient's -/// transparency), so a graphic is hidden where its cap is. -fn with_graphics<'s>(surfaces: Vec<(&'s [Scope], Arc)>, arts: &[(usize, PlanarFace, Arc)]) -> Vec<(&'s [Scope], Arc)> { +/// `surfaces` (those from index `first`) drawn whole, each with its scopes, and the graphics `arts` +/// ([`placed_graphics`]) of those surfaces each right after its surface, with that surface's scopes +/// and its opacity mask (a gradient's transparency), so a graphic is hidden where its cap is. +fn with_graphics<'s>( + surfaces: Vec<(&'s [Scope], Arc)>, + first: usize, + arts: &[(usize, PlanarFace, Arc)], +) -> Vec<(&'s [Scope], Arc)> { let mut out = Vec::with_capacity(surfaces.len() + arts.len()); for (k, (scopes, s)) in surfaces.into_iter().enumerate() { let mask = s.extras().mask.clone(); out.push((scopes, s)); - out.extend(arts.iter().filter(|(at, ..)| *at == k).map(|(.., art)| { + out.extend(arts.iter().filter(|(at, ..)| *at == first + k).map(|(.., art)| { let mut art = art.clone(); if let Some(mask) = &mask { Arc::make_mut(&mut art).extras_mut().mask = Some(mask.clone()); @@ -1058,7 +1514,7 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile } } let arts = placed_graphics(doc, n.id, (ROTATE, &p), b, &filled, masks); - let out = with_graphics(out, &arts); + let out = with_graphics(out, 0, &arts); return Some(if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() }); } let (parts, bounds) = solid_parts(shapes, b); @@ -1085,6 +1541,43 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile let (_, opacity, blend) = paint_of(item, *member); opacity >= 1.0 && blend == BlendMode::Normal }); + let closed = |shape: usize| shapes.get(shape).is_some_and(|s| holds_edge(&fx.id, &s.path)); + // A solid whose surface is one composite of all its facets ([`surface`]: a solid color under + // colored lights with smooth shading) has no faces to order. + let composite = |item: &AppearanceItem, f: &[Facet]| colored && paint_ref(item).color().is_some() && f.iter().any(|f| f.rgb_gradient.is_some()); + // The faces are drawn in one order (below) unless a composite draws the surfaces whole. Under + // a member's opacity mask or blending, each member's faces go in one order of their own when its + // fills and strokes are opaque, blend normally, carry no opacity mask and are not composites. + let one_order = opaque && !solids.iter().any(|(item, _, _, f, _)| composite(item, f)); + let shape_order: Vec = (0..shapes.len()) + .map(|shape| { + solids.iter().filter(|s| s.4 == shape).all(|(item, member, _, f, _)| { + let (paint, opacity, blend) = paint_of(item, *member); + opacity >= 1.0 && blend == BlendMode::Normal && !masks_surface(&paint, colored) && !composite(item, f) + }) + }) + .collect(); + let ordered = |shape: usize| if masks { shape_order.get(shape).copied().unwrap_or(false) } else { one_order }; + if solids.iter().any(|s| ordered(s.4)) { + // A stroke face that passes through a fill wall or another stroke's face is cut where it + // does. The pieces count against the limits as the faces did: cutting stops before the + // faces pass MAX_OBJECT_FACES or their paint copies pass the allowance, so an effect that + // draws uncut still draws. + let counts: Vec = solids.iter().map(|(.., f, _)| f.len()).collect(); + let room = cut_room(solids.iter().map(|(item, ..)| *item), counts.iter().sum(), paint_bytes); + let mut cuts: Vec<(Paints, usize, &mut Vec)> = solids + .iter_mut() + .filter(|(.., shape)| ordered(*shape)) + .map(|(item, _, _, f, shape)| (Paints::of(item, closed(*shape)), *shape, f)) + .collect(); + cut_stroke_faces(&mut cuts, room); + for ((item, _, _, f, _), before) in solids.iter().zip(counts) { + let added = f.get(before..).unwrap_or_default(); + if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(added, paint_ref(item), colored), paint_ref(item)) { + return None; + } + } + } let arts = if !graphics_on { vec![] } else { @@ -1100,11 +1593,11 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile .collect(); placed_graphics(doc, n.id, (&fx.id, &p), bounds, &filled, masks) }; + let members: Vec = solids.iter().map(|s| s.4).collect(); let surfaces: Vec = solids .into_iter() .map(|(item, member, scopes, f, shape)| { - let closed = shapes.get(shape).is_some_and(|s| s.path.subpaths.iter().all(|p| p.closed)); - let paints = Paints::of(item, closed); + let paints = Paints::of(item, closed(shape)); let depths: Vec = f.iter().map(|f| Placed::of(f, shape, paints)).collect(); let ends = f.iter().map(|f| f.end.filter(|_| !f.away)).collect(); let (paint, opacity, blend) = paint_of(item, member); @@ -1112,50 +1605,86 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile (depths, art, scopes, ends) }) .collect(); - if masks { - return Some(masked(n.id, whole_surfaces(surfaces, &arts))); - } - // One order takes a plain group of faces from each solid, one face for each facet. With - // colored lights a surface can instead be one clipped composite of all its facets. A composite - // has no faces to order, so when any surface is one, every surface of the solid, masked ones - // included, draws whole in member order. - let plain = - surfaces.iter().all(|(depths, s, _, _)| matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len())); - // A surface in a gradient with transparent stops carries an opacity mask: its faces go in runs - // ([`in_runs`]), and each run carries the mask. With graphics as well, the surfaces draw whole, - // each graphic right after its surface. - let masks: Vec>> = surfaces.iter().map(|(_, s, _, _)| s.extras().mask.clone()).collect(); - let masked_faces = masks.iter().any(Option::is_some); - if !opaque || !plain || (masked_faces && !arts.is_empty()) { - return Some(whole_surfaces(surfaces, &arts).into_iter().map(|(_, s)| s).collect()); - } - let (mut placed, mut faces, mut ends) = (vec![], vec![], vec![]); - for (surface, (depths, s, _, e)) in surfaces.into_iter().enumerate() { - if let NodeKind::Group { children, .. } = s.kind { - placed.extend(depths); - faces.extend(children.into_iter().map(|face| Some((surface, face)))); - ends.extend(e); - } - } let sealed = match fx.id.as_str() { INFLATE => inflate_options(&p).cap, CLASSIC_EXTRUDE => classic_extrude_options(&p).cap, _ => extrude_options(&p).cap, }; + // One order takes a plain group of faces from each solid, one face for each facet. With + // colored lights a surface can instead be one clipped composite of all its facets. A composite + // has no faces to order, so it draws whole. + let plain = |(depths, s, _, _): &BuiltSurface| matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len()); + if masks { + // Each member's surfaces, in the scopes of its opacity mask or blending: its faces in one + // order when it is opaque and plain, otherwise each surface whole. + let mut out = vec![]; + let mut surfaces = surfaces.into_iter().zip(members).enumerate().peekable(); + while let Some((first, (s, member))) = surfaces.next() { + let mut run = vec![s]; + while let Some((_, (s, _))) = surfaces.next_if(|(_, (_, m))| *m == member) { + run.push(s); + } + let flat = run.iter().all(|s| plain(s) && s.1.opacity >= 1.0 && s.1.blend == BlendMode::Normal && s.1.extras().mask.is_none()); + if ordered(member) && flat { + let scopes = run.first().map_or(&[][..], |s| s.2); + out.push((scopes, Arc::new(Node::group(n.id, in_one_order(n.id, run, first, &arts, sealed))))); + } else { + out.extend(with_graphics(run.into_iter().map(|(_, s, scopes, _)| (scopes, Arc::new(s))).collect(), first, &arts)); + } + } + return Some(masked(n.id, out)); + } + if !opaque || !surfaces.iter().all(plain) { + return Some(whole_surfaces(surfaces, &arts).into_iter().map(|(_, s)| s).collect()); + } + Some(vec![Arc::new(Node::group(n.id, in_one_order(n.id, surfaces, 0, &arts, sealed)))]) +} + +/// The faces of `surfaces` (plain groups of their faces, [`surfaces_for`]'s from index `first`) in +/// one order ([`draw_order`], `sealed` for solids with caps), each of the graphics `arts` of those +/// surfaces right after the last face it is drawn on, of the surfaces that share it. A surface in a gradient with transparent stops +/// carries an opacity mask: its faces go in runs ([`in_runs`]), each carrying the mask, and each of +/// its graphics carries the mask too ([`with_graphics`]), so a graphic is hidden where its cap is. +fn in_one_order(id: NodeId, surfaces: Vec>, first: usize, arts: &[(usize, PlanarFace, Arc)], sealed: bool) -> Vec> { + let masks: Vec>> = surfaces.iter().map(|(_, s, _, _)| s.extras().mask.clone()).collect(); + let arts: Vec<&(usize, PlanarFace, Arc)> = arts.iter().filter(|(at, ..)| (first..first + surfaces.len()).contains(at)).collect(); + let (mut placed, mut faces, mut ends) = (vec![], vec![], vec![]); + for (surface, (depths, s, _, e)) in surfaces.into_iter().enumerate() { + if let NodeKind::Group { children, .. } = s.kind { + placed.extend(depths); + faces.extend(children.into_iter().map(|face| Some((surface, face)))); + ends.extend(e.into_iter().map(|end| end.map(|end| (surface, end)))); + } + } let order = draw_order(&placed, sealed); - if masked_faces { - let faces: Vec<(usize, Arc)> = order.into_iter().filter_map(|k| faces.get_mut(k).and_then(Option::take)).collect(); - return Some(vec![Arc::new(Node::group(n.id, in_runs(n.id, faces, &masks)))]); - } - // Each face's graphics go right after the last of the faces they are drawn on. - let last: Vec> = - arts.iter().map(|(_, face, _)| order.iter().rposition(|k| ends.get(*k).copied().flatten() == Some(*face))).collect(); - let mut children = Vec::with_capacity(order.len() + arts.len()); + // Each graphic goes right after the last of the faces it is drawn on, among the surfaces that + // share it ([`placed_graphics`]): a masked surface's own, or else the run of surfaces without a + // mask that ends at its surface. + let last: Vec> = arts + .iter() + .map(|(at, face, _)| { + let at = at - first; + let from = if masks.get(at).is_some_and(Option::is_some) { + at + } else { + masks.get(..at).and_then(|before| before.iter().rposition(Option::is_some)).map_or(0, |k| k + 1) + }; + order.iter().rposition(|k| ends.get(*k).copied().flatten().is_some_and(|(surface, end)| end == *face && (from..=at).contains(&surface))) + }) + .collect(); + let mut drawn: Vec<(usize, Arc)> = Vec::with_capacity(order.len() + arts.len()); for (at, k) in order.into_iter().enumerate() { - children.extend(faces.get_mut(k).and_then(Option::take).map(|(_, face)| face)); - children.extend(last.iter().zip(&arts).filter(|(l, _)| **l == Some(at)).map(|(_, (.., art))| art.clone())); + drawn.extend(faces.get_mut(k).and_then(Option::take)); + drawn.extend(last.iter().zip(&arts).filter(|(l, _)| **l == Some(at)).map(|(_, (surface, .., art))| { + let mut art = art.clone(); + if let Some(mask) = masks.get(surface - first).cloned().flatten() { + Arc::make_mut(&mut art).extras_mut().mask = Some(mask); + } + // An index past the surfaces: the graphic goes in a run of its own, with its own mask. + (masks.len(), art) + })); } - Some(vec![Arc::new(Node::group(n.id, children))]) + if masks.iter().any(Option::is_some) { in_runs(id, drawn, &masks) } else { drawn.into_iter().map(|(_, face)| face).collect() } } /// `faces` in their back-to-front order, each with the index of its surface, where some surfaces diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index b4e012f977..5126b76660 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -253,6 +253,468 @@ fn a_fills_walls_are_drawn_before_the_stroke_faces_over_them() { } } +/// The faces of the solids effect `id` with `params` builds for `n`, in the order they are drawn, +/// as [`surfaces_for`] orders them, each with the index of the part ([`solid_parts`]) it was built +/// from and whether it is a stroke's. +fn drawn_parts(n: &Node, id: &str, params: &Value) -> Vec<(Facet, usize, bool)> { + let (path, rule) = profile(n).unwrap(); + let shapes = [Profile { path, rule, items: solid_paints(n), opacity: 1.0, scopes: vec![] }]; + let p = crate::merged_params(id, params); + let (parts, bounds) = solid_parts(&shapes, union_bounds(&shapes).unwrap()); + let mut solids = vec![]; + for (part, ((item, _, _, _, _, member), f)) in parts.iter().zip(built_solids(id, &p, &parts, bounds, MAX_OBJECT_FACES)).enumerate() { + let Some(f) = f.unwrap() else { continue }; + let closed = holds_edge(id, &shapes[*member].path); + solids.push((Paints::of(item, closed), *member, f, part, matches!(item, AppearanceItem::Stroke(_)))); + } + let mut cuts: Vec<(Paints, usize, &mut Vec)> = solids.iter_mut().map(|(paints, member, f, _, _)| (*paints, *member, f)).collect(); + cut_stroke_faces(&mut cuts, MAX_OBJECT_FACES); + let (mut placed, mut all) = (vec![], vec![]); + for (paints, member, f, part, stroke) in solids { + for facet in f { + placed.push(Placed::of(&facet, member, paints)); + all.push((facet, part, stroke)); + } + } + let sealed = match id { + INFLATE => inflate_options(&p).cap, + CLASSIC_EXTRUDE => classic_extrude_options(&p).cap, + _ => extrude_options(&p).cap, + }; + draw_order(&placed, sealed).into_iter().map(|k| all[k].clone()).collect() +} + +/// Is `p` inside the polygon of `f` (nonzero winding)? +fn facet_contains(f: &Facet, p: Point) -> bool { + let mut winding = 0i32; + for c in &f.contours { + for (a, b) in c.iter().zip(c.iter().cycle().skip(1)).take(c.len()) { + let cross = (b.x - a.x) * (p.y - a.y) - (p.x - a.x) * (b.y - a.y); + if a.y <= p.y && b.y > p.y && cross > 0.0 { + winding += 1; + } else if a.y > p.y && b.y <= p.y && cross < 0.0 { + winding -= 1; + } + } + } + winding != 0 +} + +/// The points of a 1 pt grid over `faces` (drawn in that order, each with whether it is a stroke's) +/// where the face drawn on top is the fill's while a face of the stroke turned toward the viewer is +/// nearer the viewer there by more than 0.5 pt, or the other way round. Points within 0.3 pt of an +/// edge are left out. +fn wrong_on_top(faces: &[(Facet, bool)]) -> Vec { + let polygons: Vec<&Facet> = faces.iter().map(|(f, _)| f).collect(); + let extent = + polygons.iter().flat_map(|f| f.contours.iter().flatten()).fold(Rect::new(f64::MAX, f64::MAX, f64::MIN, f64::MIN), |r, p| r.union_pt(*p)); + let mut wrong = vec![]; + let mut y = extent.y0.floor() + 0.5; + while y < extent.y1 { + let mut x = extent.x0.floor() + 0.5; + while x < extent.x1 { + let p = Point::new(x, y); + let well_inside = |f: &Facet| { + [(-0.3, -0.3), (0.3, -0.3), (-0.3, 0.3), (0.3, 0.3), (0.0, 0.0)].iter().all(|(dx, dy)| facet_contains(f, Point::new(x + dx, y + dy))) + }; + let top = faces.iter().rposition(|(f, _)| facet_contains(f, p)); + if let Some((f, stroke)) = top.and_then(|k| faces.get(k)).filter(|(f, _)| !f.away && well_inside(f)) { + let nearest = |of_stroke: bool| { + faces.iter().filter(|(g, s)| *s == of_stroke && !g.away && well_inside(g)).filter_map(|(g, _)| g.depth_at(p)).reduce(f64::max) + }; + if let (Some(ds), Some(df)) = (nearest(true), nearest(false)) + && (ds - df).abs() > 0.5 + && (ds > df) != *stroke + && f.depth_at(p).is_some() + { + wrong.push(p); + } + } + x += 1.0; + } + y += 1.0; + } + wrong +} + +/// The points of a 1 pt grid over `faces` (drawn in that order) where the face drawn on top is +/// farther from the viewer than another face turned toward the viewer, of any part, by more than +/// 0.5 pt. Points within 0.3 pt of an edge, and faces without a plane, are left out. +fn misdrawn(faces: &[(Facet, usize, bool)]) -> Vec { + let extent = + faces.iter().flat_map(|(f, ..)| f.contours.iter().flatten()).fold(Rect::new(f64::MAX, f64::MAX, f64::MIN, f64::MIN), |r, p| r.union_pt(*p)); + let mut wrong = vec![]; + let mut y = extent.y0.floor() + 0.5; + while y < extent.y1 { + let mut x = extent.x0.floor() + 0.5; + while x < extent.x1 { + let p = Point::new(x, y); + let well_inside = |f: &Facet| { + [(-0.3, -0.3), (0.3, -0.3), (-0.3, 0.3), (0.3, 0.3), (0.0, 0.0)].iter().all(|(dx, dy)| facet_contains(f, Point::new(x + dx, y + dy))) + }; + let top = faces.iter().rposition(|(f, ..)| facet_contains(f, p)).and_then(|k| faces.get(k)).filter(|(f, ..)| !f.away && well_inside(f)); + if let Some(on_top) = top.and_then(|(f, ..)| f.depth_at(p)) { + let nearest = faces.iter().filter(|(g, ..)| !g.away && well_inside(g)).filter_map(|(g, ..)| g.depth_at(p)).reduce(f64::max); + if nearest.is_some_and(|d| d - on_top > 0.5) { + wrong.push(p); + } + } + x += 1.0; + } + y += 1.0; + } + wrong +} + +/// The faces of a shape's fill and strokes are drawn in the order of their depths where they +/// overlap: on a turned C, with or without perspective, under a stroke that does not cover the +/// fill's whole edge (dashed, with a width profile, or with a brush), under a plain stroke and +/// under two strokes whose faces pass through each other, no point shows a face farther from the +/// viewer than another, in Extrude & Bevel and Extrude & Bevel (Classic), and only a few in +/// Inflate, where curved puffs cross. +#[test] +fn fill_walls_and_strokes_that_leave_gaps_draw_in_the_order_of_their_depths_where_they_overlap() { + use vectorcraft_doc::{Dash, WidthProfile}; + let views = [ + json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0}), + json!({"rotationX": 25, "rotationY": -55, "rotationZ": 10}), + json!({"rotationX": -30, "rotationY": 50, "rotationZ": 5, "perspectiveAngle": 40}), + json!({"rotationX": -30, "rotationY": 20, "rotationZ": 5, "perspectiveAngle": 40}), + ]; + type Style<'a> = (&'a str, &'a dyn Fn(&mut Node)); + let first = |n: &mut Node, set: &dyn Fn(&mut StrokeLayer)| { + if let Some(AppearanceItem::Stroke(s)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) { + set(s); + } + }; + let dash = |pattern: Vec, offset: f64| Some(Dash { pattern, offset, align_corners: false }); + let styles: [Style; 6] = [ + ("plain", &|_| {}), + ("dashed", &|n| first(n, &|s| s.dash = dash(vec![12.0, 12.0], 0.0))), + ("profiled", &|n| first(n, &|s| s.profile = Some(WidthProfile::lens()))), + ("brushed", &|n| first(n, &|s| s.brush = Some("brush".into()))), + ("dashed with perspective", &|n| first(n, &|s| s.dash = dash(vec![20.0, 6.0], 3.0))), + ("two strokes", &|n| { + first(n, &|s| s.dash = dash(vec![12.0, 12.0], 0.0)); + let mut wide = StrokeLayer::new(Paint::solid(RED), 14.0); + wide.profile = Some(WidthProfile::lens()); + n.appearance.items.push(AppearanceItem::Stroke(wide)); + }), + ]; + for id in [EXTRUDE, CLASSIC_EXTRUDE, INFLATE] { + for (v, view) in views.iter().enumerate() { + for (style, set) in &styles { + // The last two views, for the plain and the two strokes only. + if v >= 2 && !["plain", "two strokes"].contains(style) { + continue; + } + let mut params = view.clone(); + params["depth"] = json!(60); + if style.contains("perspective") { + params["perspectiveAngle"] = json!(40); + } + let mut n = stroked(&letter_c()); + set(&mut n); + let parts = drawn_parts(&n, id, ¶ms); + let faces: Vec<(Facet, bool)> = parts.iter().map(|(f, _, s)| (f.clone(), *s)).collect(); + assert!(faces.iter().any(|(_, s)| *s) && faces.iter().any(|(_, s)| !*s), "{id} {view} {style}: faces of both"); + // Inflate's curved puffs cross each other along curves its flat facets only follow + // roughly: a few points next to those crossings may still show the farther face. + let allowed = if id == INFLATE { 5 } else { 0 }; + let wrong = wrong_on_top(&faces); + assert!(wrong.len() <= allowed, "{id} {view} {style}: {} points drawn in the wrong paint, first {:?}", wrong.len(), wrong.first()); + let wrong = misdrawn(&parts); + assert!(wrong.len() <= allowed, "{id} {view} {style}: {} points show a farther face, first {:?}", wrong.len(), wrong.first()); + } + } + } +} + +/// The paths of `art`'s faces in drawing order, leaving out the graphics (clip groups). +fn face_paths(art: &Node) -> Vec { + fn walk(n: &Node, out: &mut Vec) { + match &n.kind { + NodeKind::Group { clip: true, .. } => {} + NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, out)), + _ => out.extend(n.path_data().cloned()), + } + } + let mut out = vec![]; + walk(art, &mut out); + out +} + +/// A member of a 3D group with an opacity mask or a blending mode of its own draws its fill's and +/// its strokes' faces in one order inside that mask, the order the same member draws them in +/// without it, its dashes cut where they pass through the fill's walls. A member whose stroke is +/// translucent still draws each surface whole. +#[test] +fn a_masked_members_fill_and_stroke_faces_go_in_one_order() { + let mut member = stroked(&letter_c()); + if let Some(AppearanceItem::Stroke(s)) = member.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) { + s.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false }); + } + let solid = |member: Node| { + let mut g = Node::group(NodeId(2), vec![Arc::new(member)]); + g.appearance.effects.push(fx(EXTRUDE, json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0, "depth": 60}))); + solid_art(&g).unwrap() + }; + let cover = Node::path( + NodeId(900), + vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 400.0, 400.0)), + Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0), + ); + let mut masked = member.clone(); + masked.extras_mut().mask = Some(Box::new(OpacityMask::new(cover, true))); + let mut multiplied = member.clone(); + multiplied.blend = BlendMode::Multiply; + let unmasked = face_paths(&solid(member.clone())); + for (what, scoped) in [("masked", masked.clone()), ("multiplied", multiplied)] { + let art = solid(scoped); + let mut scopes = 0; + art.walk(&mut |n| scopes += usize::from(n.extras().mask.is_some() || n.blend == BlendMode::Multiply)); + assert!(scopes > 0, "{what}: drawn in its scope"); + assert_eq!(face_paths(&art), unmasked, "{what}: the faces in the member's one order"); + } + // A translucent stroke keeps its surface whole: the fill's faces, then the stroke's. + if let Some(AppearanceItem::Stroke(s)) = masked.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) { + s.opacity = 0.5; + } + let art = solid(masked); + let mut groups = vec![]; + art.walk(&mut |n| { + if n.opacity == 0.5 { + groups.push(n.children().map_or(0, Vec::len)); + } + }); + assert_eq!(groups.len(), 1, "the stroke's surface is one translucent group"); +} + +/// Under a light that is not white, Inflate in gradients, whose faces are drawn one by one, draws the +/// fill's and the dashed stroke's faces in one order, as it does under a white light. A solid color, +/// drawn as one composite of each surface's facets, still draws each surface whole. +#[test] +fn a_colored_inflate_in_gradients_draws_its_faces_in_one_order() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let gradient = |c: Color| { + Paint::Gradient(Box::new(GradientPaint::new(Gradient::new( + GradientKind::Linear, + vec![GradientStop::new(0.0, c), GradientStop::new(1.0, Color::WHITE)], + )))) + }; + let mut n = stroked(&letter_c()); + for item in &mut n.appearance.items { + match item { + AppearanceItem::Fill(f) => f.paint = gradient(RED), + AppearanceItem::Stroke(s) => { + s.paint = gradient(BLUE); + s.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false }); + } + } + } + // How many surfaces the art draws, and how many faces the first holds. + let drawn = |n: &Node, lights: Option| { + let mut n = n.clone(); + let mut p = json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0, "depth": 60}); + if let Some(lights) = lights { + p["lights"] = lights; + } + n.appearance.effects.push(fx(INFLATE, p)); + let art = solid_art(&n).unwrap(); + let surfaces = art.children().unwrap(); + (surfaces.len(), surfaces[0].children().map_or(0, Vec::len)) + }; + let colored = json!([{"color": "#ff8080"}]); + let white = drawn(&n, None); + assert_eq!(white.0, 1, "one order"); + let cut = drawn_parts(&n, INFLATE, &json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0, "depth": 60})).len(); + assert_eq!(white.1, cut, "the white light's faces, cut"); + assert_eq!(drawn(&n, Some(colored.clone())).0, 1, "one order under the colored light"); + // A solid color under the colored light: a composite for each of the fill and the stroke. + let solid = stroked(&letter_c()); + assert_eq!(drawn(&solid, Some(colored)).0, 2); +} + +/// A face of a stroke that leaves gaps passing through the plane of its fill's wall where they +/// overlap is cut along the line where their depths meet, into the piece in front of the wall and +/// the piece behind it; a face on one side of the wall, another shape's stroke, a covering stroke +/// and a cut past the room left are left whole. +#[test] +fn a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet() { + let facet = |x: f64, normal: [f64; 3], offset: f64| Facet { + contours: vec![vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)]], + depth: 0.0, + brightness: 1.0, + illumination: [1.0; 3], + normal, + rgb_gradient: None, + outline: None, + side: true, + away: false, + end: None, + plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }), + }; + let wall = facet(0.0, [0.0, 0.0, 1.0], 0.0); + // z = x - 8: behind the wall left of x = 8, in front of it right of it. + let r = std::f64::consts::FRAC_1_SQRT_2; + let mut through = facet(5.0, [-r, 0.0, r], -8.0 * r); + // Its curved outline: the top edge bows up to y = -2. + let mut curved = BezPath::new(); + curved.move_to((5.0, 0.0)); + curved.curve_to((8.0, -8.0 / 3.0), (12.0, -8.0 / 3.0), (15.0, 0.0)); + curved.line_to((15.0, 10.0)); + curved.line_to((5.0, 10.0)); + curved.close_path(); + through.outline = Some(PathData::from_bezpath(&curved)); + let extent = |f: &Facet| polygon_bounds(&f.contours[0]); + let cut_with = |paints: Paints, member: usize, room: usize| { + let (mut fill, mut stroke) = (vec![wall.clone()], vec![through.clone()]); + let mut solids: Vec<(Paints, usize, &mut Vec)> = vec![(Paints::Fill, 0, &mut fill), (paints, member, &mut stroke)]; + cut_stroke_faces(&mut solids, room); + stroke + }; + let pieces = cut_with(Paints::Other, 0, 10); + assert_eq!(pieces.len(), 2); + let (near, far) = (extent(&pieces[0]), extent(&pieces[1])); + assert!((near.x0 - 8.0).abs() < 1e-9 && near.x1 == 15.0 && far.x0 == 5.0 && (far.x1 - 8.0).abs() < 1e-9, "{near:?} {far:?}"); + assert!(pieces[0].depth > 0.0 && pieces[1].depth < 0.0); + // Each piece keeps its side of the curved outline, the bowed edge included. + let curve = |f: &Facet| f.outline.as_ref().and_then(PathData::bounds).unwrap(); + let (near, far) = (curve(&pieces[0]), curve(&pieces[1])); + assert!((near.x0 - 8.0).abs() < 1e-6 && (near.x1 - 15.0).abs() < 1e-6 && near.y0 < -1.5, "{near:?}"); + assert!((far.x0 - 5.0).abs() < 1e-6 && (far.x1 - 8.0).abs() < 1e-6 && far.y0 < -1.5, "{far:?}"); + let whole = std::slice::from_ref(&through); + assert_eq!(cut_with(Paints::Other, 1, 10), whole, "another shape's stroke"); + assert_eq!(cut_with(Paints::Stroke, 0, 10), whole, "a covering stroke"); + assert_eq!(cut_with(Paints::Other, 0, 0), whole, "no room"); + let (mut fill, mut stroke) = (vec![wall.clone()], vec![facet(5.0, [0.0, 0.0, 1.0], 1.0)]); + cut_stroke_faces(&mut [(Paints::Fill, 0, &mut fill), (Paints::Other, 0, &mut stroke)], 10); + assert_eq!(stroke.len(), 1, "in front of the wall wherever they overlap"); + // Of two of a shape's strokes whose faces pass through each other, the later stroke's face is + // cut against the earlier one's; a covering stroke's face is never cut, and the other stroke's + // face is cut against it. Two shapes' strokes are left whole. + for (case, (first, second, cut_first)) in + [(Paints::Other, Paints::Other, false), (Paints::Stroke, Paints::Other, false), (Paints::Other, Paints::Stroke, true)].into_iter().enumerate() + { + let (mut a, mut b) = (vec![wall.clone()], vec![through.clone()]); + cut_stroke_faces(&mut [(first, 0, &mut a), (second, 0, &mut b)], 10); + assert_eq!((a.len(), b.len()), if cut_first { (2, 1) } else { (1, 2) }, "case {case}"); + } + let (mut a, mut b) = (vec![wall.clone()], vec![through.clone()]); + cut_stroke_faces(&mut [(Paints::Other, 0, &mut a), (Paints::Other, 1, &mut b)], 10); + assert_eq!((a.len(), b.len()), (1, 1), "two shapes"); +} + +/// A small polygon far from the origin keeps its area and centroid. +#[test] +fn a_small_polygon_far_away_has_a_centroid() { + let far = 100_000_000.0; + let square = [Point::new(far, far), Point::new(far + 1.0, far), Point::new(far + 1.0, far + 1.0), Point::new(far, far + 1.0)]; + let c = centroid(&square).unwrap(); + assert!((c.x - far - 0.5).abs() < 1e-6 && (c.y - far - 0.5).abs() < 1e-6, "{c:?}"); + assert!(centroid(&[]).is_none() && centroid(&square[..2]).is_none()); +} + +/// Cutting adds no more faces than the object's face limit and the paint-copy allowance leave room +/// for, so an effect that draws with its faces uncut still draws. +#[test] +fn cutting_stays_within_the_face_limit_and_the_paint_allowance() { + let items = stroked(&letter_c()).appearance.items.clone(); + let stroke = items.iter().find(|i| matches!(i, AppearanceItem::Stroke(_))).unwrap(); + let mut one = 0usize; + crate::revolve::paint_copies_add(&mut one, 6, paint_ref(stroke)); + let max = crate::revolve::MAX_PAINT_COPIES; + assert_eq!(cut_room(items.iter(), 10, 0), (MAX_OBJECT_FACES - 10).min(max / one)); + assert_eq!(cut_room(items.iter(), MAX_OBJECT_FACES + 5, 0), 0); + assert_eq!(cut_room(items.iter(), 10, max - 3 * one), 3); + assert_eq!(cut_room(items.iter(), 10, max + 1), 0); +} + +/// Where a shape's fill wall and a face of its stroke that leaves gaps overlap, the one nearer the +/// viewer there is drawn after the other, whichever their depths put first; a stroke face that +/// overlaps no fill wall keeps its place. +#[test] +fn local_order_puts_overlapping_fill_walls_and_stroke_faces_in_depth_order() { + let square = |x: f64| vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)]; + let at = |depth: f64, x: f64, z: f64, paints: Paints| Placed { + depth, + side: true, + away: false, + bounds: Rect::new(x, 0.0, x + 10.0, 10.0), + member: 0, + paints, + outline: square(x), + plane: Some(DepthPlane { normal: [0.0, 0.0, 1.0], offset: z, center: Point::ZERO, eye: None }), + }; + // 0 a fill wall at z 0; 1 a stroke face over half of it, nearer, sorted before it; 2 a stroke + // face elsewhere; 3 a stroke face over it, farther, sorted after it. + let faces = + [at(5.0, 0.0, 0.0, Paints::Fill), at(2.0, 5.0, 1.0, Paints::Other), at(1.0, 20.0, 1.0, Paints::Other), at(6.0, 2.0, -1.0, Paints::Other)]; + assert_eq!(draw_order(&faces, true), [2, 3, 0, 1]); + assert_eq!(draw_order(&faces, false), [2, 3, 0, 1]); + // A covering stroke's faces keep the wall's own rule. + let covering: Vec = faces + .iter() + .map(|f| Placed { paints: if f.paints == Paints::Other { Paints::Stroke } else { f.paints }, outline: vec![], plane: None, ..*f }) + .collect(); + assert_eq!(draw_order(&covering, false), [2, 1, 0, 3]); + // Another shape's stroke, and a stroke face at the same depth where they overlap, move nothing. + let other_shape: Vec = + faces[..3].iter().map(|f| Placed { member: usize::from(f.paints == Paints::Other), outline: f.outline.clone(), ..*f }).collect(); + assert_eq!(draw_order(&other_shape, true), [2, 1, 0]); + let level = [at(5.0, 0.0, 0.0, Paints::Fill), at(2.0, 5.0, 0.0, Paints::Other)]; + assert_eq!(draw_order(&level, true), [1, 0]); + // A stroke face moved after its fill's wall does not pass a nearer face of another shape that + // it overlaps: 0 a stroke face, 1 another shape's face in front of both, 2 the fill's wall. + let in_front = Placed { member: 1, ..at(2.0, 5.0, 2.0, Paints::Fill) }; + let shapes = [at(1.0, 5.0, 1.0, Paints::Other), in_front, at(3.0, 0.0, 0.0, Paints::Fill)]; + assert_eq!(draw_order(&shapes, true), [2, 0, 1]); + // A shape with a covering stroke as well keeps its fill wall before the covering stroke's face, + // even where that face is the farther: 0 the fill's wall, 1 the covering stroke's face behind + // it, 2 the other stroke's face in front. + let both = [at(3.0, 0.0, 0.0, Paints::Fill), at(3.0, 0.0, -1.0, Paints::Stroke), at(2.0, 5.0, 1.0, Paints::Other)]; + assert_eq!(draw_order(&both, true), [0, 1, 2]); + // Faces of a shape's strokes go in the order of their depths where they overlap too, with no + // fill face among them: 1 is nearer than 0 there, though sorted before it. + for (case, (back, front)) in + [(Paints::Other, Paints::Other), (Paints::Stroke, Paints::Other), (Paints::Stroke, Paints::Stroke)].into_iter().enumerate() + { + let strokes = [at(5.0, 0.0, 0.0, back), at(2.0, 5.0, 1.0, front)]; + assert_eq!(draw_order(&strokes, true), [0, 1], "case {case}"); + } +} + +/// A cycle of overlapping stroke faces is broken at the face that comes first by depth, and a cap +/// drawn last stays after every wall: 0 at x 0 to 10, flat at z 0; 1 at x 4 to 14, z = x - 8; 2 at +/// x 8 to 18, flat at z 1. Where they overlap, 0 is nearer than 1, 1 nearer than 2 and 2 nearer +/// than 0. 3 is the cap. +#[test] +fn a_depth_cycle_keeps_the_cap_last() { + let square = |x: f64| vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)]; + let at = |depth: f64, x: f64, normal: [f64; 3], offset: f64| Placed { + depth, + side: true, + away: false, + bounds: Rect::new(x, 0.0, x + 10.0, 10.0), + member: 0, + paints: Paints::Other, + outline: square(x), + plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }), + }; + let cap = Placed { + depth: f64::MAX, + side: false, + away: false, + bounds: Rect::new(0.0, 0.0, 18.0, 10.0), + member: 0, + paints: Paints::Other, + outline: vec![], + plane: None, + }; + let faces = [at(1.0, 0.0, [0.0, 0.0, 1.0], 0.0), at(2.0, 4.0, [-1.0, 0.0, 1.0], -8.0), at(3.0, 8.0, [0.0, 0.0, 1.0], 1.0), cap]; + assert_eq!(draw_order(&faces, true), [0, 2, 1, 3]); +} + /// The order keeps depths except where a shape's fill wall turned toward the viewer overlaps a /// face of the same shape's stroke drawn before it: the wall then goes just before that face. A /// cap, a face turned away, another shape's stroke, a stroke face the wall does not overlap and an @@ -266,6 +728,8 @@ fn the_draw_order_moves_a_fill_wall_before_the_stroke_faces_it_overlaps() { bounds: Rect::new(x, 0.0, x + 10.0, 10.0), member, paints, + outline: vec![], + plane: None, }; // 0 the fill's wall; 1 the stroke's wall over it; 2 another shape's stroke over it; 3 a stroke // wall elsewhere; 4 a stroke face turned away; 5 a fill cap; 6 the stroke's cap, nearer; 7 a @@ -292,6 +756,9 @@ fn the_draw_order_moves_a_fill_wall_before_the_stroke_faces_it_overlaps() { }; assert!(Paints::of(&stroke(&|_| {}), true) == Paints::Stroke); assert!(Paints::of(&stroke(&|_| {}), false) == Paints::Other, "an open shape"); + let closed = profile(&stroked(&letter_c())).unwrap().0; + assert!(holds_edge(EXTRUDE, &closed) && holds_edge(CLASSIC_EXTRUDE, &closed)); + assert!(!holds_edge(INFLATE, &closed), "an inflated fill can rise in front of its stroke"); assert!(Paints::of(&stroke(&|s| s.width = 0.0), true) == Paints::Other, "no width"); let dash = vectorcraft_doc::Dash { pattern: vec![4.0, 4.0], offset: 0.0, align_corners: false }; assert!(Paints::of(&stroke(&|s| s.dash = Some(dash.clone())), true) == Paints::Other, "dashes"); diff --git a/crates/effects/src/solids/tests_graphics.rs b/crates/effects/src/solids/tests_graphics.rs index aa73535fc5..bf219353cf 100644 --- a/crates/effects/src/solids/tests_graphics.rs +++ b/crates/effects/src/solids/tests_graphics.rs @@ -620,6 +620,110 @@ fn a_solid_in_a_transparent_gradient_keeps_its_graphic() { assert_eq!(masks(&solid_art_in(Some(&d), &n).unwrap()), vec![true, false]); } +/// The paths of `art`'s faces in drawing order (a face lit by a colored light is a clip group: its +/// clipping path), leaving out the graphics (clip groups of solid-color paths). +fn face_paths(art: &Node) -> Vec { + fn walk(n: &Node, out: &mut Vec) { + match &n.kind { + NodeKind::Group { children, clip: true } => { + let graphic = children.get(1).is_some_and(|inner| match &inner.kind { + NodeKind::Group { children: paths, clip: false } => paths.iter().all(|p| { + p.path_data().is_some() + && p.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if f.paint.color().is_some())) + }), + _ => false, + }); + if !graphic { + out.extend(children.first().and_then(|c| c.path_data()).cloned()); + } + } + NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, out)), + _ => out.extend(n.path_data().cloned()), + } + } + let mut out = vec![]; + walk(art, &mut out); + out +} + +/// A turned solid in a gradient with transparent stops under a colored light, with a dashed stroke +/// and a graphic, draws its fill's and its stroke's faces in the one order it draws them in without +/// the graphic, and the graphic keeps the cap's mask and goes after the fill's cap, not the stroke's. +#[test] +fn a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let d = document(); + let mut stop = GradientStop::new(1.0, red()); + stop.opacity = 0.25; + let gradient = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop])); + let solid = |graphics: Value| { + let mut n = object( + EXTRUDE, + json!({"rotationX": -20.0, "rotationY": -40.0, "depth": 60.0, "shade": true, "lights": [{"color": "#ff8080"}], "graphics": graphics}), + ); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.paint = Paint::Gradient(Box::new(gradient.clone())); + } + // A gradient stroke: a solid color under the colored light would be one composite. + let blues = Gradient::new( + GradientKind::Linear, + vec![GradientStop::new(0.0, Color::rgb(0.0, 0.0, 1.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 0.5))], + ); + let mut stroke = StrokeLayer::new(Paint::Gradient(Box::new(GradientPaint::new(blues))), 6.0); + stroke.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false }); + n.appearance.items.push(AppearanceItem::Stroke(stroke)); + solid_art_in(Some(&d), &n).unwrap() + }; + let with = solid(json!([{"symbol": "Mark"}])); + let without = solid(json!([])); + assert!(face_paths(&without).len() > 20, "the faces are found"); + assert_eq!(face_paths(&with), face_paths(&without), "the faces in one order"); + // The graphic is drawn on the fill's cap and on the stroke's (the clip groups holding the + // symbol's red square); the fill's, whose surface carries the mask, carries it too. + let mut masked = vec![]; + with.walk(&mut |c| { + if let NodeKind::Group { children, clip: true } = &c.kind + && let [_, inner] = children.as_slice() + && let NodeKind::Group { children: paths, clip: false } = &inner.kind + && paths.iter().any(|p| { + p.appearance.items.iter().any(|i| match i { + AppearanceItem::Fill(f) => f.paint.color().is_some_and(|c| c.to_rgb()[1] < 0.1 && c.to_rgb()[0] > 0.3), + AppearanceItem::Stroke(_) => false, + }) + }) + { + masked.push(c.extras().mask.is_some()); + } + }); + masked.sort_unstable(); + assert_eq!(masked, [false, true], "the fill's graphic carries the cap's mask"); + // The fill's graphic goes right after the fill's cap, so the dashes on the cap's edge, drawn + // after it, cover it. Drawn in order: the fill's graphic (the masked clip group), and each face, + // the fill's or the stroke's by its gradient's first stop (red or blue), with its bounds. + let mut drawn: Vec<(&str, Rect)> = vec![]; + with.walk(&mut |c| { + if let NodeKind::Group { children, clip: true } = &c.kind + && c.extras().mask.is_some() + && let Some(bounds) = children.first().and_then(|clip| clip.path_data()).and_then(PathData::bounds) + { + drawn.push(("graphic", bounds)); + } + let first_stop = c.appearance.items.iter().find_map(|i| match i { + AppearanceItem::Fill(f) => match &f.paint { + Paint::Gradient(g) => g.gradient.stops.first().map(|s| s.color.to_rgb()), + _ => None, + }, + AppearanceItem::Stroke(_) => None, + }); + if let (Some(rgb), Some(bounds)) = (first_stop, c.path_data().and_then(PathData::bounds)) { + drawn.push((if rgb[0] > rgb[2] { "fill" } else { "stroke" }, bounds)); + } + }); + let graphic = drawn.iter().position(|(kind, _)| *kind == "graphic").unwrap(); + let covering = |(kind, b): &(&str, Rect)| *kind == "stroke" && b.intersect(drawn[graphic].1).area() > 0.0; + assert!(drawn[graphic..].iter().any(covering), "a dash on the cap's edge is drawn over the fill's graphic"); +} + #[test] fn a_cap_with_a_hole_keeps_the_hole_out_of_the_graphic() { let d = document(); diff --git a/crates/effects/src/tests/rasterfollow.rs b/crates/effects/src/tests/rasterfollow.rs index e0c7bc5130..aead8b72ce 100644 --- a/crates/effects/src/tests/rasterfollow.rs +++ b/crates/effects/src/tests/rasterfollow.rs @@ -523,11 +523,12 @@ fn a_groups_transform_applies_after_its_members_own() { let mut on_fill = fill_square(33, vec![shadow(10.0, 0.0, 0.0)]); on_fill.appearance.effects = vec![turn()]; let art = crate::evaluate_container(None, &group(32, vec![on_fill], vec![uneven()])).unwrap(); - assert!(near(&[fill_shadow(&node_in(&art, 33))], &[want]), "fill: {:?}", fill_shadow(&node_in(&art, 33))); + // The member is drawn as its art: a group with its id holding the turned square. + let filled = node_in(&art, 33).children().and_then(|ch| ch.first().map(|c| (**c).clone())).unwrap(); + assert!(near(&[fill_shadow(&filled)], &[want]), "fill: {:?}", fill_shadow(&filled)); let nested = group(34, vec![group(35, vec![square(36, vec![shadow(10.0, 0.0, 0.0)])], vec![turn()])], vec![uneven()]); let art = crate::evaluate_container(None, &nested).unwrap(); - let inner = crate::evaluate_container(None, &node_in(&art, 35)).unwrap(); - assert!(near(&shadows_in(&inner), &[want]), "nested: {:?}", shadows_in(&inner)); + assert!(near(&shadows_in(&art), &[want]), "nested: {:?}", shadows_in(&art)); } /// An object's Transform effect transforms the raster effects of its fills and strokes with the @@ -645,7 +646,8 @@ fn a_groups_transform_moves_its_members_fills_shadows_beside_their_own_transform let art = crate::evaluate_container(None, &g).unwrap(); for (id, _, want) in &cases { let member = node_in(&art, *id); - let drawn = shadows_in(&crate::reshape(None, &member, None).unwrap()); + // The member is drawn as its art, its fill's own Transform effect applied. + let drawn = shadows_in(&member); assert!(!drawn.is_empty() && near(&drawn, &vec![*want; drawn.len()]), "Scale Strokes & Effects {strokes}: {id} {drawn:?}"); } } diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 80ed19d145..af768284b0 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -778,6 +778,8 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap< pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000; pub(crate) use addons::{DecodedImages, refresh_color_masks}; +/// Document Info's category titles and the Objects category's count labels. +pub use docinfo::{CATEGORIES, OBJECT_LABELS}; pub use docmenu::guide_indexes; pub(crate) use edit::{settle_interaction, typing_in_progress}; pub(crate) use object::bounds_rewrite; diff --git a/crates/engine/src/cmd/addons/document.rs b/crates/engine/src/cmd/addons/document.rs index 654138a1dd..68681b50fa 100644 --- a/crates/engine/src/cmd/addons/document.rs +++ b/crates/engine/src/cmd/addons/document.rs @@ -132,8 +132,10 @@ fn export_all_open(s: &mut Session, p: &Value) -> Result { let active = s.active; for i in 0..s.docs.len() { // Each document in turn is the one Save a Copy writes; switching tabs this way leaves every - // document's tool and interaction alone, and the active one comes back below. + // document's tool and interaction alone, and the active one comes back below. Its colors + // are written through its own profiles. s.active = Some(i); + s.sync_front_profiles(); let Ok(st) = s.doc() else { continue }; let title = st.doc.title.clone(); let stem = fileio::file_stem(st.path.as_deref().unwrap_or(&title)); @@ -160,6 +162,7 @@ fn export_all_open(s: &mut Session, p: &Value) -> Result { } } s.active = active; + s.sync_front_profiles(); Ok(json!({ "files": files, "failed": failed, "format": format.id })) } diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index fb86fa7852..afe86769db 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -1365,17 +1365,19 @@ fn copy_from(s: &mut Session, p: &Value) -> Result { let (fill, stroke) = (attrs.appearance.fill, attrs.appearance.stroke); let source_has = |kind: bool| picked.appearance.items.iter().any(|it| it.is_fill() == kind); let source_shows = |kind: bool| picked.appearance.items.iter().any(|it| it.is_fill() == kind && it.visible()); + // A whole pick replaces the stack: it removes the rows of a kind the source has no row of. + let whole = fill == FillAttrs::ALL && stroke == StrokeAttrs::ALL; let (paints, opacities) = if append { let rows = (fill.color && source_shows(true), stroke.color && source_shows(false)); (rows, rows) } else { ( (fill.color, stroke.color || (stroke.weight && source_has(false))), - (fill.transparency && source_has(true), stroke.transparency && source_has(false)), + (fill.transparency && (whole || source_has(true)), stroke.transparency && (whole || source_has(false))), ) }; // A pick of some attributes edits the topmost row of its kind, which may be hidden; `append` and a whole pick write rows. - let rows_written = append || (fill == FillAttrs::ALL && stroke == StrokeAttrs::ALL); + let rows_written = append || whole; let top_shows = |id: NodeId, kind: bool| { let items = d.node(id).map_or(&[][..], |n| &n.appearance.items[..]); items.iter().rev().find(|it| it.is_fill() == kind).is_some_and(|it| it.visible()) @@ -1389,6 +1391,9 @@ fn copy_from(s: &mut Session, p: &Value) -> Result { .collect() }; let mut opacity_rows = top_opacity_changed(&before, d, &targets); + // A written row that had paint before the pick counts too when the pick left it without paint, as in + // `capture_series_writes`. + opacity_rows.extend(painted_rows(&before, written(opacities))); opacity_rows.extend(painted_rows(d, written(opacities))); let mut rows = top_paint_changed(&before, d, &targets); rows.extend(painted_rows(d, written(paints))); diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index 9c6c28b900..11519b84be 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -527,8 +527,9 @@ fn color_groups(cmd: &str, d: &mut Document, items: Vec>) -> Result, + /// The encoded image the tracer decodes: the blob under the image's key, shared with the + /// document. Two blobs are equal when they are the same allocation or hold the same bytes. + bytes: Arc>, } /// What `imageTrace.make` and `imageTrace.makeAndExpand` take from the session before they trace. @@ -549,7 +553,6 @@ struct Prepared { params_json: Value, preset_label: String, library: Vec<([u8; 3], Paint)>, - bytes: Arc>, } /// What command `c` with params `p` traces, and how, from the session: everything but the trace. @@ -597,8 +600,8 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result { let bytes = Arc::clone(&blob.bytes); let library = trace_library(c, s, &mut params)?; let traced_with = serde_json::to_value(¶ms).map_err(|e| EngineError::Other(e.to_string()))?; - let inputs = TraceInputs { target, image, params: traced_with, swatches: params.swatches.clone() }; - Ok(Prepared { inputs, trace: params, view, params_json, preset_label, library, bytes }) + let inputs = TraceInputs { target, image, params: traced_with, swatches: params.swatches.clone(), bytes }; + Ok(Prepared { inputs, trace: params, view, params_json, preset_label, library }) } /// What a trace made of an image: the size in pixels it was decoded at, and the paths. @@ -616,11 +619,11 @@ impl Traced { } } -/// Decode the image `bytes` and trace it with `params`, telling `steps` how far it has got -/// ([`tr::trace_watched`]); [`EngineError::Cancelled`] once `steps` answers `false`. -fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, bytes: &[u8], steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result { +/// Decode the image bytes of `inputs` and trace them with `params`, telling `steps` how far it has +/// got ([`tr::trace_watched`]); [`EngineError::Cancelled`] once `steps` answers `false`. +fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result { // An image over the tracer's size is traced scaled down (the paths are scaled back). - let raster = tr::Raster::decode_to_fit(bytes).map_err(|e| EngineError::Other(e.to_string()))?; + let raster = tr::Raster::decode_to_fit(&inputs.bytes).map_err(|e| EngineError::Other(e.to_string()))?; if !steps(0, 0) { return Err(EngineError::Cancelled); } @@ -682,7 +685,8 @@ impl TraceRun { (self.prepared.inputs.image.width, self.prepared.inputs.image.height) } - /// Does it still apply: would the command trace the same object, image and settings now? + /// Does it still apply: would the command trace the same object, image, pixels and settings + /// now? pub fn current(&self, s: &Session) -> bool { prepare(s, self.command, &self.params).is_ok_and(|now| now.inputs == self.prepared.inputs) } @@ -691,13 +695,13 @@ impl TraceRun { /// failed or stopped ([`EngineError::Cancelled`] once `steps` answers `false`). It touches no /// document, so it can run on any thread. pub fn run(&self, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result { - trace_now(&self.prepared.inputs, &self.prepared.trace, &self.prepared.bytes, steps) + trace_now(&self.prepared.inputs, &self.prepared.trace, steps) } } pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result { let c = if expand { "imageTrace.makeAndExpand" } else { "imageTrace.make" }; - let Prepared { inputs, trace, view, params_json, preset_label, library, bytes } = prepare(s, c, p)?; + let Prepared { inputs, trace, view, params_json, preset_label, library } = prepare(s, c, p)?; let group_by_color = expand && by_color_param(c, p)?; // A saved preset's settings join the journal entry, so a replay traces as this run did after // the preset is changed, renamed or deleted. @@ -709,7 +713,7 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result traced, - _ => trace_now(&inputs, &trace, &bytes, &|_, _| true)?, + _ => trace_now(&inputs, &trace, &|_, _| true)?, }; let TraceInputs { target, image: img, .. } = inputs; let mut warnings = keep_warnings(&trace, &res); diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index d28bd0e6c9..446634d21c 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -143,17 +143,13 @@ pub(crate) fn subpath_selected_segments( let has_explicit_segs = seg_refs.is_some_and(|segments| !segments.is_empty()); if has_explicit_segs { if let Some(segments) = seg_refs { - for &(s, seg) in segments { - if s == si && seg < seg_count { - selected_segs.insert(seg); - } - } + selected_segs.extend(super::path::subpath_refs(segments, si).filter(|&seg| seg < seg_count)); } return selected_segs; } if let Some(anchors) = anchor_refs { - let sub_anchors: BTreeSet = anchors.iter().filter_map(|&(s, a)| (s == si && a < n).then_some(a)).collect(); + let sub_anchors: BTreeSet = super::path::subpath_refs(anchors, si).filter(|&a| a < n).collect(); if !sub_anchors.is_empty() { for i in 0..seg_count { let next = (i + 1) % n; diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 16990fc2ea..6c75eae128 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -5,9 +5,11 @@ //! Colour settings and the proof view are process-wide (`vectorcraft_color::cms::active`, //! `vectorcraft_render::proof::view`). A document's assigned profiles are stored in //! `Document::color_profiles` (files before format v3: `Document.unknown["colorProfiles"]`) and -//! take the place of the working spaces in the active settings when assigned, and when the working -//! settings change while the document is in front ([`use_front_profiles`]); the working spaces stay -//! as Edit → Color Settings set them. +//! take the place of the working spaces in the active settings while the document is in front +//! ([`use_front_profiles`]): when they are assigned, when the working settings change, and when the +//! document comes to the front or its assignment comes back (an open, a switch, a close, a revert, +//! an undo or a rollback, [`Session::sync_front_profiles`]); the working spaces stay as Edit → Color +//! Settings set them. use std::collections::BTreeMap; use std::sync::Arc; @@ -181,7 +183,7 @@ fn touch_all(s: &mut Session) { /// Make the active settings the working settings with the profiles the front document is assigned /// in place of the working spaces (none, or no document open: the working spaces). The open /// documents redraw when the active settings change. -fn use_front_profiles(s: &mut Session) { +pub(crate) fn use_front_profiles(s: &mut Session) { let (rgb, cmyk) = s.active().map(|d| doc_profiles(&d.doc)).unwrap_or_default(); if cms::use_document_profiles(rgb.as_deref(), cmyk.as_deref()) { touch_all(s); diff --git a/crates/engine/src/cmd/docinfo.rs b/crates/engine/src/cmd/docinfo.rs index 833c7d22bf..a43325becd 100644 --- a/crates/engine/src/cmd/docinfo.rs +++ b/crates/engine/src/cmd/docinfo.rs @@ -52,7 +52,7 @@ pub const CATEGORIES: [(&str, &str); 13] = [ ]; /// The object counts of `document.info` and their labels. -const OBJECT_LABELS: [(&str, &str); 19] = [ +pub const OBJECT_LABELS: [(&str, &str); 19] = [ ("paths", "Paths"), ("compoundPaths", "Compound Paths"), ("groups", "Groups"), diff --git a/crates/engine/src/cmd/draw2/anchors.rs b/crates/engine/src/cmd/draw2/anchors.rs index 10254f3cd3..5b80fcc80f 100644 --- a/crates/engine/src/cmd/draw2/anchors.rs +++ b/crates/engine/src/cmd/draw2/anchors.rs @@ -116,8 +116,11 @@ pub(super) fn remove_anchor(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Other("no such anchor".into())); } let mut emptied = Beside::replacing(d, &[id]); - let removed = remove_anchors_of(d, sel, &mut emptied, id, [(si, ai)], curvature)?; + let removed = remove_anchors_of(d, sel, &mut emptied, id, vec![(si, ai)], curvature)?; emptied.finish(d)?; + if removed { + sel.remove(id); + } Ok(removed) })?; Ok(json!({ "removedObject": removed })) @@ -136,14 +139,14 @@ pub(super) fn remove_anchors(s: &mut Session, _: &Value) -> Result { return Err(bad("path.removeAnchors", "direct-select anchor points of a path")); } let removed = s.edit("Remove Anchor Points", |d, sel| { - let mut removed = 0; + let mut gone = Vec::new(); let mut emptied = Beside::replacing(d, &jobs.iter().map(|(id, _)| *id).collect::>()); for (id, anchors) in jobs { let shape: Vec<(usize, bool)> = d.node(id).and_then(Node::path_data).map(|p| p.subpaths.iter().map(|sp| (sp.anchors.len(), sp.closed)).collect()).unwrap_or_default(); let next = following_anchors(&shape, &anchors); if remove_anchors_of(d, sel, &mut emptied, id, anchors, false)? { - removed += 1; + gone.push(id); } else if !next.is_empty() { // The next anchor along is selected, so the next Remove Anchor Points goes on from // there without picking it first (#2241). @@ -151,7 +154,8 @@ pub(super) fn remove_anchors(s: &mut Session, _: &Value) -> Result { } } emptied.finish(d)?; - Ok(removed) + sel.remove_all(gone.iter().copied()); + Ok(gone.len()) })?; Ok(json!({ "removedObjects": removed })) } @@ -160,19 +164,32 @@ pub(super) fn remove_anchors(s: &mut Session, _: &Value) -> Result { /// path whose subpaths have `shape` (anchor count, closed): in each subpath, the anchor after its /// last removed one, round the end of a closed subpath, or the one before it at an open subpath's /// end. Indexes are those after the removal, without the subpaths left with fewer than two anchors. +/// `removed` is in ascending order without repeats, as a selection holds it, and each subpath reads +/// only its own pairs. fn following_anchors(shape: &[(usize, bool)], removed: &[(usize, usize)]) -> BTreeSet<(usize, usize)> { let mut next = BTreeSet::new(); let mut kept = 0; + let mut rest = removed; for (si, &(n, closed)) in shape.iter().enumerate() { - let gone: BTreeSet = removed.iter().filter(|&&(s, a)| s == si && a < n).map(|&(_, a)| a).collect(); + let (mine, after) = rest.split_at(rest.iter().take_while(|&&(s, _)| s == si).count()); + rest = after; + let gone = &mine[..mine.partition_point(|&(_, a)| a < n)]; if n - gone.len() < 2 { continue; } - if let Some(&last) = gone.last() { - let wrap = if closed { 0..last } else { 0..0 }; - let after = (last + 1..n).chain(wrap).find(|a| !gone.contains(a)); - if let Some(a) = after.or_else(|| (0..last).rev().find(|a| !gone.contains(a))) { - next.insert((kept, a - gone.range(..a).count())); + if let Some(&(_, last)) = gone.last() { + // Anchors past `last` are all left. Below it, the first one left (round a closed + // subpath's end) is past the removed run from 0, and the last one left is below the + // removed run down from `last`. + let a = if last + 1 < n { + Some(last + 1) + } else if closed { + Some(gone.iter().zip(0..).take_while(|&(&(_, g), k)| g == k).count()) + } else { + last.checked_sub(gone.iter().rev().zip((0..=last).rev()).take_while(|&(&(_, g), k)| g == k).count()) + }; + if let Some(a) = a { + next.insert((kept, a - gone.partition_point(|&(_, g)| g < a))); } } kept += 1; @@ -183,34 +200,37 @@ fn following_anchors(shape: &[(usize, bool)], removed: &[(usize, usize)]) -> BTr /// Remove `anchors` (subpath, anchor) of path `id` without opening it, refitting the curve round /// each one, or with `curvature` re-curving it as the Curvature tool curves its points /// ([`vectorcraft_tools::draw2::curvature_remove`]). A subpath left with one anchor is removed, -/// and a path left with no subpath is removed through `emptied`. True when the path went. +/// and a path left with no subpath is removed through `emptied`; the caller then takes it out of +/// the selection. True when the path went. fn remove_anchors_of( d: &mut Document, sel: &mut Selection, emptied: &mut Beside, id: NodeId, - anchors: impl IntoIterator, + mut anchors: Vec<(usize, usize)>, curvature: bool, ) -> Result { - let mut anchors: Vec<(usize, usize)> = anchors.into_iter().collect(); // The last first, so the indexes still to come stay valid. anchors.sort_unstable_by(|a, b| b.cmp(a)); anchors.dedup(); let path = path_mut(d, id)?; - for (si, ai) in anchors { - if let Some(sp) = path.subpaths.get_mut(si) { - if curvature { + let mut rest = &anchors[..]; + while let Some(&(si, _)) = rest.first() { + let (mine, after) = rest.split_at(rest.iter().take_while(|&&(s, _)| s == si).count()); + rest = after; + let Some(sp) = path.subpaths.get_mut(si) else { continue }; + if curvature { + for &(_, ai) in mine { vectorcraft_tools::draw2::curvature_remove(sp, ai); - } else { - po::remove_anchor(sp, ai); } + } else { + po::remove_anchors(sp, &mine.iter().map(|&(_, ai)| ai).collect::>()); } } path.subpaths.retain(|sp| sp.anchors.len() >= 2); let gone = path.is_empty(); if gone { emptied.put(d, id, vec![])?; - sel.remove(id); } else { sel.anchors.remove(&id); sel.segments.remove(&id); @@ -277,3 +297,47 @@ pub(super) fn reshape_segment(s: &mut Session, p: &Value) -> Result { })?; ok() } + +#[cfg(test)] +mod tests { + use super::*; + + /// [`following_anchors`] by its definition: for each subpath, a search of the anchors after + /// its last removed one, round a closed end, then before it. + fn following_by_search(shape: &[(usize, bool)], removed: &[(usize, usize)]) -> BTreeSet<(usize, usize)> { + let mut next = BTreeSet::new(); + let mut kept = 0; + for (si, &(n, closed)) in shape.iter().enumerate() { + let gone: BTreeSet = removed.iter().filter(|&&(s, a)| s == si && a < n).map(|&(_, a)| a).collect(); + if n - gone.len() < 2 { + continue; + } + if let Some(&last) = gone.last() { + let wrap = if closed { 0..last } else { 0..0 }; + let after = (last + 1..n).chain(wrap).find(|a| !gone.contains(a)); + if let Some(a) = after.or_else(|| (0..last).rev().find(|a| !gone.contains(a))) { + next.insert((kept, a - gone.range(..a).count())); + } + } + kept += 1; + } + next + } + + #[test] + fn following_anchors_matches_a_search_along_each_subpath() { + let mut seed = 0x2545_f491_4f6c_dd1d_u64; + let mut rnd = |m: u64| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % m) as usize + }; + for case in 0..2000 { + let shape: Vec<(usize, bool)> = (0..rnd(5) + 1).map(|_| (rnd(9), rnd(2) == 0)).collect(); + let removed: BTreeSet<(usize, usize)> = (0..rnd(14)).map(|_| (rnd(shape.len() as u64 + 1), rnd(11))).collect(); + let removed: Vec<_> = removed.into_iter().collect(); + assert_eq!(following_anchors(&shape, &removed), following_by_search(&shape, &removed), "case {case}: {shape:?} removing {removed:?}"); + } + } +} diff --git a/crates/engine/src/cmd/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs index df383c838b..0ac4fc8d6b 100644 --- a/crates/engine/src/cmd/draw2/smooth.rs +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -8,10 +8,22 @@ use super::{ // ---------- Smooth ---------- -/// Refit the anchors of an open run `a[lo..=hi]` keeping its end points and outer handles. -fn refit_run(anchors: &[Anchor], tol: f64) -> Vec { +/// The spread (points) of the Gaussian the Smooth tool smooths a path along its length with before +/// refitting it, as a share of the tool's reach: a third, so each point is averaged with the stretch +/// of path within the reach on either side of it. VectorCraft's own value. +const SMOOTH_SPREAD: f64 = 1.0 / 3.0; + +/// The options the Smooth tool refits with: the path smoothed along its length by a Gaussian of +/// spread `sigma` (none at 0), then refitted within `tol` of that and within twice the distance the +/// smoothing moved it, keeping a corner only where the path turns back on itself. +fn refit_options(tol: f64, sigma: f64) -> SimplifyOptions { + SimplifyOptions { tolerance: tol, corner_angle_deg: 179.0, straight_lines: false, smooth: sigma, smooth_moved_only: true } +} + +/// Smooth and refit the anchors of an open run `a[lo..=hi]` keeping its end points and outer handles. +fn refit_run(anchors: &[Anchor], tol: f64, sigma: f64) -> Vec { let piece = PathData::single(SubPath::new(anchors.to_vec(), false)); - let fitted = po::simplify_with(&piece, &SimplifyOptions { tolerance: tol, corner_angle_deg: 179.0, straight_lines: false, ..Default::default() }); + let fitted = po::simplify_with(&piece, &refit_options(tol, sigma)); let Some(mut out) = fitted.subpaths.into_iter().next().map(|s| s.anchors).filter(|a| a.len() >= 2) else { return anchors.to_vec() }; let (f, l) = (anchors[0], anchors[anchors.len() - 1]); let last = out.len() - 1; @@ -25,7 +37,7 @@ fn refit_run(anchors: &[Anchor], tol: f64) -> Vec { out } -fn smooth_subpath(sp: &SubPath, near: &dyn Fn(Point) -> bool, tol: f64) -> Option { +fn smooth_subpath(sp: &SubPath, near: &dyn Fn(Point) -> bool, tol: f64, sigma: f64) -> Option { let n = sp.anchors.len(); let marked: Vec = sp.anchors.iter().map(|a| near(a.p)).collect(); if n < 3 || !marked.iter().any(|m| *m) { @@ -33,11 +45,8 @@ fn smooth_subpath(sp: &SubPath, near: &dyn Fn(Point) -> bool, tol: f64) -> Optio } if sp.closed { let Some(k) = marked.iter().position(|m| !m) else { - // Everything is in range: smooth the whole closed path. - let f = po::simplify_with( - &PathData::single(sp.clone()), - &SimplifyOptions { tolerance: tol, corner_angle_deg: 179.0, straight_lines: false, ..Default::default() }, - ); + // Everything is in range: smooth the whole closed path, across its start too. + let f = po::simplify_with(&PathData::single(sp.clone()), &refit_options(tol, sigma)); return f.subpaths.into_iter().next(); }; // Rotate so an untouched anchor comes first, duplicate it at the end and treat as open. @@ -48,14 +57,14 @@ fn smooth_subpath(sp: &SubPath, near: &dyn Fn(Point) -> bool, tol: f64) -> Optio open.anchors.push(open.anchors[0]); m.push(false); open.closed = false; - let mut res = smooth_open(&open.anchors, &m, near, tol); + let mut res = smooth_open(&open.anchors, &m, near, tol, sigma); let l = res.pop()?; if let Some(r0) = res.first_mut() { r0.h_in = l.h_in; } return Some(SubPath::new(res, true)); } - Some(SubPath::new(smooth_open(&sp.anchors, &marked, near, tol), false)) + Some(SubPath::new(smooth_open(&sp.anchors, &marked, near, tol, sigma), false)) } /// The segment `c`, which ends in the drag's reach (`near`) and starts outside it, split where it @@ -84,10 +93,11 @@ fn split_at_reach(c: CubicBez, near: &dyn Fn(Point) -> bool) -> Option<(CubicBez (hi > 0.02).then(|| (part(0.0..hi), part(hi..1.0))) } -/// `anchors` with each run of `marked` ones refitted, together with the stretch of the segments -/// leading into the run that is in the drag's reach (`near`): a short drag smooths what is under -/// it, and the rest of a long segment next to it stays as it was (#1512). -fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool, tol: f64) -> Vec { +/// `anchors` with each run of `marked` ones smoothed by a Gaussian of spread `sigma` and refitted +/// within `tol`, together with the stretch of the segments leading into the run that is in the +/// drag's reach (`near`): a short drag smooths what is under it, and the rest of a long segment next +/// to it stays as it was (#1512). +fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool, tol: f64, sigma: f64) -> Vec { let n = anchors.len(); let mut runs = vec![]; let mut i = 0; @@ -127,7 +137,7 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool head = Some(Anchor { h_out: far.p1, ..*outer }); *outer = Anchor::with_handles(far.p3, far.p2, reach.p1); } - let new = refit_run(&piece, tol); + let new = refit_run(&piece, tol, sigma); out.splice(lo..=hi, head.into_iter().chain(new).chain(tail)); } out @@ -138,6 +148,7 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result { let pts = points_param(p, "points", C)?; let radius = number_or(p, "radius", 12.0, C)?.max(0.0); let tol = number_or(p, "fidelity", 2.5, C)?.clamp(vectorcraft_tools::draw2::SMOOTH_MIN_FIDELITY, 100.0); + let sigma = radius * SMOOTH_SPREAD; let st = s.doc()?; let near = |q: Point| dist_to_polyline(&pts, q) <= radius; let mut plan = vec![]; @@ -148,7 +159,7 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result { let subs: Vec = pd .subpaths .iter() - .map(|sp| match smooth_subpath(sp, &near, tol) { + .map(|sp| match smooth_subpath(sp, &near, tol, sigma) { Some(n) if n != *sp && n.anchors.len() >= 2 => { changed = true; n diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index f3befb3462..990ac1a1c6 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -678,12 +678,22 @@ fn undo_group_end(s: &mut Session, p: &Value) -> Result { /// under an interaction that would then preview on, or cancel to, the document from before (#1719). /// A typing session also ends in the Type tool, whose caret and marked text (IME) must follow the /// document. A preview that Real-time Drawing off left unapplied is applied first, as the tool's own -/// commit applies it; when it fails, the interaction is canceled. +/// commit applies it; when it fails, the interaction is canceled. The applied preview's warning +/// goes to the running command's result or the tool's status messages, as the tool's own commit +/// reports it ([`Session::note_settled_warning`]). pub(crate) fn settle_interaction(s: &mut Session) -> Result<()> { let typing = typing_in_progress(s); match s.unapplied_interaction_preview().filter(|_| !s.previewing) { - Some((cmd, p)) if s.preview(&cmd, &p).is_err() => s.cancel_interaction()?, - _ => s.commit_interaction()?, + Some((cmd, p)) => match s.preview(&cmd, &p) { + Ok(v) => { + if let Some(w) = v.get("warning").and_then(Value::as_str) { + s.note_settled_warning(w); + } + s.commit_interaction()? + } + Err(_) => s.cancel_interaction()?, + }, + None => s.commit_interaction()?, } if typing { s.set_tool_option("endTyping", &Value::Bool(true)); @@ -1086,7 +1096,7 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result { subpaths.extend(super::path::without_segments(sp, &cuts)); } else { // Picked anchors leave the path with their connections, as Clear removes them. - let gone: BTreeSet = anchor_refs.into_iter().flatten().filter_map(|&(s, a)| (s == si).then_some(a)).collect(); + let gone: BTreeSet = anchor_refs.into_iter().flat_map(|refs| super::path::subpath_refs(refs, si)).collect(); subpaths.extend(super::path::without_anchors(sp, &gone)); } } diff --git a/crates/engine/src/cmd/fileio/batch.rs b/crates/engine/src/cmd/fileio/batch.rs index 18bc78b5d9..0974934ded 100644 --- a/crates/engine/src/cmd/fileio/batch.rs +++ b/crates/engine/src/cmd/fileio/batch.rs @@ -41,6 +41,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { roll_back(s, start, &stash); s.notify_text_tool("batch.rollBack"); s.active = active; + s.sync_front_profiles(); (s.paint, s.fill_active, s.draw_mode, s.draw_inside, s.clipboard, s.untitled_counter, s.explicit_undo_group) = saved; s.pending_paint = None; return Err(e); @@ -78,8 +79,11 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { /// `artboard`, as the Artboards panel shows it in the document the step runs in: past that /// document's last artboard, the last one; a Paste in Place, in Front or in Back step that names /// `artboards` keeps them, and one that names neither, while the Artboard tool is chosen with -/// several artboards selected, pastes on those. A step that resizes the active artboard -/// ([`crate::FIT_ACTIVE_ARTBOARD`]) and names no `index` gets that artboard as its `index`. +/// several artboards selected, pastes on those. A Fit to Artwork Bounds step that names neither +/// `index` nor `indices`, while the Artboard tool is chosen with several artboards selected when the +/// step runs, gets those as its `indices`, which its journal entry records. Otherwise a step that +/// resizes the active artboard ([`crate::FIT_ACTIVE_ARTBOARD`]) and names no `index` (nor +/// `indices`, for Fit to Artwork Bounds) gets that artboard as its `index`. /// `grouped` gets each step's undo groups, as [`Session::batch_steps`] keeps them. fn run_steps( s: &mut Session, @@ -110,9 +114,22 @@ fn run_steps( // Artboard tool is chosen with several artboards selected, pastes on those. let names_artboards = id.starts_with("edit.pasteIn") && (params.get("artboards").is_some() || (params.get("artboard").is_none() && !crate::cmd::edit::artboard_tool_picks(s).is_empty())); + // A Fit to Artwork Bounds step that names neither `index` nor `indices`, while the Artboard + // tool is chosen with several artboards selected, fits those, as the command does on its own. + let fit_picks = if id == "artboard.fitToArt" && params.get("index").is_none() && params.get("indices").is_none() { + crate::cmd::edit::artboard_tool_picks(s) + } else { + Vec::new() + }; + if !fit_picks.is_empty() + && let Some(o) = params.as_object_mut() + { + o.insert("indices".into(), json!(fit_picks)); + } if let Some(a) = artboard && let Some(key) = key && params.get(key).is_none() + && !(id == "artboard.fitToArt" && params.get("indices").is_some()) && !names_artboards && let Some(last) = s.active().and_then(|d| d.doc.artboards.len().checked_sub(1)) && let Some(o) = params.as_object_mut() @@ -129,8 +146,9 @@ fn run_steps( } grouped.push(step_groups(s, start, &held)); // The step's journal entry records what it took from the preferences or the clock (a - // save's date, a new document's), as a command of its own would. - if noted != params + // save's date, a new document's), as a command of its own would, and the artboards a Fit to + // Artwork Bounds step took from the Artboard tool. + if (noted != params || !fit_picks.is_empty()) && let Some(c) = c.as_object_mut() { c.insert("params".into(), noted); diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 96d6187b82..e867fdee41 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Export Document", [], None, - "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the visible art), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Never changes the document's path", + "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the visible art), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Never changes the document's path", has_doc, export::export ), @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Batch", [], None, - "{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included", + "{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer; an artboard.fitToArt step that names neither index nor indices, while the Artboard tool is chosen with several artboards selected when the step runs, gets those as indices instead, and the journal records them)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included", has_doc, batch::batch ), diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 31539ff51d..0fbffcea82 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -629,6 +629,13 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result { { return Ok(Encoded::one_with_notes(bytes, notes)); } + // So does a `.ai` file of the art's bounds (a legacy version 7 `.ai` file has none to leave out). + if use_artboards == Some(false) + && f.id == "ai" + && let Some(enc) = super::save::encode_ai_art_page(C, f, doc, p)? + { + return Ok(enc); + } if use_artboards == Some(false) && let Some((art, q)) = art_page(C, doc, p)? { diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index e9f6ecf3d4..4df490af13 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -868,7 +868,7 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option { /// A TIFF with more strips or tiles than the decoder can count /// ([`vectorcraft_doc::cmyk::oversized_tiff`]) is refused as too large to draw. JPEG XL images are /// read with [`jxlread`] and stored as PNG, with the ICC profile their colors are left in. -/// A PNG, JPEG, GIF, WebP or TIFF whose orientation ([`exif_orientation`]) turns or flips it is +/// A PNG, JPEG, GIF, WebP or TIFF whose orientation ([`vectorcraft_doc::cmyk::exif_orientation`]) turns or flips it is /// stored as it is shown, with its resolution's axes swapped when it turns a quarter; a CMYK JPEG /// or TIFF keeps its inks, 8 bits each, as a CMYK TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]). pub fn raster_image(bytes: &[u8]) -> Result { @@ -909,7 +909,7 @@ pub fn raster_image(bytes: &[u8]) -> Result { let f = image_format(kind).ok_or_else(|| err(format!("{kind:?} images can't be opened (see document.formats)")))?; // A photo whose EXIF orientation turns or flips it (a camera held upright) is stored as it is // seen, so it places the way it was taken (#4284); the others keep their own bytes. - let orientation = matches!(f.id, "png" | "jpg" | "gif" | "webp" | "tiff").then(|| exif_orientation(bytes)).flatten(); + let orientation = matches!(f.id, "png" | "jpg" | "gif" | "webp" | "tiff").then(|| vectorcraft_doc::cmyk::exif_orientation(bytes)).flatten(); let turned = orientation.is_some(); // The resolution describes the stored pixels; a quarter turn swaps its axes. let quarter = orientation.is_some_and(|o| o.to_exif() >= 5); @@ -957,18 +957,6 @@ pub fn raster_image(bytes: &[u8]) -> Result { as_png(img, None, shown_ppi) } -/// The EXIF orientation of encoded image `bytes` when it turns or flips the pixels; `None` when -/// it leaves them as stored, or the image has none. A TIFF the image decoder can't open (one with -/// extra samples) has its Orientation tag read from its first image -/// ([`vectorcraft_doc::cmyk::tiff_orientation`]). -pub(crate) fn exif_orientation(bytes: &[u8]) -> Option { - use image::ImageDecoder as _; - use image::metadata::Orientation; - let decoded = || image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_decoder().ok()?.orientation().ok(); - let tagged = || vectorcraft_doc::cmyk::tiff_orientation(bytes).and_then(|v| Orientation::from_exif(u8::try_from(v).ok()?)); - decoded().or_else(tagged).filter(|o| *o != Orientation::NoTransforms) -} - /// `img` stored as a PNG that keeps the file's resolution and carries `icc`, the ICC profile its /// colors are in. pub(super) fn as_png(img: image::RgbaImage, icc: Option>, ppi: Option<(f64, f64)>) -> Result { diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index f8e2a9a19f..bcbd9cea20 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -691,6 +691,31 @@ struct AiEditingData { editing_data: Option, } +/// Why a `.ai` file of the art's bounds (`useArtboards: false`) carries no editing data. +pub const AI_EDITING_NEEDS_THE_ARTBOARDS: &str = + "Preserve editing was left out: an .ai file of the art's bounds would replace the document's artboards when reopened"; + +/// The error for a `.ai` file of the art's bounds without PDF content. +pub const ART_PAGE_NEEDS_PDF: &str = "pdfCompatible: false needs the artboards to keep the editable artwork when useArtboards is false"; + +/// With `useArtboards: false` in `p`: the PDF-compatible `.ai` file of one page, the bounds of +/// `doc`'s visible art ([`super::encode::art_page`]). It carries neither the native document nor +/// the editing copy for other apps, and its notes end with [`AI_EDITING_NEEDS_THE_ARTBOARDS`]. +/// `pdfCompatible: false` is refused. `None` when `p` asks for the artboards or for a legacy +/// version 7 `.ai` file. +pub(super) fn encode_ai_art_page(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result> { + if super::encode::use_artboards(cmd, p)? != Some(false) || super::legacy_ai::wanted(cmd, f, p)? { + return Ok(None); + } + if !bool_or(p, "pdfCompatible", true) { + return Err(bad(cmd, ART_PAGE_NEEDS_PDF)); + } + let Some((art, q)) = super::encode::art_page(cmd, doc, p)? else { return Ok(None) }; + let mut enc = encode_ai_pages(cmd, f, &art, &q, false)?; + enc.setting_notes.push(AI_EDITING_NEEDS_THE_ARTBOARDS.to_string()); + Ok(Some(enc)) +} + /// The shared Save and Export encoder for `.ai` files (and `.ait` templates, the same file): /// PDF-compatible by default, without PDF content (`pdfCompatible: false`), or legacy version 7 /// `.ai` files (`aiVersion: "7"`). @@ -698,9 +723,15 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res if super::legacy_ai::wanted(cmd, f, p)? { return super::legacy_ai::encode(cmd, f, doc, p); } + encode_ai_pages(cmd, f, doc, p, true) +} + +/// [`encode_ai`] of a `.ai` file with or without PDF content, carrying the native document and +/// the editing copy for other apps when `editing` is true, and neither otherwise. +fn encode_ai_pages(cmd: &str, f: &Format, doc: &Document, p: &Value, editing: bool) -> Result { let mut params = if p.is_object() { p.clone() } else { json!({}) }; if let Some(o) = params.as_object_mut() { - o.insert("preserveEditing".into(), json!(true)); + o.insert("preserveEditing".into(), json!(editing)); // Keep upstream AI PDF layers, including hidden layers, unless a standard decides. if o.get("standard").is_none_or(Value::is_null) { o.entry("createLayers").or_insert(json!(true)); diff --git a/crates/engine/src/cmd/fileio/tests_pdfedit.rs b/crates/engine/src/cmd/fileio/tests_pdfedit.rs index 2970238e38..0b560e5e04 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfedit.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfedit.rs @@ -402,28 +402,75 @@ fn ai_export_validates_options_even_when_editing_data_is_omitted() { } } -#[test] -fn ai_export_without_artboards_keeps_art_outside_the_original_pages() { +/// Two artboards, a visible 30 × 20 pt rectangle outside them at (180, 100) and a hidden one. +fn art_outside_the_artboards() -> Session { let mut s = Session::new(); s.execute("file.new", &json!({"width": 100, "height": 80, "artboards": 2})).unwrap(); s.execute("paint.setStroke", &json!({"none": true})).unwrap(); s.execute("shape.rectangle", &json!({"x": 180, "y": 100, "width": 30, "height": 20})).unwrap(); s.execute("shape.rectangle", &json!({"x": 1000, "y": 1000, "width": 50, "height": 40})).unwrap(); s.execute("object.hide", &json!({})).unwrap(); + s +} + +/// Whether the `.ai` file `bytes` carries the editing copy of its art for other apps. +fn carries_private_data(bytes: &[u8]) -> bool { + let opts = LoadOptions { native: false, ..Default::default() }; + load::load_with("a.ai", bytes, &opts).unwrap().editing_data +} + +#[test] +fn an_ai_of_the_arts_bounds_carries_no_editing_data() { + let mut s = art_outside_the_artboards(); let before = comparable(&s.doc().unwrap().doc); - let r = s.execute("document.export", &json!({"format": "ai", "useArtboards": false, "range": "2"})).unwrap(); - let bytes = b64(&r); - let pages = vectorcraft_pdf::import(&bytes).unwrap(); - assert_eq!(pages.artboards.len(), 1); - assert_eq!((pages.artboards[0].rect.width(), pages.artboards[0].rect.height()), (30.0, 20.0)); - let editing = vectorcraft_pdf::editing(&bytes).unwrap(); - let exported = vectorcraft_format::load(&editing.data).unwrap(); - assert_eq!(exported.artboards.len(), 1); - assert_eq!(exported.artboards[0].rect, vectorcraft_geom::Rect::new(180.0, 100.0, 210.0, 120.0)); - assert_eq!(comparable(&s.doc().unwrap().doc), before); + let left_out = |v: &Value| v["warnings"].as_array().unwrap().iter().any(|w| w == super::save::AI_EDITING_NEEDS_THE_ARTBOARDS); + let path = tmp("art-bounds.ai"); + for extra in [json!({}), json!({"range": "2"}), json!({"editingData": false}), json!({"path": path})] { + let mut params = json!({"format": "ai", "useArtboards": false}); + params.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + let r = s.execute("document.export", ¶ms).unwrap(); + let bytes = if params.get("path").is_some() { std::fs::read(&path).unwrap() } else { b64(&r) }; + // One page, the visible art's bounds, whatever range names. + let pages = vectorcraft_pdf::import(&bytes).unwrap(); + assert_eq!(pages.artboards.len(), 1, "{params}"); + assert_eq!((pages.artboards[0].rect.width(), pages.artboards[0].rect.height()), (30.0, 20.0), "{params}"); + assert!(vectorcraft_pdf::editing(&bytes).is_none(), "{params}"); + assert!(!carries_private_data(&bytes), "{params}"); + assert!(left_out(&r), "{params}: {r}"); + assert_eq!(comparable(&s.doc().unwrap().doc), before); + } + // The artboards keep both editing copies, without the warning. + for params in [json!({"format": "ai"}), json!({"format": "ai", "useArtboards": true})] { + let r = s.execute("document.export", ¶ms).unwrap(); + let bytes = b64(&r); + let editing = vectorcraft_pdf::editing(&bytes).expect("editing data"); + assert_eq!(vectorcraft_format::load(&editing.data).unwrap().artboards.len(), 2, "{params}"); + assert!(carries_private_data(&bytes), "{params}"); + assert!(!left_out(&r), "{params}: {r}"); + } assert!(s.execute("document.export", &json!({"format": "ai", "useArtboards": "yes"})).is_err()); } +#[test] +fn an_ai_of_the_arts_bounds_without_pdf_is_refused() { + let mut s = art_outside_the_artboards(); + let before = comparable(&s.doc().unwrap().doc); + for extra in [json!({}), json!({"editingData": false}), json!({"editingData": true})] { + for command in ["document.export", "document.serialize"] { + let mut params = json!({"format": "ai", "useArtboards": false, "pdfCompatible": false}); + params.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + let e = s.execute(command, ¶ms).unwrap_err().to_string(); + assert!(e.contains(super::save::ART_PAGE_NEEDS_PDF), "{command} {params}: {e}"); + assert_eq!(comparable(&s.doc().unwrap().doc), before); + } + } + // A document with no visible art is still refused for that. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 80})).unwrap(); + let e = s.execute("document.export", &json!({"format": "ai", "useArtboards": false})).unwrap_err().to_string(); + assert!(e.contains("no visible art"), "{e}"); +} + /// Color Halftone's Max Radius is in pixels of the raster effects resolution since document /// version 3 (#3260). A PDF saved with Preserve Editing carries the native document, so one from /// before that opens with the radius converted, drawing the same dots; one saved since opens as diff --git a/crates/engine/src/cmd/flatten/analysis.rs b/crates/engine/src/cmd/flatten/analysis.rs index 4ad89c773b..0adb06132a 100644 --- a/crates/engine/src/cmd/flatten/analysis.rs +++ b/crates/engine/src/cmd/flatten/analysis.rs @@ -135,6 +135,9 @@ fn touch(a: &Rect, b: &Rect) -> bool { struct Sets { parent: Vec, seeded: Vec, + /// How many open boxes the sweep's boxes met. + #[cfg(test)] + meets: usize, } impl Sets { @@ -180,17 +183,25 @@ impl Sets { /// tops that knows the lowest bottom below each of its branches, so each box meets only the open /// boxes it overlaps, not every open one (many objects stacked in a column, sharing their /// horizontal extent, would otherwise compare every pair). An open box inside a later box of -/// its group, ending no further right, is closed early: whatever overlaps it overlaps that box. -/// Fails only when cancelled ([`vectorcraft_doc::cancel`]). +/// its group, ending no further right, is closed early, and a box inside an open box of its group, +/// ending no further right, isn't opened: whatever overlaps it overlaps that box. Fails only when +/// cancelled ([`vectorcraft_doc::cancel`]). pub(super) fn overlapping(bounds: &[Option]) -> Result>, Cancelled> { Ok(sweep(bounds, None)?.groups()) } /// [`overlapping`]'s sweep. With `see_through`, two boxes are joined only when one of them is -/// see-through, and an open box is closed early only inside a later see-through box. +/// see-through, and an open box is closed early, or a box isn't opened, only inside a see-through +/// box. The open +/// see-through boxes and the open boxes without transparency are then in trees of their own, and +/// a box without transparency meets only the see-through ones. fn sweep(bounds: &[Option], see_through: Option<&[bool]>) -> Result { - let mut sets = Sets { parent: (0..bounds.len()).collect(), seeded: (0..bounds.len()).map(|i| see_through.is_some_and(|s| s[i])).collect() }; - let joins = |a: usize, b: usize| see_through.is_none_or(|s| s[a] || s[b]); + let mut sets = Sets { + parent: (0..bounds.len()).collect(), + seeded: (0..bounds.len()).map(|i| see_through.is_some_and(|s| s[i])).collect(), + #[cfg(test)] + meets: 0, + }; let boxes: Vec<(usize, Rect)> = bounds.iter().enumerate().filter_map(|(i, b)| b.filter(finite).map(|b| (i, b))).collect(); let n = boxes.len(); // Each box's place in the tree: by top (then index). @@ -201,9 +212,11 @@ fn sweep(bounds: &[Option], see_through: Option<&[bool]>) -> Result], see_through: Option<&[bool]>) -> Result &[0], + Some(_) if shadows => &[0, 1], + Some(_) => &[1], + }; let below = tops.partition_point(|t| *t <= b.y1); met.clear(); - stack.clear(); - stack.push((1, 0, size)); - while let Some((node, lo, hi)) = stack.pop() { - work += 1; - if work.is_multiple_of(4096) { - vectorcraft_doc::cancel::check()?; + for &t in looks { + stack.clear(); + stack.push((1, 0, size)); + while let Some((node, lo, hi)) = stack.pop() { + work += 1; + if work.is_multiple_of(4096) { + vectorcraft_doc::cancel::check()?; + } + if lo >= below || low[t][node] < b.y0 { + continue; + } + if hi - lo == 1 { + met.push(by_top[lo]); + continue; + } + let mid = (lo + hi) / 2; + stack.push((2 * node + 1, mid, hi)); + stack.push((2 * node, lo, mid)); } - if lo >= below || low[node] < b.y0 { - continue; - } - if hi - lo == 1 { - met.push(by_top[lo]); - continue; - } - let mid = (lo + hi) / 2; - stack.push((2 * node + 1, mid, hi)); - stack.push((2 * node, lo, mid)); } + #[cfg(test)] + { + sets.meets += met.len(); + } + // An open box it met that holds it, ending no further right, and that joins whatever it + // overlaps: whatever later overlaps this box overlaps that one and joins it, so this box + // isn't opened. + let holder = met.iter().copied().find(|&o| { + let ob = boxes[o].1; + see_through.is_none_or(|s| s[boxes[o].0]) && b.x1 <= ob.x1 && ob.y0 <= b.y0 && b.y1 <= ob.y1 + }); // Whatever overlaps a box inside this one overlaps this one, and joins it when this one is // see-through. - let shadows = see_through.is_none_or(|s| s[boxes[k].0]); for &o in &met { - if joins(boxes[k].0, boxes[o].0) { - sets.join(boxes[k].0, boxes[o].0); - } + sets.join(boxes[k].0, boxes[o].0); let ob = boxes[o].1; - if shadows && ob.x1 <= b.x1 && b.y0 <= ob.y0 && ob.y1 <= b.y1 { - set(&mut low, leaf[o], f64::NEG_INFINITY); + if shadows && Some(o) != holder && ob.x1 <= b.x1 && b.y0 <= ob.y0 && ob.y1 <= b.y1 { + set(&mut low[tree(o)], leaf[o], f64::NEG_INFINITY); } } - set(&mut low, leaf[k], b.y1); + if holder.is_none() { + set(&mut low[tree(k)], leaf[k], b.y1); + } } Ok(sets) } @@ -392,6 +425,11 @@ mod tests { /// What [`overlapping`] gives, comparing every pair. fn every_pair(bounds: &[Option]) -> Vec> { + every_pair_joining(bounds, |_, _| true) + } + + /// The groups of `bounds` comparing every pair, joining overlapping pairs that `joins`. + fn every_pair_joining(bounds: &[Option], joins: impl Fn(usize, usize) -> bool) -> Vec> { let n = bounds.len(); let mut group: Vec = (0..n).collect(); let hit = |a: &Rect, b: &Rect| a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1; @@ -401,6 +439,7 @@ mod tests { for j in 0..n { if let (Some(a), Some(b)) = (bounds[i], bounds[j]) && hit(&a, &b) + && joins(i, j) && group[j] < group[i] { group[i] = group[j]; @@ -464,6 +503,69 @@ mod tests { assert_eq!(overlapping(&odd).unwrap(), vec![vec![0, 2], vec![1]]); } + /// `n` boxes sharing their left and top edges, each inside the one before. + fn shrinking_nest(n: usize) -> Vec> { + (0..n).map(|i| Some(Rect::new(0.0, 0.0, 2.0 * (n - i) as f64, 2.0 * (n - i) as f64))).collect() + } + + /// Each box of a nest that shrinks to the right and bottom meets only the outermost box, which + /// stays open and holds it, not every box around it. + #[test] + fn a_shrinking_nest_meets_only_its_outermost_box() { + let n = 512; + let bounds = shrinking_nest(n); + let mut sets = sweep(&bounds, None).unwrap(); + assert_eq!(sets.meets, n - 1); + assert_eq!(sets.groups(), every_pair(&bounds)); + assert_eq!(sets.groups(), vec![(0..n).collect::>()]); + // Equal boxes: the later one isn't opened and the earlier one stays open for the third. + let same = [Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(Rect::new(9.0, 9.0, 20.0, 20.0))]; + assert_eq!(overlapping(&same).unwrap(), vec![vec![0, 1, 2]]); + // With transparency, an opaque box isn't opened inside a see-through box, and boxes inside + // an opaque box are opened: an opaque box that overlaps only the inner one still joins it + // when that one is see-through. + let see = [true, false]; + let mut sets = sweep(&bounds[..2], Some(&see)).unwrap(); + assert_eq!(sets.groups(), vec![vec![0, 1]]); + let held = [Some(Rect::new(0.0, 0.0, 20.0, 20.0)), Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(Rect::new(5.0, 5.0, 8.0, 8.0))]; + let mut sets = sweep(&held, Some(&[false, true, false])).unwrap(); + assert_eq!(sets.groups(), vec![vec![0, 1, 2]]); + let mut sets = sweep(&held, Some(&[true, false, false])).unwrap(); + assert_eq!(sets.groups(), vec![vec![0, 1, 2]]); + let mut sets = sweep(&held, Some(&[false, false, true])).unwrap(); + assert_eq!(sets.groups(), vec![vec![0, 1, 2]]); + let mut sets = sweep(&held, Some(&[false, false, false])).unwrap(); + assert_eq!(sets.groups(), vec![vec![0], vec![1], vec![2]]); + } + + /// Boxes nested at shared corners and placed at random, some see-through, group with and + /// without transparency as comparing every pair groups them. + #[test] + fn nested_and_scattered_boxes_group_as_comparing_every_pair() { + let mut seed = 0x51_7cc1_b727_220au64; + let mut next = |m: f64| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % 1000) as f64 / 1000.0 * m + }; + for round in 0..40 { + let n = 6 + round * 3; + let bounds: Vec> = (0..n) + .map(|_| { + // Corners on a coarse grid so that edges are often shared and boxes often nest. + let (x, y) = ((next(6.0).floor()) * 10.0, (next(6.0).floor()) * 10.0); + let (w, h) = ((next(5.0).floor() + 1.0) * 10.0, (next(5.0).floor() + 1.0) * 10.0); + Some(Rect::new(x, y, x + w, y + h)) + }) + .collect(); + assert_eq!(overlapping(&bounds).unwrap(), every_pair(&bounds), "round {round}"); + let see: Vec = (0..n).map(|_| next(1.0) < 0.3).collect(); + let mut sets = sweep(&bounds, Some(&see)).unwrap(); + assert_eq!(sets.groups(), every_pair_joining(&bounds, |i, j| see[i] || see[j]), "round {round}, with transparency"); + } + } + /// A filled rectangle, unstroked. fn filled(id: u64, r: Rect) -> Node { let look = vectorcraft_doc::Appearance::basic( @@ -583,6 +685,62 @@ mod tests { assert_eq!(flatten_groups(&reach, &painted, &vec![false; n], 0.0).unwrap().len(), n); } + /// A small see-through box, then `n` opaque boxes nested around it, each inside the one + /// before and sharing its left and top edges. + fn nest_around_a_see_through_box(n: usize) -> (Vec>, Vec) { + let mut bounds = vec![Some(Rect::new(0.0, 0.0, 1.0, 1.0))]; + bounds.extend((0..n).map(|i| Some(Rect::new(0.0, 0.0, 2.0 * (n - i) as f64 + 1.0, 2.0 * (n - i) as f64 + 1.0)))); + let mut see = vec![false; n + 1]; + see[0] = true; + (bounds, see) + } + + /// Opaque boxes nested in each other around a see-through box each meet only the see-through + /// box, not the open opaque boxes they can't join, and all join it. + #[test] + fn nested_opaque_boxes_meet_only_the_see_through_box() { + let n = 512; + let (bounds, see) = nest_around_a_see_through_box(n); + let mut sets = sweep(&bounds, Some(&see)).unwrap(); + assert_eq!(sets.meets, n); + assert_eq!(sets.groups(), vec![(0..=n).collect::>()]); + // The unfiltered sweep that runs before it meets each box once too. + let mut sets = sweep(&bounds, None).unwrap(); + assert_eq!(sets.meets, n); + assert_eq!(sets.groups(), vec![(0..=n).collect::>()]); + let (painted, see) = nest_around_a_see_through_box(40); + let reach: Vec> = painted.iter().map(|b| b.map(|b| b.inflate(1.0, 1.0))).collect(); + for fringe in [0.0, 0.7] { + let groups = flatten_groups(&reach, &painted, &see, fringe).unwrap(); + check(&reach, &painted, &see, fringe, &groups, &format!("nest, fringe {fringe}")); + assert_eq!(groups, vec![(0..=40).collect::>()]); + } + } + + /// An opaque box inside a later see-through box is closed: later boxes meet the see-through + /// box instead, and join the opaque one through it. + #[test] + fn a_see_through_box_closes_an_opaque_box_inside_it() { + // An opaque box, a see-through box around it, a see-through box over both and an opaque + // box over the first. + let bounds = [ + Some(Rect::new(0.0, 0.0, 10.0, 10.0)), + Some(Rect::new(0.0, 0.0, 20.0, 20.0)), + Some(Rect::new(5.0, 5.0, 30.0, 30.0)), + Some(Rect::new(8.0, 8.0, 12.0, 12.0)), + ]; + let see = [false, true, true, false]; + let mut sets = sweep(&bounds, Some(&see)).unwrap(); + // The second box meets the first; the third meets the second; the fourth meets the second + // and the third. + assert_eq!(sets.meets, 4); + assert_eq!(sets.groups(), vec![vec![0, 1, 2, 3]]); + // Opaque boxes alone meet nothing. + let mut sets = sweep(&bounds, Some(&[false; 4])).unwrap(); + assert_eq!(sets.meets, 0); + assert_eq!(sets.groups().len(), 4); + } + /// An opaque box between a member and its group's top that paints over the member joins, and /// so on along a chain; one under the member stays, but for one within the fringe. #[test] diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index aef1918a6d..fcc2a593c1 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -1034,6 +1034,85 @@ fn an_opaque_pick_replaces_the_opacity_the_series_stores() { assert_eq!(spec(&s, id).series_paints[0].fill_opacity, None); } +/// A column graph whose series 0 stores the 40% Multiply fill set on its first mark, and a mark of series 1 whose top fill +/// row has no paint and is opaque and Normal: the session, the graph, series 0's marks and that source. +fn marks_and_unpainted_source() -> (Session, NodeId, Vec, NodeId) { + let (mut s, id, _, marks) = column_marks(); + let source = series(s.doc().unwrap().doc.node(id).unwrap(), 1).children().unwrap()[0].id; + s.execute("appearance.setItem", &json!({"ids": [source.0], "index": top_row(&s, source, true), "none": true})).unwrap(); + let fill = top_row(&s, marks[0], true); + s.execute("appearance.setItem", &json!({"ids": [marks[0].0], "index": fill, "opacity": 40, "blend": "multiply"})).unwrap(); + let kept = spec(&s, id).series_paints[0].clone(); + assert_eq!((kept.fill_opacity, kept.fill_blend), (Some(0.4), Some(BlendMode::Multiply))); + (s, id, marks, source) +} + +/// An Eyedropper pick from a fill row without paint onto a mark whose fill had paint replaces the fill opacity and blend +/// mode another mark of the series stored: the series is drawn opaque and Normal again. +#[test] +fn an_eyedropper_pick_that_unpaints_a_series_fill_clears_its_stored_transparency() { + let (mut s, id, marks, source) = marks_and_unpainted_source(); + let mark = s.doc().unwrap().doc.node(marks[1]).unwrap().appearance.fill().unwrap().clone(); + assert_eq!((mark.paint.is_none(), mark.opacity, mark.blend), (false, 1.0, BlendMode::Normal), "the target's fill row"); + s.execute("appearance.copyFrom", &json!({"source": source.0, "ids": [marks[1].0]})).unwrap(); + let picked = s.doc().unwrap().doc.node(marks[1]).unwrap().appearance.fill().unwrap().clone(); + assert_eq!((picked.paint.is_none(), picked.opacity, picked.blend), (true, 1.0, BlendMode::Normal)); + let kept = spec(&s, id).series_paints[0].clone(); + assert_eq!((kept.fill_opacity, kept.fill_blend), (None, None)); + s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let fills: Vec<_> = series(&n, 0).children().unwrap().iter().filter_map(|m| m.appearance.fill().map(|f| (f.opacity, f.blend))).collect(); + assert!(fills.iter().all(|f| *f == (1.0, BlendMode::Normal)), "{fills:?}"); +} + +/// An Eyedropper pick from a fill row without paint onto a mark whose fill had no paint before the pick either leaves the +/// fill opacity and blend mode another mark of the series stored. +#[test] +fn an_eyedropper_pick_of_an_already_unpainted_row_leaves_series_transparency() { + let (mut s, id, marks, source) = marks_and_unpainted_source(); + s.execute("appearance.setItem", &json!({"ids": [marks[1].0], "index": top_row(&s, marks[1], true), "none": true})).unwrap(); + let kept = spec(&s, id).series_paints[0].clone(); + assert_eq!((kept.fill_opacity, kept.fill_blend), (Some(0.4), Some(BlendMode::Multiply)), "a color set to None writes no opacity"); + s.execute("appearance.copyFrom", &json!({"source": source.0, "ids": [marks[1].0]})).unwrap(); + let kept = spec(&s, id).series_paints[0].clone(); + assert_eq!((kept.fill_opacity, kept.fill_blend), (Some(0.4), Some(BlendMode::Multiply))); +} + +/// A whole Eyedropper pick from a source with no fill row, or no stroke row, removes that row from the mark. Where the +/// mark's row had paint, the pick replaces the opacity and blend mode another mark of the series stored for that kind +/// of row. Where the mark's row had no paint, the stored values stay. +#[test] +fn a_whole_eyedropper_pick_that_removes_a_painted_row_clears_its_stored_transparency() { + let stored = |s: &Session, id: NodeId, fill: bool| { + let kept = spec(s, id).series_paints[0].clone(); + if fill { (kept.fill_opacity, kept.fill_blend) } else { (kept.stroke_opacity, kept.stroke_blend) } + }; + for (fill, painted) in [(true, true), (false, true), (false, false)] { + let (mut s, id, _, marks) = column_marks(); + let row = top_row(&s, marks[0], fill); + if painted { + s.execute("appearance.setItem", &json!({"ids": [marks[1].0], "index": row, "color": "#ff0000"})).unwrap(); + } + s.execute("appearance.setItem", &json!({"ids": [marks[0].0], "index": row, "color": "#ff0000", "opacity": 40, "blend": "multiply"})).unwrap(); + assert_eq!(stored(&s, id, fill), (Some(0.4), Some(BlendMode::Multiply)), "fill {fill}, painted {painted}"); + let source = series(s.doc().unwrap().doc.node(id).unwrap(), 1).children().unwrap()[0].id; + s.execute("appearance.removeItem", &json!({"ids": [source.0], "index": top_row(&s, source, fill)})).unwrap(); + let was = spec(&s, id).series_paints; + s.execute("appearance.copyFrom", &json!({"source": source.0, "ids": [marks[1].0]})).unwrap(); + let mark = s.doc().unwrap().doc.node(marks[1]).unwrap().clone(); + assert!(!mark.appearance.items.iter().any(|it| it.is_fill() == fill), "the pick removed the row: fill {fill}"); + let want = if painted { (None, None) } else { (Some(0.4), Some(BlendMode::Multiply)) }; + assert_eq!(stored(&s, id, fill), want, "fill {fill}, painted {painted}"); + if painted { + let after = spec(&s, id).series_paints; + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(spec(&s, id).series_paints, was); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(spec(&s, id).series_paints, after); + } + } +} + /// An appearance moved between two marks of one series leaves the series with the target's paint, not the source's /// empty one, and the series still shows when the graph is drawn again. #[test] @@ -1251,6 +1330,45 @@ fn a_style_that_removes_a_marks_stroke_replaces_the_kept_stroke_opacity() { } } +/// An Eyedropper pick from a stroke row without paint onto a marker whose stroke had paint replaces the stroke opacity and +/// blend mode the series' Filled Lines band left, in the pick's undo step: the band's outline is drawn opaque and Normal +/// again. A pick onto a marker whose stroke had no paint before the pick leaves them as they are. +#[test] +fn an_eyedropper_pick_that_unpaints_a_series_stroke_clears_its_stored_transparency() { + for stroked in [true, false] { + let (mut s, id, band) = band_graph(); + let parts = series_parts(&s, id, 0); + let (marker, source) = (parts[1].id, parts[2].id); + let st = parts[2].appearance.stroke().unwrap(); + assert_eq!((st.paint.is_none(), st.opacity, st.blend), (true, 1.0, BlendMode::Normal), "the source's stroke row"); + if stroked { + let row = top_row(&s, marker, false); + s.execute("appearance.setItem", &json!({"ids": [marker.0], "index": row, "color": "#ff0000"})).unwrap(); + } + let row = top_row(&s, band, false); + s.execute("appearance.setItem", &json!({"ids": [band.0], "index": row, "opacity": 40, "blend": "multiply"})).unwrap(); + let was = spec(&s, id).series_paints; + assert_eq!((was[0].stroke_opacity, was[0].stroke_blend), (Some(0.4), Some(BlendMode::Multiply))); + s.execute("appearance.copyFrom", &json!({"source": source.0, "ids": [marker.0]})).unwrap(); + let picked = s.doc().unwrap().doc.node(marker).unwrap().appearance.stroke().unwrap().clone(); + assert_eq!((picked.paint.is_none(), picked.opacity, picked.blend), (true, 1.0, BlendMode::Normal), "stroked {stroked}"); + let kept = spec(&s, id).series_paints[0].clone(); + let want = if stroked { (None, None) } else { (Some(0.4), Some(BlendMode::Multiply)) }; + assert_eq!((kept.stroke_opacity, kept.stroke_blend), want, "stroked {stroked}"); + if stroked { + let after = spec(&s, id).series_paints; + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(spec(&s, id).series_paints, was); + assert!(!s.doc().unwrap().doc.node(marker).unwrap().appearance.stroke_paint().is_none(), "the undo took back the pick"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(spec(&s, id).series_paints, after); + } + redrawn_band(&mut s, id); + let st = series_parts(&s, id, 0)[0].appearance.stroke().unwrap().clone(); + assert_eq!((Some(st.opacity).filter(|o| *o < 1.0), Some(st.blend).filter(|b| *b != BlendMode::Normal)), want, "stroked {stroked}"); + } +} + /// A Filled Lines band's stroke row removed with the Appearance panel or set to None with `paint.setStroke` leaves the /// band its color: an empty stored stroke is not a color for the band. #[test] diff --git a/crates/engine/src/cmd/linkfiles.rs b/crates/engine/src/cmd/linkfiles.rs index f2ce9d4d12..99295e5c79 100644 --- a/crates/engine/src/cmd/linkfiles.rs +++ b/crates/engine/src/cmd/linkfiles.rs @@ -13,7 +13,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::NodeKind; use super::findfiles::{self, Limits, Visitor}; -use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, bool_or, checked_ids_param, cmd}; +use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, bool_or, cmd, ids_param}; /// The most linked files one search looks for. const MAX_LINKS: usize = 1_000; @@ -143,8 +143,14 @@ fn find(s: &mut Session, p: &Value) -> Result { let ids = match p.get("ids") { None | Some(Value::Null) => None, Some(_) => { - let ids = checked_ids_param(s, p, "ids", C)?; - let linkable = |id: &NodeId| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_) | NodeKind::PlacedDocument(_))); + // Images and placed documents in opacity-mask art and in the art of symbols, graph + // designs and patterns are named by their ids too (`links.list`). + let ids = ids_param(p, "ids", C)?.unwrap_or_default(); + let kind = |id: &NodeId| st.doc.stored_node(*id).map(|(n, _)| &n.kind); + if let Some(value) = ids.iter().find(|id| kind(id).is_none()).map(|id| id.0) { + return Err(bad(C, format!("no such object id {value}"))); + } + let linkable = |id: &NodeId| matches!(kind(id), Some(NodeKind::Image(_) | NodeKind::PlacedDocument(_))); if let Some(id) = ids.iter().find(|id| !linkable(id)) { return Err(bad(C, format!("object {} is not an image or a linked file", id.0))); } diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index e3e72861b9..d9c2ccf3ad 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -30,6 +30,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::links::{Align, Preserve, hash_bytes}; use vectorcraft_doc::{ Appearance, DataValue, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, PlacedDocument, PlacementOptions, + StoredPlace, StoredRoot, }; use vectorcraft_geom::{Affine, FillRule, PathData, Rect, shapes}; @@ -43,7 +44,7 @@ pub fn specs() -> Vec { "Check Links", [], None, - "{ids?: [image or placed document ids] (default: every linked image and placed document)} where each linked file is and whether it changed since it was read → {links: [{name, path?, status: ok|modified|missing, ids, found?: path (found away from its path: relative to the document, or by name in its folder), preview: true (showing the low-resolution preview, not the file), refused?: why the path is not followed (another computer, a device or a URL: it counts as missing)}], missing, modified}; under automation read roots, path and found are left out when the file they name is outside the roots", + "{ids?: [image or placed document ids] (default: every linked image and placed document, in the layers and in opacity-mask art, symbols, graph designs and patterns)} where each linked file is and whether it changed since it was read → {links: [{name, path?, status: ok|modified|missing, ids, found?: path (found away from its path: relative to the document, or by name in its folder), preview: true (showing the low-resolution preview, not the file), refused?: why the path is not followed (another computer, a device or a URL: it counts as missing)}], missing, modified}; under automation read roots, path and found are left out when the file they name is outside the roots", has_doc, check ), @@ -52,7 +53,7 @@ pub fn specs() -> Vec { "Update Links", [], None, - "{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. The images and placed documents inside symbols, graph designs, patterns and opacity masks that show the same content are read again too (by default also those only that art shows); they have no ids to list. One undo step → {updated: [ids], missing: [ids], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns]}", + "{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. Images and placed documents inside symbols, graph designs, patterns and opacity masks have ids of their own, as links.list gives them; those that show the same content as one read again are read again too. One undo step → {updated: [ids], missing: [ids], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns]}", has_doc, update ), @@ -70,7 +71,7 @@ pub fn specs() -> Vec { "Relink", [], None, - "{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object in the layers linked to the same file as one of them) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's)}", + "{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object linked to the same file as one of them, in the layers, opacity-mask art, symbols, graph designs and patterns) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's)}", has_doc, relink ), @@ -79,7 +80,7 @@ pub fn specs() -> Vec { "Links", [], None, - "{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first, dcsTransparency?: false (Show DCS Transparency Interactions: mark the images placed from DCS files that are transparent, themselves or a group or layer holding them, or that overlap a visible object with its own transparency; it looks at every object, so it takes longer)} every image object and placed document in the layers, as the Links panel lists them → {links: [{id, name, linked, status: ok|modified|missing|embedded, format (DCS for an image placed from a DCS file), pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels), dcsTransparency?: true (with dcsTransparency)}], missing, modified, embedded}; under automation read roots, path and found are left out when the file they name is outside the roots", + "{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first, dcsTransparency?: false (Show DCS Transparency Interactions: mark the images placed from DCS files that are transparent, themselves or a group or layer holding them, or that overlap a visible object with its own transparency; it looks at every object, so it takes longer)} every image object and placed document the document stores, as the Links panel lists them: those in the layers, then those in opacity-mask art and in the art of symbols, graph designs and patterns (one row per stored object, never one per symbol instance or pattern tile) → {links: [{id, name, linked, status: ok|modified|missing|embedded, format (DCS for an image placed from a DCS file), pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels), dcsTransparency?: true (with dcsTransparency), owner?: {kind: layers|symbol|graphDesign|pattern, name? (of the symbol, graph design or pattern), maskOf?: id (in the opacity-mask art of that object)} (an object outside the layer tree)}], missing, modified, embedded}; under automation read roots, path and found are left out when the file they name is outside the roots", has_doc, list ), @@ -88,7 +89,7 @@ pub fn specs() -> Vec { "Go To Link", [], None, - "{id?} select image or placed document `id` (default: the first selected one); the Links panel scrolls it into view → {id, bounds: [x0, y0, x1, y1]}", + "{id?} select image or placed document `id` (default: the first selected one); the Links panel scrolls it into view → {id, bounds: [x0, y0, x1, y1], onCanvas: true}; one in opacity-mask art or in the art of a symbol, graph design or pattern has no place of its own on the canvas: the selection is cleared → {id, onCanvas: false, owner} (owner as links.list gives it)", has_doc, go_to ), @@ -156,7 +157,8 @@ impl Status { struct Group { link: LinkInfo, key: String, - /// The objects in the layers (images in symbols and patterns share the content, not an id). + /// The stored objects showing it: in the layers, in opacity-mask art and in the art of symbols, + /// graph designs and patterns ([`Document::visit_stored`]), each once. ids: Vec, /// Placed documents: what they show. document: Option, @@ -177,8 +179,9 @@ fn linked(n: &Node) -> Option<(&LinkInfo, &str, Option)> { } } -/// Every linked file of `d` with the ids of the objects showing it (for [`crate::link_watch`]): an -/// image placed from a DCS file has its plate files of their own too, beside its file. +/// Every linked file of `d` with the ids of the objects showing it, wherever they are stored (for +/// [`crate::link_watch`]): an image placed from a DCS file has its plate files of their own too, +/// beside its file. pub(crate) fn linked_groups(d: &Document) -> Vec<(String, Vec)> { let mut out = vec![]; for g in groups(d, None).into_iter().filter(|g| !g.ids.is_empty()) { @@ -190,8 +193,10 @@ pub(crate) fn linked_groups(d: &Document) -> Vec<(String, Vec)> { out } -/// The linked images and placed documents of `d` by file and content: those in the layers (only `ids` when -/// given), then, without `ids`, the ones only symbols and patterns show. +/// The linked images and placed documents of `d` by file and content, wherever they are stored +/// (only `ids` when given), in [`Document::visit_stored`] order. An object whose id an object +/// visited before it has (art being edited on a layer and its definition) counts once, by its +/// first place; without `ids` its content is still grouped. fn groups(d: &Document, ids: Option<&[NodeId]>) -> Vec { let mut out: Vec = vec![]; let mut index: BTreeMap<(String, String, bool), usize> = BTreeMap::new(); @@ -210,24 +215,48 @@ fn groups(d: &Document, ids: Option<&[NodeId]>) -> Vec { g.ids.push(id); } }; - d.walk(|n| { - if let Some((l, key, document)) = linked(n) - && wanted.as_ref().is_none_or(|ids| ids.contains(&n.id)) - { + let mut seen = std::collections::HashSet::new(); + d.visit_stored(|n, _| { + let Some((l, key, document)) = linked(n) else { return }; + // Id 0 names no object. + let first = n.id.0 != 0 && seen.insert(n.id); + if first && wanted.as_ref().is_none_or(|ids| ids.contains(&n.id)) { add(l, key, document, Some(n.id)); + } else if ids.is_none() { + add(l, key, document, None); } }); - if ids.is_none() { - d.visit_images(|_, im| { - if let Some(l) = &im.link { - add(l, &im.key, None, None); - } - }); - d.visit_placed(|_, p| add(&p.link, &p.key, Some((p.bounding, p.page_box)), None)); - } out } +/// Stored object `id` of `d` ([`Document::stored_node`]). +fn stored(d: &Document, id: NodeId) -> Option<&Node> { + d.stored_node(id).map(|(n, _)| &**n) +} + +/// Of `ids`, the objects of `d` outside the layer tree (where [`Document::node`] finds none). +fn nested_ids(d: &Document, ids: &[NodeId]) -> std::collections::HashSet { + ids.iter().copied().filter(|id| d.node(*id).is_none()).collect() +} + +/// `links.list`'s `owner` of an object stored at `place` of `d`, when it is not in the layer tree +/// itself: `{kind: layers|symbol|graphDesign|pattern, name?, maskOf?}`. +fn owner_json(d: &Document, place: StoredPlace) -> Option { + if place.in_layers() { + return None; + } + let mut owner = match place.root { + StoredRoot::Layer(_) => json!({ "kind": "layers" }), + StoredRoot::Symbol(i) => json!({ "kind": "symbol", "name": d.symbols.get(i).map(|s| s.name.as_str()) }), + StoredRoot::GraphDesign(i) => json!({ "kind": "graphDesign", "name": d.graph_designs.get(i).map(|g| g.name.as_str()) }), + StoredRoot::Pattern { pattern, .. } => json!({ "kind": "pattern", "name": d.patterns.get(pattern).map(|p| p.name.as_str()) }), + }; + if let Some(m) = place.mask_of { + owner["maskOf"] = json!(m.0); + } + Some(owner) +} + /// A linked file where it was found. struct Found { path: String, @@ -493,8 +522,8 @@ pub(crate) fn full_linked_images<'a>(d: &'a Document, base: LinkBase) -> (Cow<'a } /// The linked files of the open document `st` that `links.findFiles` looks for, each with the -/// objects in the layers that show it: the files of objects `ids` whatever their status, else the -/// files that can't be found. +/// stored objects that show it: the files of objects `ids` whatever their status, else the files +/// that can't be found. pub(crate) fn files_to_find(st: &crate::DocState, ids: Option<&[NodeId]>) -> Vec<(LinkInfo, Vec)> { groups(&st.doc, ids) .into_iter() @@ -708,7 +737,7 @@ fn clip_to( type Remake<'a> = dyn FnMut(&Node, Option<(&PathData, FillRule)>) -> (Node, ClipTo) + 'a; /// Remakes the linked objects outside the layer tree (in symbols, graph designs, patterns and -/// opacity masks, where [`Document::node`] finds no ids) that `pick` holds for. +/// opacity masks, where [`Document::node`] does not find them) that `pick` holds for. struct Nested<'a> { pick: &'a dyn Fn(&Node) -> bool, make: &'a mut Remake<'a>, @@ -854,10 +883,10 @@ impl Nested<'_> { } } -/// Placed documents `ids` show `src`, read from the file `link` points at, each placed as its -/// Placement Options say (`force`: as that Preserve choice says, whatever they say); with `also` -/// (a file's path and the content shown), so do the placed documents outside the layer tree that -/// show that content. +/// Placed documents `ids` (in the layers or outside them) show `src`, read from the file `link` +/// points at, each placed as its Placement Options say (`force`: as that Preserve choice says, +/// whatever they say); with `also` (a file's path and the content shown), so do the placed +/// documents outside the layer tree that show that content. fn install_document( d: &mut Document, ids: &[NodeId], @@ -872,8 +901,10 @@ fn install_document( let o = PlacementOptions { preserve: force.unwrap_or(p.placement.preserve), ..p.placement }; placed_xf(p.xf, (p.width, p.height), (1.0, 1.0), (w, h), (1.0, 1.0), o) }; - if let Some(also) = also { - let pick = |n: &Node| shows(n, also, true); + let nested = nested_ids(d, ids); + if also.is_some() || !nested.is_empty() { + let pick = + |n: &Node| matches!(n.kind, NodeKind::PlacedDocument(_)) && (nested.contains(&n.id) || also.is_some_and(|also| shows(n, also, true))); let mut make = |n: &Node, _: Option<(&PathData, FillRule)>| { let mut n = n.clone(); let mut clip = ClipTo::Keep; @@ -1037,26 +1068,39 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_ install(d, &[id], read, Some(Preserve::Bounds), None) } -/// Image objects `ids` show the file read for `link` (`img`), each placed as its Placement -/// Options say (`force`: as that Preserve choice says, whatever they say); with `also` (a file's -/// path and the content shown), so do the images outside the layer tree that show that content. +/// Image objects `ids` (in the layers or outside them) show the file read for `link` (`img`), each +/// placed as its Placement Options say (`force`: as that Preserve choice says, whatever they say); +/// with `also` (a file's path and the content shown), so do the images outside the layer tree that +/// show that content. fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Option, also: Option<(&str, &str)>) -> Result<()> { let new_pt = super::place::pt_per_px(img.ppi); let mut clips = vec![]; - if let Some(also) = also { - // Every image picked shows content `also.1`, so one resolution serves them all. - let old_pt = file_pt(d, also.1); - let pick = |n: &Node| shows(n, also, false); - // The clipping path the old content's DCS file drew it through. - let old_clip = d.images.get(also.1).and_then(ImageBlob::separated_clip); + let nested = nested_ids(d, ids); + if also.is_some() || !nested.is_empty() { + let pick = |n: &Node| matches!(n.kind, NodeKind::Image(_)) && (nested.contains(&n.id) || also.is_some_and(|also| shows(n, also, false))); + // The resolution of each content the images picked show, and the clipping path its DCS file + // drew it through, looked up once each. + let mut old: BTreeMap)> = BTreeMap::new(); + d.visit_stored(|n, _| { + if let NodeKind::Image(im) = &n.kind + && pick(n) + && !old.contains_key(&im.key) + { + old.insert(im.key.clone(), (file_pt(d, &im.key), d.images.get(&im.key).and_then(ImageBlob::separated_clip))); + } + }); let mut make = |n: &Node, held: Option<(&PathData, FillRule)>| { let mut n = n.clone(); let mut clip = ClipTo::Keep; if let NodeKind::Image(im) = &mut n.kind { let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement }; let size = |w: u32, h: u32| (w as f64, h as f64); + let (old_pt, old_clip) = match old.get(&im.key) { + Some((pt, clip)) => (*pt, clip.as_ref()), + None => (super::place::pt_per_px(None), None), + }; let (xf, c) = placed_xf(im.xf, size(im.width, im.height), old_pt, size(img.width, img.height), new_pt, o); - clip = clip_to(im.xf, old_clip.as_ref(), c, &img, xf, held); + clip = clip_to(im.xf, old_clip, c, &img, xf, held); (im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone())); } (n, clip) @@ -1267,7 +1311,7 @@ pub fn resolve(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_eps } } // The objects in symbols, graph designs, patterns and opacity masks that show the same file and - // content, which have no ids here, whatever else their links hold. + // content, whatever else their links hold, those whose id an earlier object has included. if !moved.is_empty() { let mut by_path: BTreeMap> = BTreeMap::new(); for (path, key, document, new) in moved { @@ -1302,13 +1346,25 @@ fn link_mut(n: &mut Node) -> Option<&mut LinkInfo> { } } -/// Linked image objects (or placed documents) `ids` link to `link`. +/// Linked image objects (or placed documents) `ids`, in the layers or outside them, link to `link`. fn set_links(d: &mut Document, ids: &[NodeId], link: &LinkInfo) { - for id in ids { + let nested = nested_ids(d, ids); + for id in ids.iter().filter(|id| !nested.contains(id)) { if let Some(l) = d.node_mut(*id).and_then(link_mut) { *l = link.clone(); } } + if !nested.is_empty() { + let pick = |n: &Node| nested.contains(&n.id) && linked(n).is_some(); + let mut make = |n: &Node, _: Option<(&PathData, FillRule)>| { + let mut out = n.clone(); + if let Some(l) = link_mut(&mut out) { + *l = link.clone(); + } + (out, ClipTo::Keep) + }; + Nested { pick: &pick, make: &mut make, next: 0 }.run(d); + } } /// Placed documents of the document saved at `path` (document `saved` of `s`) in the other open @@ -1331,14 +1387,17 @@ pub(crate) fn refresh_placed(s: &mut Session, saved: u64, path: &str) { if targets.is_empty() { return; } - // Each document is updated as the active one, without switching tools. + // Each document is updated as the active one, through its own profiles, without switching + // tools. let back = s.active; for i in targets { s.active = Some(i); + s.sync_front_profiles(); // A file that can't be read leaves what its objects show: links.check reports it. let _ = update_where(s, None, Some(&path)); } s.active = back; + s.sync_front_profiles(); } // ---------- relative paths ---------- @@ -1537,7 +1596,7 @@ fn update(s: &mut Session, p: &Value) -> Result { /// Update Links in the active document of `s` for objects `ids` (default: the linked files that /// changed or show their preview), or with `path`, for the placed documents of the file at `path` /// whatever their status. The objects in symbols, graph designs, patterns and opacity masks that -/// show the same content are read again too, and have no ids to report. +/// show the same content are read again too. fn update_where(s: &mut Session, ids: Option>, path: Option<&str>) -> Result { let st = s.doc()?; let (mut reads, mut missing) = (vec![], vec![]); @@ -1603,7 +1662,7 @@ enum Scope { Each, /// The objects given or selected. Selected, - /// Every object in the layers linked to the same file as one given or selected. + /// Every stored object linked to the same file as one given or selected. All, /// The objects given or selected, then every other missing link whose file name is in the new /// file's folder. @@ -1687,7 +1746,7 @@ fn relink(s: &mut Session, p: &Value) -> Result { }; // An image or a placed document, with its link. let image = |id: &NodeId| { - st.doc.node(*id).and_then(|n| match &n.kind { + stored(&st.doc, *id).and_then(|n| match &n.kind { NodeKind::Image(im) => Some(im.link.as_ref()), NodeKind::PlacedDocument(p) => Some(Some(&p.link)), _ => None, @@ -1712,22 +1771,23 @@ fn relink(s: &mut Session, p: &Value) -> Result { if ids.is_empty() { return Err(bad(C, "select the images to relink, or pass ids")); } - // All Instances: the other objects in the layers linked to the same files. + // All Instances: the other stored objects linked to the same files, each once. if scope == Scope::All { let paths: BTreeSet<&str> = ids.iter().filter_map(|id| image(id).flatten()).map(|l| l.path.as_str()).collect(); - let given: BTreeSet = ids.iter().copied().collect(); + let mut given: BTreeSet = ids.iter().copied().collect(); let mut more = vec![]; - st.doc.walk(|n| { + st.doc.visit_stored(|n, _| { if let Some((l, _, _)) = linked(n) && paths.contains(l.path.as_str()) - && !given.contains(&n.id) + && n.id.0 != 0 + && given.insert(n.id) { more.push(n.id); } }); ids.extend(more); } - if copy_to.is_some() && ids.iter().any(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::PlacedDocument(_)))) { + if copy_to.is_some() && ids.iter().any(|id| matches!(stored(&st.doc, *id).map(|n| &n.kind), Some(NodeKind::PlacedDocument(_)))) { return Err(bad(C, "copy takes images only: relink placed documents where their files are")); } // (ids, the file) per file to read. @@ -1763,7 +1823,7 @@ fn relink(s: &mut Session, p: &Value) -> Result { let mut images = vec![]; let mut documents: Vec<((u32, bool, PageBox), Vec)> = vec![]; for id in ids { - match st.doc.node(id).map(|n| &n.kind) { + match stored(&st.doc, id).map(|n| &n.kind) { Some(NodeKind::PlacedDocument(pl)) => { let k = (pl.page(), pl.bounding, pl.page_box); match documents.iter_mut().find(|(e, _)| *e == k) { @@ -1913,9 +1973,9 @@ fn copy_into_folder(_: &str, _: &[u8], _: &Path) -> Result<(String, bool)> { // ---------- the Links panel ---------- -/// Image object `id` of `d`. +/// Image object `id` of `d`, wherever it is stored. fn image_of(d: &Document, id: NodeId) -> Option<&ImageObject> { - match &d.node(id)?.kind { + match &stored(d, id)?.kind { NodeKind::Image(im) => Some(im), _ => None, } @@ -1933,7 +1993,7 @@ fn image_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result { .ok_or_else(|| bad(cmd, "select an image, or pass id"))?; match image_of(&st.doc, id) { Some(_) => Ok(id), - None if st.doc.node(id).is_none() => Err(crate::EngineError::NoNode(id)), + None if stored(&st.doc, id).is_none() => Err(crate::EngineError::NoNode(id)), None => Err(bad(cmd, format!("object {} is not an image", id.0))), } } @@ -1947,9 +2007,9 @@ fn placement_mut(n: &mut Node) -> Option<&mut PlacementOptions> { } } -/// The Placement Options of image or placed document `id` of `d`. +/// The Placement Options of image or placed document `id` of `d`, wherever it is stored. fn placement_of(d: &Document, id: NodeId) -> Option { - match &d.node(id)?.kind { + match &stored(d, id)?.kind { NodeKind::Image(im) => Some(im.placement), NodeKind::PlacedDocument(p) => Some(p.placement), _ => None, @@ -1962,12 +2022,12 @@ fn linked_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result { let id = object_param(p, "id", cmd)?.or_else(first).ok_or_else(|| bad(cmd, "select an image, or pass id"))?; match placement_of(&st.doc, id) { Some(_) => Ok(id), - None if st.doc.node(id).is_none() => Err(crate::EngineError::NoNode(id)), + None if stored(&st.doc, id).is_none() => Err(crate::EngineError::NoNode(id)), None => Err(bad(cmd, format!("object {} is not an image or a linked file", id.0))), } } -/// Per linked image in the layers of `st`: its file's status, where it was found when away from +/// Per linked image or placed document of `st`, wherever it is stored: its file's status, where it was found when away from /// its path, and whether the image shows its preview (each file probed once). pub(crate) fn statuses(st: &crate::DocState) -> BTreeMap, bool)> { let mut out = BTreeMap::new(); @@ -2068,17 +2128,20 @@ fn list(s: &mut Session, p: &Value) -> Result { } let interactions = if switch_or(p, "dcsTransparency", false, C)? { dcs_transparency(&st.doc) } else { BTreeSet::new() }; let statuses = statuses(st); - let mut objects = vec![]; - st.doc.walk(|n| { - if matches!(n.kind, NodeKind::Image(_) | NodeKind::PlacedDocument(_)) { - objects.push(n); + // The layer tree's objects, top first as the Layers panel lists them, then the others in the + // order they are stored (opacity-mask art, symbols, graph designs, patterns), each once. + let (mut objects, mut nested) = (vec![], vec![]); + let mut seen = std::collections::HashSet::new(); + st.doc.visit_stored(|n, place| { + if matches!(n.kind, NodeKind::Image(_) | NodeKind::PlacedDocument(_)) && n.id.0 != 0 && seen.insert(n.id) { + if place.in_layers() { objects.push((n, place)) } else { nested.push((n, place)) } } }); - // Top first, as the Layers panel lists them. objects.reverse(); + objects.extend(nested); let mut counts: BTreeMap<&str, usize> = BTreeMap::new(); let mut rows = vec![]; - for n in objects { + for (n, place) in objects { let (status, found, preview) = match statuses.get(&n.id) { Some((s, f, p)) => (s.as_str(), f.as_deref(), *p), None => ("embedded", None, false), @@ -2121,6 +2184,9 @@ fn list(s: &mut Session, p: &Value) -> Result { if preview { row["preview"] = json!(true); } + if let Some(owner) = owner_json(&st.doc, place) { + row["owner"] = owner; + } if interactions.contains(&n.id) { row["dcsTransparency"] = json!(true); } @@ -2141,15 +2207,21 @@ fn list(s: &mut Session, p: &Value) -> Result { fn go_to(s: &mut Session, p: &Value) -> Result { let st = s.doc()?; let id = linked_param(st, p, "links.goTo")?; + // An object in mask art or a definition has no place of its own on the canvas: the selection + // is cleared, and the reply names what holds it. + if let Some(owner) = st.doc.stored_node(id).and_then(|(_, place)| owner_json(&st.doc, place)) { + s.select(|_, sel| sel.set([]))?; + return Ok(json!({ "id": id.0, "onCanvas": false, "owner": owner })); + } let b = st.doc.node(id).and_then(Node::geometric_bounds).unwrap_or_default(); s.select(|_, sel| sel.set([id]))?; - Ok(json!({ "id": id.0, "bounds": [b.x0, b.y0, b.x1, b.y1] })) + Ok(json!({ "id": id.0, "bounds": [b.x0, b.y0, b.x1, b.y1], "onCanvas": true })) } fn embed(s: &mut Session, p: &Value) -> Result { const C: &str = "links.embed"; let st = s.doc()?; - let kind = |id: &NodeId| st.doc.node(*id).map(|n| &n.kind); + let kind = |id: &NodeId| stored(&st.doc, *id).map(|n| &n.kind); let linked = |id: &NodeId| match kind(id) { Some(NodeKind::Image(im)) => im.link.is_some(), Some(NodeKind::PlacedDocument(_)) => true, @@ -2207,7 +2279,7 @@ fn embed(s: &mut Session, p: &Value) -> Result { install(d, &ids, read, Some(Preserve::Bounds), None)?; } for id in &done { - if let Some(Node { kind: NodeKind::Image(im), .. }) = d.node_mut(*id) { + if let Some(Node { kind: NodeKind::Image(im), .. }) = d.stored_node_mut(*id) { im.link = None; } } @@ -2235,7 +2307,7 @@ fn unembed(s: &mut Session, p: &Value) -> Result { const C: &str = "links.unembed"; let st = s.doc()?; let id = image_param(st, p, C)?; - let n = st.doc.node(id).ok_or(crate::EngineError::NoNode(id))?; + let n = stored(&st.doc, id).ok_or(crate::EngineError::NoNode(id))?; let im = image_of(&st.doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?; if im.link.is_some() { return Err(bad(C, format!("image {} is linked already", id.0))); @@ -2321,7 +2393,7 @@ fn scale_rotation(xf: Affine, (px, py): (f64, f64)) -> (Value, Value) { /// Link Info of placed document `id`. fn placed_info(st: &crate::DocState, id: NodeId) -> Result { - let n = st.doc.node(id).ok_or(crate::EngineError::NoNode(id))?; + let n = stored(&st.doc, id).ok_or(crate::EngineError::NoNode(id))?; let NodeKind::PlacedDocument(pl) = &n.kind else { return Err(bad("links.info", format!("object {} is not a placed document", id.0))) }; let size = n.geometric_bounds().unwrap_or_default(); let (scale, rotation) = scale_rotation(pl.xf, (1.0, 1.0)); @@ -2401,7 +2473,7 @@ fn placement_options(s: &mut Session, p: &Value) -> Result { }; s.edit("Placement Options", |d, _| { for id in &ids { - if let Some(o) = d.node_mut(*id).and_then(placement_mut) { + if let Some(o) = d.stored_node_mut(*id).and_then(placement_mut) { set(o); } } diff --git a/crates/engine/src/cmd/live/commands.rs b/crates/engine/src/cmd/live/commands.rs index 8a92d759f9..692ce9e563 100644 --- a/crates/engine/src/cmd/live/commands.rs +++ b/crates/engine/src/cmd/live/commands.rs @@ -172,7 +172,7 @@ pub fn specs() -> Vec { "Make with Top Object", ["Object", "Envelope Distort"], Some("Cmd+Alt+C"), - "{ids?} the topmost selected path becomes the envelope of the others: its outline splits into four sides at its corners, and each piece of a side takes a share of the content in proportion to its control polygon's length (type maps from its glyph outline bounds) → {id}", + "{ids?} the topmost selected path becomes the envelope of the others: its outline splits into four sides at its corners, and each piece of a side takes a share of the content in proportion to its control polygon's length, and a side whose pieces are all one curve split at anchors follows that curve's parameter (type maps from its glyph outline bounds) → {id}", has_multi, env_make_top ), diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index b4639f0de5..2dee458930 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -481,6 +481,12 @@ fn join_point(sp: &mut SubPath, ai: usize, smooth: bool) { } } +#[cfg(test)] +thread_local! { + /// Anchors that [`merge_coincident`] moved to a lower index of their vector on this thread. + static ANCHOR_MOVES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Merge each run of `picked` neighbours of `sp` that lie on one another into one anchor, which /// keeps the first one's incoming handle and the last one's outgoing handle. Returns how many /// anchors went. @@ -501,23 +507,68 @@ fn merge_coincident(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind: join_point(sp, 0, smooth); } } - // Back to front, so the indices `picked` knows stay true for the anchors still to visit. - for i in (1..sp.anchors.len()).rev() { + // Back to front, so the indices `picked` knows stay true for the anchors still to visit. A + // merged anchor is only marked here; the marked anchors are removed in one pass at the end. + let closed = sp.closed; + let anchors = &mut sp.anchors; + let len = anchors.len(); + let mut gone = vec![false; len]; + // The anchor after `i` that is still on the path, and the last one still on it. + let mut next = None; + let mut last = len.saturating_sub(1); + for i in (1..len).rev() { if picked(i - 1) && picked(i) - && let Some([a, b]) = sp.anchors.get_mut(i - 1..=i) + && let Some([a, b]) = anchors.get_mut(i - 1..=i) && same(a, b) { a.h_out = b.h_out; - sp.anchors.remove(i); - if let Some(smooth) = join_kind { - join_point(sp, i - 1, smooth); + if let Some(slot) = gone.get_mut(i) { + *slot = true; } + if next.is_none() { + last = i - 1; + } + if let Some(smooth) = join_kind { + // The neighbors the anchor has on the path as it now stands, as `join_point` sees them. + let prev = if i > 1 { Some(i - 2) } else { closed.then_some(last) }; + let after = next.or(closed.then_some(0)); + join_point_between(anchors, i - 1, prev, after, smooth); + } + } else { + next = Some(i); } } + #[cfg(test)] + if let Some(first) = gone.iter().position(|&g| g) { + // `retain` moves each anchor it keeps after the first one it drops. + let dropped = gone.iter().filter(|&&g| g).count(); + ANCHOR_MOVES.set(ANCHOR_MOVES.get() + (len - first - dropped)); + } + if gone.contains(&true) { + let mut k = 0; + anchors.retain(|_| { + let keep = !gone.get(k).copied().unwrap_or(false); + k += 1; + keep + }); + } before - sp.anchors.len() } +/// [`join_point`] on anchor `ai` of `anchors` with its neighbors given by index. +fn join_point_between(anchors: &mut [Anchor], ai: usize, prev: Option, next: Option, smooth: bool) { + let at = |j: Option| j.and_then(|j| anchors.get(j)).map(|a| a.p); + let (prev, next) = (at(prev), at(next)); + if let Some(a) = anchors.get_mut(ai) { + if smooth { + a.smooth_between(prev, next); + } else { + a.retract(); + } + } +} + /// Close subpath `si` of path `id`, merging coincident endpoints if present. fn close_subpath_in_node(d: &mut Document, id: NodeId, si: usize, join_kind: Option) -> Result<()> { let path = path_mut(d, id)?; @@ -751,8 +802,19 @@ pub(super) fn join(s: &mut Session, p: &Value) -> Result { let mut merged = vec![]; for (id, picked) in &st.selection.anchors { let Some(mut path) = st.doc.node(*id).and_then(|n| n.path_data()).cloned() else { continue }; - let n: usize = - path.subpaths.iter_mut().enumerate().map(|(si, sp)| merge_coincident(sp, |ai| picked.contains(&(si, ai)), join_kind)).sum(); + // One flag per anchor; references past the end of a subpath or to a missing one pick nothing. + let mut masks: Vec> = path.subpaths.iter().map(|sp| vec![false; sp.anchors.len()]).collect(); + for &(si, ai) in picked { + if let Some(flag) = masks.get_mut(si).and_then(|m| m.get_mut(ai)) { + *flag = true; + } + } + let n: usize = path + .subpaths + .iter_mut() + .zip(&masks) + .map(|(sp, mask)| merge_coincident(sp, |ai| mask.get(ai).copied().unwrap_or(false), join_kind)) + .sum(); if n > 0 { merged.push((*id, path)); } @@ -1276,7 +1338,7 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result { .into_iter() .enumerate() .flat_map(|(si, sp)| { - let cuts = refs.iter().filter_map(|&(s, seg)| (s == si).then_some(seg)).collect(); + let cuts = subpath_refs(refs, si).collect(); without_segments(sp, &cuts) }) .filter(|s| s.anchors.len() >= 2) @@ -1288,7 +1350,7 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result { .into_iter() .enumerate() .flat_map(|(si, sp)| { - let gone = set.iter().filter_map(|&(s, ai)| (s == si).then_some(ai)).collect(); + let gone = subpath_refs(set, si).collect(); without_anchors(sp, &gone) }) .filter(|s| s.anchors.len() >= 2) @@ -1314,6 +1376,12 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result { ok() } +/// The anchor or segment indexes in `refs` that belong to subpath `si`, in index order. +/// `refs` is ordered by subpath first, so this reads only that subpath's entries. +pub(super) fn subpath_refs(refs: &BTreeSet<(usize, usize)>, si: usize) -> impl Iterator + '_ { + refs.range((si, 0)..=(si, usize::MAX)).map(|&(_, i)| i) +} + /// Retain path `id` from `d` without copying its geometry before deletion takes its subpaths. /// The shared snapshot supplies the original path classification and, only if needed, gradient /// bounds after the working node's geometry has moved. Returns `NoNode` for a missing/non-path ID. @@ -1722,7 +1790,7 @@ fn cut_at_anchors(s: &mut Session, _: &Value) -> Result { let Some(pd) = st.doc.node(*id).and_then(|n| n.path_data()) else { continue }; let (mut subs, mut starts) = (vec![], vec![]); for (si, sp) in pd.subpaths.iter().enumerate() { - let at: BTreeSet = set.iter().filter(|(s, _)| *s == si).map(|(_, a)| *a).collect(); + let at: BTreeSet = subpath_refs(set, si).collect(); let pieces = sp.cut_at(&at); // The pieces that start at a cut: every piece of an opened closed subpath, all but the // first of an open one. @@ -1763,3 +1831,140 @@ fn cut_at_anchors(s: &mut Session, _: &Value) -> Result { })?; Ok(super::draw2::ids_json(&ids)) } + +#[cfg(test)] +mod tests { + use super::*; + + /// `merge_coincident` removing each merged anchor from the vector straight away, kept as the + /// reference the one-pass version must match. + fn merge_coincident_by_removal(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind: Option) -> usize { + let same = |a: &Anchor, b: &Anchor| a.p.distance(b.p) < 1e-6; + let before = sp.anchors.len(); + if sp.closed + && before > 2 + && picked(0) + && picked(before - 1) + && let [first, .., last] = sp.anchors.as_mut_slice() + && same(first, last) + { + first.h_in = last.h_in; + sp.anchors.pop(); + if let Some(smooth) = join_kind { + join_point(sp, 0, smooth); + } + } + for i in (1..sp.anchors.len()).rev() { + if picked(i - 1) + && picked(i) + && let Some([a, b]) = sp.anchors.get_mut(i - 1..=i) + && same(a, b) + { + a.h_out = b.h_out; + sp.anchors.remove(i); + if let Some(smooth) = join_kind { + join_point(sp, i - 1, smooth); + } + } + } + before - sp.anchors.len() + } + + /// Every field of every anchor, bit for bit. + fn bits(sp: &SubPath) -> (Vec<[u64; 6]>, Vec, bool) { + let b = |p: Point| [p.x.to_bits(), p.y.to_bits()]; + let fields = sp.anchors.iter().map(|a| [b(a.p), b(a.h_in), b(a.h_out)].concat().try_into().unwrap()).collect(); + (fields, sp.anchors.iter().map(|a| a.kind).collect(), sp.closed) + } + + /// A small linear congruential generator, so the cases are the same on every run. + struct Lcg(u64); + impl Lcg { + fn below(&mut self, n: u64) -> u64 { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (self.0 >> 33) % n + } + } + + fn same_as_removal(sp: &SubPath, picked: &dyn Fn(usize) -> bool, join_kind: Option) { + let (mut ours, mut theirs) = (sp.clone(), sp.clone()); + let n = merge_coincident(&mut ours, picked, join_kind); + let m = merge_coincident_by_removal(&mut theirs, picked, join_kind); + assert_eq!(n, m, "{sp:?} {join_kind:?}"); + assert_eq!(bits(&ours), bits(&theirs), "{sp:?} {join_kind:?}"); + } + + /// Short paths with points on, near and just past the merge distance, selections with stale + /// indices, every anchor kind and every join kind give the same anchors, bit for bit, as + /// removing each merged anchor straight away. + #[test] + fn merging_coincident_anchors_matches_removing_them_one_by_one() { + let spots = [(0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (5e-7, 0.0), (0.0, 1.5e-6), (10.0, 0.0), (5.0, 5.0), (10.0, 0.0)]; + let mut rng = Lcg(7); + for _ in 0..30_000 { + let n = rng.below(9) as usize; + let anchors = (0..n) + .map(|_| { + let (x, y) = spots[rng.below(spots.len() as u64) as usize]; + let p = Point::new(x, y); + let handle = |rng: &mut Lcg| match rng.below(3) { + 0 => p, + _ => p + Vec2::new(rng.below(7) as f64 - 3.0, rng.below(7) as f64 - 3.0), + }; + let (h_in, h_out) = (handle(&mut rng), handle(&mut rng)); + let kind = if rng.below(2) == 0 { AnchorKind::Corner } else { AnchorKind::Smooth }; + Anchor { p, h_in, h_out, kind } + }) + .collect(); + let sp = SubPath::new(anchors, rng.below(2) == 0); + let picks: Vec = (0..n + 2).map(|_| rng.below(4) != 0).collect(); + let join_kind = [None, Some(false), Some(true)][rng.below(3) as usize]; + same_as_removal(&sp, &|i| picks.get(i).copied().unwrap_or(false), join_kind); + } + } + + /// A smooth join of three anchors on one another takes the outgoing handle the middle anchor + /// was given when it joined the right one: an already smooth left anchor keeps that handle. + #[test] + fn a_smooth_join_of_three_anchors_keeps_the_handle_the_middle_one_got() { + let o = Point::ZERO; + let left = Anchor { p: o, h_in: Point::new(-2.0, 0.0), h_out: o, kind: AnchorKind::Smooth }; + let right = Anchor { p: o, h_in: o, h_out: Point::new(0.0, 5.0), kind: AnchorKind::Corner }; + let mut sp = SubPath::new(vec![left, Anchor::corner(o), right, Anchor::corner(Point::new(10.0, 0.0))], false); + assert_eq!(merge_coincident(&mut sp, |i| i < 3, Some(true)), 2); + let a = sp.anchors[0]; + assert_eq!((a.h_in, a.h_out, a.kind), (Point::new(-2.0, 0.0), Point::new(10.0 / 3.0, 0.0), AnchorKind::Smooth)); + assert_eq!(sp.anchors.len(), 2); + } + + /// One long run of selected anchors on one another, open or closed, becomes one anchor. + #[test] + fn a_long_run_of_anchors_on_one_another_becomes_one() { + for closed in [false, true] { + for join_kind in [None, Some(false), Some(true)] { + let anchors = (0..50_000).map(|i| Anchor::smooth(Point::ZERO, Point::new(1.0, i as f64))).collect(); + let sp = SubPath::new(anchors, closed); + same_as_removal(&sp, &|_| true, join_kind); + let mut ours = sp.clone(); + assert_eq!(merge_coincident(&mut ours, |_| true, join_kind), 49_999); + assert_eq!((ours.anchors.len(), ours.closed), (1, closed)); + } + } + } + + /// A long selected run at the start of a path followed by as many anchors that stay: each + /// anchor after the run moves once, not once per merged anchor. + #[test] + fn a_long_run_before_many_other_anchors_merges_in_one_pass() { + let run = 300_000; + let anchors = (0..run).map(|_| Anchor::corner(Point::ZERO)).chain((1..=run).map(|i| Anchor::corner(Point::new(i as f64, 1.0)))).collect(); + let mut sp = SubPath::new(anchors, false); + ANCHOR_MOVES.set(0); + assert_eq!(merge_coincident(&mut sp, |i| i < run, Some(false)), run - 1); + assert_eq!(ANCHOR_MOVES.get(), run); + assert_eq!(sp.anchors.len(), run + 1); + assert_eq!(sp.anchors[0].p, Point::ZERO); + assert_eq!(sp.anchors[1].p, Point::new(1.0, 1.0)); + assert_eq!(sp.anchors[run].p, Point::new(run as f64, 1.0)); + } +} diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index c617c4de8e..ac57d1852f 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -1228,7 +1228,7 @@ fn simplify(s: &mut Session, p: &Value) -> Result { Some(l) => po::simplify_level_tolerance(l), None => given_tolerance.unwrap_or(1.0), }; - let opts = po::SimplifyOptions { tolerance: tolerance.clamp(1e-4, 1e4), corner_angle_deg: corner_angle, straight_lines, smooth: 0.0 }; + let opts = po::SimplifyOptions { tolerance: tolerance.clamp(1e-4, 1e4), corner_angle_deg: corner_angle, straight_lines, ..Default::default() }; // A path with segments direct-selected simplifies only their runs, and keeps those runs (and the // other anchors it had selected) direct-selected. let roots = selected_roots(s)?; diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 36444878ef..b221f60187 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -944,7 +944,8 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result { (None, [id]) => *id, _ => return Err(bad(C, "select one image or pass id")), }; - let n = st.doc.node(id).ok_or(EngineError::NoNode(id))?; + // An image in opacity-mask art or a definition's art is found by its id too (`links.list`). + let n = st.doc.stored_node(id).map(|(n, _)| &**n).ok_or(EngineError::NoNode(id))?; let NodeKind::Image(im) = &n.kind else { return Err(bad(C, format!("object {} is not an image", id.0))) }; // Effective resolution: 72 pt per inch over the points one pixel spans along each axis. let [a, b, c, d, ..] = im.xf.as_coeffs(); diff --git a/crates/engine/src/cmd/place/adopt.rs b/crates/engine/src/cmd/place/adopt.rs index 15a39f06e5..9cd28b7e25 100644 --- a/crates/engine/src/cmd/place/adopt.rs +++ b/crates/engine/src/cmd/place/adopt.rs @@ -10,7 +10,7 @@ use std::sync::Arc; use vectorcraft_brush::{Brush, BrushKind}; use vectorcraft_color::Paint; -use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind}; +use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind, PatternDef, Symbol}; use super::unique_name; @@ -118,11 +118,12 @@ impl Used { type Renames = BTreeMap, bool)>; /// Names in `dst` for the `used` definitions of `src` (`def`): the same name when `dst` has none -/// (copied) or an equal one (shared), else a free variant (`taken`, copied). -fn names( +/// (copied) or one that is the `same` (shared), else a free variant (`taken`, copied). +fn names( used: &[String], def: impl Fn(&str) -> Option, existing: impl Fn(&str) -> Option, + same: impl Fn(&T, &T) -> bool, taken: impl Fn(&str) -> bool, ) -> Renames { let mut out = Renames::new(); @@ -130,7 +131,7 @@ fn names( let Some(d) = def(name) else { continue }; let entry = match existing(name) { None => (Some(name.clone()), true), - Some(e) if e == d => (Some(name.clone()), false), + Some(e) if same(&e, &d) => (Some(name.clone()), false), Some(_) => { (Some(unique_name(name, |c| taken(c) || used.iter().any(|u| u == c) || out.values().any(|(n, _)| n.as_deref() == Some(c)))), true) } @@ -140,6 +141,65 @@ fn names( out } +/// `n` as `dst` would copy it in ([`Document::reid`]), with the ids a document of its own gives it: +/// art copied in once, which differs from the file's only in its ids, compares equal to the file's. +fn canon(dst: &Document, n: &Node) -> Node { + let mut own = Document::new(0.0, 0.0); + // Pixels the art carries take a key `dst` doesn't use for other pixels, as they do in `dst`. + let mut keys = vec![]; + vectorcraft_doc::swatches::walk_with_masks(n, &mut |c| { + if let NodeKind::Image(im) = &c.kind + && im.pixels.is_some() + { + keys.push(im.key.clone()); + } + }); + for (k, blob) in &dst.images { + if keys.iter().any(|key| k == key || k.strip_prefix(key.as_str()).is_some_and(|rest| rest.starts_with('-'))) { + own.images.insert(k.clone(), blob.clone()); + } + } + own.reid(n) +} + +/// Do symbols `a` and `b` draw the same, whatever ids their art has ([`canon`])? +fn same_symbol(dst: &Document, a: &Symbol, b: &Symbol) -> bool { + let own = |s: &Symbol| Symbol { art: Arc::new(canon(dst, &s.art)), ..s.clone() }; + own(a) == own(b) +} + +/// Do patterns `a` and `b` draw the same, whatever ids their art has ([`canon`])? +fn same_pattern(dst: &Document, a: &PatternDef, b: &PatternDef) -> bool { + let bare = |p: &PatternDef| PatternDef { art: vec![], ..p.clone() }; + bare(a) == bare(b) && a.art.len() == b.art.len() && a.art.iter().zip(&b.art).all(|(x, y)| canon(dst, x) == canon(dst, y)) +} + +/// Does art `a` use a resource that `m` (images, symbols, patterns, brushes, swatches) gives +/// another name, or a swatch whose link `m` drops? +fn uses_moved(a: &Node, m: [&Renames; 5]) -> bool { + let moved = |map: &Renames, k: &str| map.get(k).is_some_and(|(new, _)| new.as_deref() != Some(k)); + let (mut a, mut any) = (a.clone(), false); + refs(&mut a, &mut |r| { + any |= match r { + Ref::Image(k) => moved(m[0], k), + Ref::Symbol(k) => moved(m[1], k), + Ref::Pattern(k) => moved(m[2], k), + Ref::Brush(k) => moved(m[3], k), + Ref::Swatch(link) => link.as_deref().is_some_and(|k| moved(m[4], k)), + } + }); + any +} + +/// Copy each of `shared` in `map` under a free name, as [`names`] does for a definition `dst` +/// holds differently. +fn unshare(map: &mut Renames, shared: &[String], used: &[String], taken: impl Fn(&str) -> bool) { + for name in shared { + let free = unique_name(name, |c| taken(c) || used.iter().any(|u| u == c) || map.values().any(|(n, _)| n.as_deref() == Some(c))); + map.insert(name.clone(), (Some(free), true)); + } +} + /// The renamed resources whose definitions are copied: (name in `src`, name in `dst`). fn copies(m: &Renames) -> Vec<(&str, &str)> { m.iter().filter(|(_, (_, copy))| *copy).filter_map(|(old, (new, _))| Some((old.as_str(), new.as_deref()?))).collect() @@ -194,14 +254,17 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) { } } - let images = names(&used.images, |k| src.images.get(k), |k| dst.images.get(k), |c| dst.images.contains_key(c)); - let symbols = names( + let images = names(&used.images, |k| src.images.get(k), |k| dst.images.get(k), |a, b| a == b, |c| dst.images.contains_key(c)); + // Symbol and pattern art copied in takes ids of `dst`, so their art is compared by what it + // draws: placing the same file again shares what the first placement brought. + let mut symbols = names( &used.symbols, |n| src.symbols.iter().find(|s| s.name == n), |n| dst.symbols.iter().find(|s| s.name == n), + |a, b| same_symbol(dst, a, b), |c| dst.symbols.iter().any(|s| s.name == c), ); - let patterns = names(&used.patterns, |n| src.pattern(n), |n| dst.pattern(n), |c| dst.pattern(c).is_some()); + let mut patterns = names(&used.patterns, |n| src.pattern(n), |n| dst.pattern(n), |a, b| same_pattern(dst, a, b), |c| dst.pattern(c).is_some()); // A swatch the document defines differently isn't renamed (that would add look-alike swatches): // the colours linked to it keep their look, unlinked. let swatches: Renames = used @@ -236,12 +299,33 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) { any }; let mut dst_brushes = vectorcraft_brush::library(dst); - let brushes = names( + let mut brushes = names( &used.brushes, |n| src_brushes.iter().find(|b| b.name == n).map(|b| (b, moves_art(b))), |n| dst_brushes.iter().find(|b| b.name == n).map(|b| (b, false)), + |a, b| a == b, |c| dst_brushes.iter().any(|b| b.name == c), ); + // Likewise a symbol, pattern or brush whose art uses a resource that moves isn't the + // document's of that name: it is copied under a free name, which can move what uses it in turn. + loop { + let maps = [&images, &symbols, &patterns, &brushes, &swatches]; + let shared = |map: &Renames| map.iter().filter(|(_, (_, copy))| !*copy).map(|(k, _)| k.clone()).collect::>(); + let sym: Vec = + shared(&symbols).into_iter().filter(|n| src.symbols.iter().any(|s| s.name == *n && uses_moved(&s.art, maps))).collect(); + let pat: Vec = + shared(&patterns).into_iter().filter(|n| src.pattern(n).is_some_and(|p| p.art.iter().any(|a| uses_moved(a, maps)))).collect(); + let bru: Vec = shared(&brushes) + .into_iter() + .filter(|n| src_brushes.iter().find(|b| b.name == *n).is_some_and(|b| brush_art(&mut b.clone()).into_iter().any(|a| uses_moved(a, maps)))) + .collect(); + if sym.is_empty() && pat.is_empty() && bru.is_empty() { + break; + } + unshare(&mut symbols, &sym, &used.symbols, |c| dst.symbols.iter().any(|s| s.name == c)); + unshare(&mut patterns, &pat, &used.patterns, |c| dst.pattern(c).is_some()); + unshare(&mut brushes, &bru, &used.brushes, |c| dst_brushes.iter().any(|b| b.name == c)); + } let mut rename = |r: Ref| { let (map, k) = match r { @@ -272,6 +356,8 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) { if let Some(mut def) = src.symbols.iter().find(|s| s.name == old).cloned() { def.name = new.to_string(); refs(Arc::make_mut(&mut def.art), &mut rename); + // The art takes ids of `dst`: those of `src` may name objects of `dst` already. + def.art = Arc::new(dst.reid(&def.art)); dst.symbols.push(def); } } @@ -280,6 +366,7 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) { def.name = new.to_string(); for a in &mut def.art { refs(Arc::make_mut(a), &mut rename); + *a = Arc::new(dst.reid(a)); } dst.patterns.push(def); } diff --git a/crates/engine/src/cmd/place/document.rs b/crates/engine/src/cmd/place/document.rs index 9f58e4851d..8e4afaa295 100644 --- a/crates/engine/src/cmd/place/document.rs +++ b/crates/engine/src/cmd/place/document.rs @@ -378,8 +378,10 @@ pub(crate) fn full_documents(d: &Document) -> (Cow<'_, Document>, Vec) { /// Placed document `id` of `d` replaced by an editable copy of its art, as placing its file /// without Link gives (its resources joining `d`, renamed where `d` uses a name for something /// else), keeping the object's id, place, name and transparency: Break Link and Object › Expand. +/// A placed document in opacity-mask art or in the art of a symbol, graph design or pattern is +/// replaced where it is stored. pub(crate) fn expand(d: &mut Document, id: NodeId, cmd: &str) -> Result<()> { - let n = d.node(id).cloned().ok_or(EngineError::NoNode(id))?; + let n = d.stored_node(id).map(|(n, _)| Node::clone(n)).ok_or(EngineError::NoNode(id))?; let NodeKind::PlacedDocument(p) = &n.kind else { return Err(bad(cmd, format!("object {} is not a placed document", id.0))) }; let blob = d.images.get(&p.key).ok_or_else(|| bad(cmd, format!("object {} has lost its file's contents: relink it", id.0)))?; let bytes = vectorcraft_doc::placed_document::full_bytes(p, blob) @@ -395,6 +397,10 @@ pub(crate) fn expand(d: &mut Document, id: NodeId, cmd: &str) -> Result<()> { let art = super::transformed(Node::new(d.alloc_id(), NodeKind::Group { children, clip: a.clip.is_some() }), m); let mut out = n.clone(); out.kind = art.kind; + if d.node(id).is_none() { + *d.stored_node_mut(id).ok_or(EngineError::NoNode(id))? = out; + return Ok(()); + } let (par, index, _) = d.position(id).ok_or(EngineError::NoNode(id))?; d.remove(id)?; d.insert(par, index, out)?; diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index dfa44a1436..3fa082bdb0 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -672,13 +672,53 @@ fn takes_over(s: &Session, plugin: &Plugin) -> bool { } } +#[cfg(test)] +thread_local! { + /// Tests: runs once in the next `plugin.install` on this thread after its checks and before it + /// installs, as another session changing the plug-ins in between would. + pub(crate) static BEFORE_INSTALL: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; + /// Tests: runs once in the next `plugin.install` on this thread right after it reads the grant + /// held for the id. + pub(crate) static AFTER_GRANT_READ: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; + /// Tests: runs once in the next `plugin.install` on this thread after it installs and before it + /// writes the store. + pub(crate) static BEFORE_STORE: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; + /// Tests: runs once on this thread when [`hold_plugin_changes`] finds the lock held and waits. + pub(crate) static WHILE_WAITING: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + +/// Held by `plugin.install` from its first read of the grant until the store holds what it +/// installed, and throughout by `plugin.remove`, by loads of the stored plug-ins +/// ([`Session::load_stored_plugins`]) and by loads of a plug-ins folder: these run one after the +/// other across sessions. +static PLUGIN_CHANGES: Mutex<()> = Mutex::new(()); + +/// Takes [`PLUGIN_CHANGES`], waiting while another session holds it. +pub(crate) fn hold_plugin_changes() -> std::sync::MutexGuard<'static, ()> { + match PLUGIN_CHANGES.try_lock() { + Ok(held) => held, + Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(), + Err(std::sync::TryLockError::WouldBlock) => { + #[cfg(test)] + if let Some(waiting) = WHILE_WAITING.take() { + waiting(); + } + PLUGIN_CHANGES.lock().unwrap_or_else(|e| e.into_inner()) + } + } +} + /// `plugin.install`: loads and checks the module, refuses `grant` and `allowHeavy` that neither an /// [`InstallApproval`] for this module nor the session allows, one that asks for a heavy budget /// unless `allowHeavy` says a person agreed, one that lists permissions no person has granted this /// very module unless `grant` lists them all, one that would take another module's place -/// ([`takes_over`]) unless `replace` is true, and one whose SHA-256 isn't the `hash` given; records -/// the grant with the module's hash, keeps it for the next start and installs it → its -/// `plugin.list` entry. A module that lists no permissions ends any grant held for its id. +/// ([`takes_over`]) unless `replace` is true, and one whose SHA-256 isn't the `hash` given. It then +/// checks the plug-in installed under the id and its grant again while it records the grant with +/// the module's hash and installs it ([`registry::install_checked`]), and only then keeps both for +/// the next start → its `plugin.list` entry. A refused install changes neither the plug-in store +/// nor the plug-ins and grants of the process. A module that lists no permissions ends any grant +/// held for its id. A `plugin.remove` in another session waits until the install has written the +/// store. fn install(s: &mut Session, p: &Value) -> Result { const C: &str = "plugin.install"; // One use: spent whatever this install does. @@ -696,21 +736,36 @@ fn install(s: &mut Session, p: &Value) -> Result { { return Err(bad(C, "the module doesn't have the SHA-256 `hash` gives: nothing was installed")); } - if replace == Some(false) && registry::get(plugin.id()).is_some() { - return Err(bad(C, format!("a plug-in with id {:?} is already installed", plugin.id()))); + // A removal in another session waits until the store holds what this install wrote. + let _held = hold_plugin_changes(); + // The grant the checks below count on, the approval included. The install checks it again, + // with the plug-in installed under the id, before anything is stored: another session may + // change either in between. + let seen_grant = registry::granted(plugin.id()); + #[cfg(test)] + if let Some(between) = AFTER_GRANT_READ.take() { + between(); } - // Another module under the id gets the settings and cache kept for it: whoever installs it asks - // the user first. - if replace != Some(true) && takes_over(s, &plugin) { + let installed_already = || bad(C, format!("a plug-in with id {:?} is already installed", plugin.id())); + let taken_over = || { let name = permissions::display_text(&plugin.manifest().name, permissions::MAX_SHOWN_NAME); - return Err(bad( + bad( C, format!( "“{name}” is another module than the plug-in with id {:?} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees", plugin.id() ), - )); + ) + }; + if replace == Some(false) && registry::get(plugin.id()).is_some() { + return Err(installed_already()); } + // Another module under the id gets the settings and cache kept for it: whoever installs it asks + // the user first. + if replace != Some(true) && takes_over(s, &plugin) { + return Err(taken_over()); + } + let (installed_already, taken_over) = (installed_already(), taken_over()); // `grant` and `allowHeavy` say that a person agreed, and a request alone can't say that. let approval = approval.filter(|a| a.covers(&plugin)); if !s.plugin_grants_from_requests && ((grant.is_some() && approval.is_none()) || (allow_heavy && !approval.is_some_and(|a| a.heavy))) { @@ -744,15 +799,55 @@ fn install(s: &mut Session, p: &Value) -> Result { // this very module already covers all of them. let m = plugin.manifest(); let wanted = m.permissions(); - if !s.plugin_approved(&plugin) && !grant.as_ref().is_some_and(|g| wanted.iter().all(|w| g.contains(w))) { + let needs_approval = || { let name = permissions::display_text(&m.name, permissions::MAX_SHOWN_NAME); let asked = permissions::names(&wanted).join(", "); - return Err(bad( + bad( C, format!( "“{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" ), - )); + ) + }; + let granted_here = grant.as_ref().is_some_and(|g| wanted.iter().all(|w| g.contains(w))); + // Without a plug-in store, the grant read above approves the module or doesn't. + let approved = match s.plugin_dir { + None => !m.asks_permissions() || seen_grant.as_ref().is_some_and(|g| g.covers(&m.id, plugin.hash(), &wanted)), + Some(_) => s.plugin_approved(&plugin), + }; + if !approved && !granted_here { + return Err(needs_approval()); + } + let needs_approval = needs_approval(); + let (id, hash, asks) = (m.id.clone(), plugin.hash().to_string(), m.asks_permissions()); + let g = Grant { id: id.clone(), hash: hash.clone(), permissions: wanted }; + let update = if asks { registry::GrantUpdate::Record(GrantToken::after_engine_approval(g.clone())) } else { registry::GrantUpdate::Revoke }; + // Another module installed under the id since the checks above takes the place they found free, + // or held by these bytes. A grant that changed since no longer approves what they approved, + // unless `grant` approves this module by itself or the new grant covers it. + let check = |installed: Option<&Plugin>, held: Option<&Grant>| { + if let Some(installed) = installed { + match replace { + Some(false) => return Err(installed_already), + None if installed.hash() != hash => return Err(taken_over), + _ => {} + } + } + if asks && !granted_here && held != seen_grant.as_ref() && !held.is_some_and(|h| h.covers(&id, &hash, &g.permissions)) { + return Err(needs_approval); + } + Ok(()) + }; + #[cfg(test)] + if let Some(between) = BEFORE_INSTALL.take() { + between(); + } + // The plug-in gets the settings and cache kept for its id. A module without permissions takes + // the id over, so nothing the user approved for the id applies any more. + let installed = registry::install_checked(plugin, update, check, || s.attach_plugin_storage(&id), err)?; + #[cfg(test)] + if let Some(between) = BEFORE_STORE.take() { + between(); } // Installed plug-ins stay installed after a restart (#2541). The module is written first and its // grant only once it is there; when the grant can't be written, the store gets the module it @@ -760,18 +855,14 @@ fn install(s: &mut Session, p: &Value) -> Result { // which the grant doesn't cover. A write that reports a failure may still have put the old // module back, so the store is read again to tell which module it holds. A stored module that // can't be read back isn't replaced by one that needs a grant. - let previous = s.stored_plugin_bytes(plugin.id()); - let mut stored = (previous.is_ok() || !m.asks_permissions()) && s.store_plugin(plugin.id(), &bytes); - let holds_new = |s: &Session| s.stored_plugin_bytes(plugin.id()).is_ok_and(|held| held.as_deref() == Some(&bytes[..])); - if m.asks_permissions() { - let g = Grant { id: m.id.clone(), hash: plugin.hash().to_string(), permissions: wanted }; - registry::grant(GrantToken::after_engine_approval(g.clone())); - if stored && !s.store_grant(&m.id, Some(g)) { - stored = !s.put_back_plugin(plugin.id(), previous.ok().flatten().as_deref()) && holds_new(s); + let previous = s.stored_plugin_bytes(&id); + let mut stored = (previous.is_ok() || !asks) && s.store_plugin(&id, &bytes); + let holds_new = |s: &Session| s.stored_plugin_bytes(&id).is_ok_and(|held| held.as_deref() == Some(&bytes[..])); + if asks { + if stored && !s.store_grant(&id, Some(g)) { + stored = !s.put_back_plugin(&id, previous.ok().flatten().as_deref()) && holds_new(s); } } else { - // This module takes the id over, so nothing the user approved for the id applies any more. - registry::revoke(&m.id); // When the write failed, the old stored module stays in the folder and needs its grant at // the next launch. A grant that can't be removed still approves the old bytes, so the store // gets the module it held back. When that module can't be read or written back, or there @@ -780,23 +871,21 @@ fn install(s: &mut Session, p: &Value) -> Result { // approves nothing, and the new module stays; one that can't be opened or read may approve // the old bytes once it reads again. let writes = s.grant_writes(); - if stored && !s.store_grant(&m.id, None) && s.holds_plugin_grant(&m.id) { - let back = previous.as_ref().is_ok_and(|held| s.put_back_plugin(plugin.id(), held.as_deref())); + if stored && !s.store_grant(&id, None) && s.holds_plugin_grant(&id) { + let back = previous.as_ref().is_ok_and(|held| s.put_back_plugin(&id, held.as_deref())); stored = !back && holds_new(s); if !back || matches!(previous, Ok(None)) { - s.ignore_stored_grant(&m.id, writes); + s.ignore_stored_grant(&id, writes); } } } - // It gets the settings and cache kept for its id. - s.attach_plugin_storage(plugin.id()); // Installing a disabled plug-in again (an updated version) turns it on for the next launch too, // also when it is disabled by its stored file alone (it stopped a launch while loading). When // the new version could not replace the stored file, the old one stays disabled. - let file = s.stored_plugin_file(plugin.id()); + let file = s.stored_plugin_file(&id); let mut changed = false; if file.is_none() || stored { - changed = safe_mode::set_enabled(&safe_mode::Item::of(&plugin), true); + changed = safe_mode::set_enabled(&safe_mode::Item::of(&installed), true); if let Some(file) = file { changed |= safe_mode::set_enabled(&safe_mode::Item::file(file), true); } @@ -804,7 +893,6 @@ fn install(s: &mut Session, p: &Value) -> Result { if changed { s.store_disabled_plugins(); } - let installed = registry::install(plugin).map_err(err)?; let mut v = describe_installed(&installed); if !unknown.is_empty() { v["unknownCommands"] = json!(unknown); @@ -904,6 +992,8 @@ fn load_folder(s: &Session, folder: &str) -> Value { None if crate::file_access::current().is_none() => Ok(()), None => Err(format!("automation path rejected: {} isn't valid text", f.display())), }; + // A `plugin.install` in another session finishes writing the store first. + let _held = hold_plugin_changes(); match registry::load_folder_where(std::path::Path::new(folder), allow, s.plugin_folder_approver()) { Ok(r) => { for id in &r.loaded { @@ -1074,6 +1164,8 @@ fn info(_: &mut Session, p: &Value) -> Result { fn remove(s: &mut Session, p: &Value) -> Result { let id = str_param(p, "id").ok_or_else(|| bad("plugin.remove", "missing `id`"))?; + // An install in another session finishes its store writes first. + let _held = hold_plugin_changes(); let installed = registry::get(id).is_some(); // Settings and cache the store keeps for an id that isn't installed are deleted too. let stored = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.has_plugin_storage(id); diff --git a/crates/engine/src/cmd/plugin_call.rs b/crates/engine/src/cmd/plugin_call.rs index f4b91edd9b..71fbcc8540 100644 --- a/crates/engine/src/cmd/plugin_call.rs +++ b/crates/engine/src/cmd/plugin_call.rs @@ -413,6 +413,7 @@ pub(crate) fn transaction(s: &mut Session, label: &str, f: impl FnOnce(&mut Sess st.interaction = None; } saved.restore(s); + s.sync_front_profiles(); Err(e) } } diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 5958a84b53..8071c1df3d 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -478,6 +478,7 @@ pub(super) const ALLOWED: &[&str] = &[ "recolor.pickTheme", "recolor.randomize", "recolor.reduce", + "recolor.weigh", "select.add", "select.all", "select.allOnArtboard", diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index a73485f4fa..748e0a125a 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -454,10 +454,10 @@ pub fn spec(key: &str) -> Option<&'static PrefSpec> { /// Preferences kept as one object with a command of their own instead of [`PREF_SPECS`] rows (they /// aren't in the Preferences dialog): the Eyedropper Options (`eyedropper.setOptions`), the /// Perspective Grid Options (`perspective.widget.options`), the Pathfinder Options -/// (`object.pathfinder.options`) and the Snap to Glyph options (`view.snapToGlyph.options`). -/// `prefs.get` and `prefs.set` take them by key (a partial object updates what it names) and -/// `prefs.reset` without a category resets them. -pub const PREF_GROUPS: &[&str] = &["eyedropper", "perspectiveWidget", "pathfinder", "glyphSnap"]; +/// (`object.pathfinder.options`), the Snap to Glyph options (`view.snapToGlyph.options`) and the +/// Pixel Snapping Options (`view.snapToPixel.options`). `prefs.get` and `prefs.set` take them by key +/// (a partial object updates what it names) and `prefs.reset` without a category resets them. +pub const PREF_GROUPS: &[&str] = &["eyedropper", "perspectiveWidget", "pathfinder", "glyphSnap", "pixelSnap"]; /// Validate a value for preference group `key` against `current`. fn validate_group(key: &str, current: &Value, v: &Value) -> std::result::Result { @@ -477,6 +477,10 @@ fn validate_group(key: &str, current: &Value, v: &Value) -> std::result::Result< let cur: vectorcraft_tools::GlyphSnap = serde_json::from_value(current.clone()).unwrap_or_default(); cur.merged(v).map(|o| json!(o)) } + "pixelSnap" => { + let cur: vectorcraft_tools::PixelSnap = serde_json::from_value(current.clone()).unwrap_or_default(); + cur.merged(v).map(|o| json!(o)) + } "perspectiveWidget" => { let mut merged = current.clone(); if let (Some(o), Some(p)) = (merged.as_object_mut(), v.as_object()) { @@ -788,7 +792,7 @@ pub fn specs() -> Vec { "Export Preferences", [], None, - "{path?} write the preferences as a JSON file {format: \"vectorcraft-preferences\", version: 1, prefs: {key: value, …}}: every preference prefs.list lists and the eyedropper, perspectiveWidget, pathfinder and glyphSnap groups, without the folder preferences fontsFolder, pluginsFolder, recoveryFolder and templatesFolder and without saved presets; a file over 1 MB, which prefs.import would refuse, is an error and is not written → {path, count}; without path → {data: the file's text, count}", + "{path?} write the preferences as a JSON file {format: \"vectorcraft-preferences\", version: 1, prefs: {key: value, …}}: every preference prefs.list lists and the eyedropper, perspectiveWidget, pathfinder, glyphSnap and pixelSnap groups, without the folder preferences fontsFolder, pluginsFolder, recoveryFolder and templatesFolder and without saved presets; a file over 1 MB, which prefs.import would refuse, is an error and is not written → {path, count}; without path → {data: the file's text, count}", always, export ), diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index 931bcce681..8194f85547 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -7,7 +7,9 @@ use std::collections::{BTreeSet, HashMap}; use serde_json::{Value, json}; -use vectorcraft_color::recolor::{ColorKey, GlobalAdjust, Method, Preserve, Rng, RowMap, cluster, same_ink}; +use vectorcraft_color::recolor::{ + ColorKey, GlobalAdjust, Method, Preserve, Rng, RowMap, WeighUnit, cluster, row_shares, same_ink, weigh as weigh_rows, +}; use vectorcraft_color::{Color, Paint, Swatch}; use vectorcraft_doc::swatches::{node_colors, node_paints, override_paints}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; @@ -63,6 +65,15 @@ pub fn specs() -> Vec { has_doc, pick_theme ), + cmd!( + query "recolor.weigh", + "Prominent Colors", + [], + None, + "{map: rows [{from, to, …}] or {current: new} as recolor.apply, weights?: [numbers ≥ 0, one per row; an excluded row's is ignored, and at least one other must be above 0], ids?: as recolor.colors} → {map: the rows as given, each with its current colours (from) moved as below, shares: [one per row: its percent of the uses (recolor.colors' count) of the current colours of the rows that aren't excluded; 0 for an excluded row]} for Recolor Artwork's Prominent Colors (VectorCraft's own rule): without weights the rows stay as they are. With weights, current colours move one at a time between the rows that aren't excluded and have a new colour (to), while a move brings each row's share of the uses nearer its share of the weights, first the colour nearest in Lab to the first colour of the row it goes to compared with the row it leaves; a row's first colour stays in it, the tints of one global swatch in a row move together, a colour that another row with a new colour lists first stays where it is, the other rows with a new colour drop their entries for a colour that moves, and a use counts for the row recolor.apply recolors it with (rows with a new colour first, an exact colour before a hex one, the first row that lists it), else for the first other row that isn't excluded and lists it. The colours that can move are compared with the rows at most 50,000,000 times in all, and when they times the rows that aren't excluded pass that, none move. Changes nothing", + has_doc, + weigh + ), ] } @@ -1062,6 +1073,181 @@ fn colors(s: &mut Session, p: &Value) -> Result { Ok(json!({ "colors": v })) } +/// `recolor.weigh`'s rows as given, each with `from` as a list (a `{current: new}` map gives a +/// row per entry). The rows have already been read by [`parse_rows`]. +fn given_rows(p: &Value) -> Vec { + match p.get("map") { + Some(Value::Array(rows)) => rows + .iter() + .map(|r| { + let mut r = r.clone(); + if let Some(f) = r.get("from").filter(|f| !f.is_array()).cloned() { + r["from"] = json!([f]); + } + r + }) + .collect(), + Some(Value::Object(m)) => m.iter().map(|(k, v)| json!({"from": [k], "to": v})).collect(), + _ => vec![], + } +} + +fn weigh(s: &mut Session, p: &Value) -> Result { + const C: &str = "recolor.weigh"; + let rows = parse_rows(p, C)?; + let weights = match p.get("weights") { + None | Some(Value::Null) => None, + Some(Value::Array(a)) if a.len() == rows.len() => Some( + a.iter() + .map(|v| { + v.as_f64() + .filter(|x| x.is_finite() && *x >= 0.0) + .ok_or_else(|| bad(C, format!("each weight must be a number of 0 or more (got {v})"))) + }) + .collect::>>()?, + ), + Some(v) => return Err(bad(C, format!("`weights` must be a list of {} numbers, one per row (got {v})", rows.len()))), + }; + let active: Vec = (0..rows.len()).filter(|&i| !rows[i].exclude).collect(); + if let Some(w) = &weights + && !active.is_empty() + && !active.iter().any(|&i| w[i] > 0.0) + { + return Err(bad(C, "at least one row that isn't excluded needs a weight above 0")); + } + let (ids, only) = scope_ids(s, p, C)?; + let st = s.doc()?; + let mut used: Vec> = used_colors(&st.doc, &ids, only.as_ref()).into_iter().map(Some).collect(); + let mut by_key: HashMap = HashMap::new(); + let mut by_hex: HashMap> = HashMap::new(); + for (i, u) in used.iter().enumerate().filter_map(|(i, u)| Some((i, u.as_ref()?))) { + by_key.insert(ColorKey::of(&u.color), i); + by_hex.entry(u.color.to_hex()).or_default().push(i); + } + // Each current colour's uses and global swatch. A use counts where recolor.apply recolors it: + // rows with a new colour first, exact colours before hex colours, the first row that lists it; + // then the other rows that aren't excluded, in the same way. `owner` holds the row and entry that took each colour, + // and `shadows` the entries of rows with a new colour whose colours other entries took. + let mut owner: Vec> = vec![None; used.len()]; + let mut shadows: Vec<(usize, usize, Vec)> = vec![]; + let mut found: Vec)>> = rows.iter().map(|r| vec![(0, None); r.from.len()]).collect(); + for recolors in [true, false] { + for hex in [false, true] { + for (r, row) in rows.iter().enumerate().filter(|(_, r)| !r.exclude && r.new_color().is_some() == recolors) { + for (e, m) in row.from.iter().enumerate().filter(|(_, m)| matches!(m, Match::Hex(_)) == hex) { + let hits: Vec = match m { + Match::Key(k) => by_key.get(k).copied().into_iter().collect(), + Match::Hex(h) => by_hex.get(h).cloned().unwrap_or_default(), + }; + let (mut uses, mut link, mut took, mut taken) = (0, None, false, vec![]); + for i in hits { + match used[i].take() { + Some(u) => { + uses += u.count; + link = link.or(u.swatch); + took = true; + owner[i] = Some((r, e)); + } + None => taken.push(i), + } + } + found[r][e] = (uses, link); + if recolors && !took && !taken.is_empty() { + shadows.push((r, e, taken)); + } + } + } + } + } + // The units that move: in each row that isn't excluded, the colours linked to one global + // swatch go together, each other colour on its own, and the unit of the first colour stays. + let (mut units, mut members): (Vec, Vec<(usize, Vec)>) = (vec![], vec![]); + let mut unit_of: HashMap<(usize, usize), usize> = HashMap::new(); + for (n, &r) in active.iter().enumerate() { + let mut groups: Vec<(Option<&String>, Vec, usize)> = vec![]; + let mut by_link: HashMap<&String, usize> = HashMap::new(); + for (e, (uses, link)) in found[r].iter().enumerate() { + let g = match link { + Some(l) => *by_link.entry(l).or_insert_with(|| { + groups.push((Some(l), vec![], 0)); + groups.len() - 1 + }), + None => { + groups.push((None, vec![], 0)); + groups.len() - 1 + } + }; + groups[g].1.push(e); + groups[g].2 += uses; + } + for (k, (_, entries, uses)) in groups.into_iter().enumerate() { + for &e in &entries { + unit_of.insert((r, e), units.len()); + } + units.push(WeighUnit { color: rows[r].from[entries[0]].color(), uses: uses as f64, row: n, fixed: k == 0 }); + members.push((r, entries)); + } + } + // recolor.apply matches a colour to the first row with a new colour that lists it. A colour + // that another such row's first colour also lists stays where it is; another row's other + // entries for a colour that moves are dropped from that row below. + let owners = |taken: &[usize]| -> Vec { taken.iter().filter_map(|&i| unit_of.get(&owner[i]?).copied()).collect() }; + for (_, _, taken) in shadows.iter().filter(|(_, e, _)| *e == 0) { + for u in owners(taken) { + units[u].fixed = true; + } + } + if let Some(w) = &weights { + // Only rows with a new colour recolor what they hold, so only they give and take colours. + let movers: Vec = (0..active.len()).filter(|&n| rows[active[n]].new_color().is_some()).collect(); + let anchors: Vec = + movers.iter().map(|&n| rows[active[n]].from.first().map(Match::color).or(rows[active[n]].to).unwrap_or_default()).collect(); + let mut mover_of = vec![None; active.len()]; + for (m, &n) in movers.iter().enumerate() { + mover_of[n] = Some(m); + } + let at: Vec> = units.iter().map(|u| mover_of[u.row]).collect(); + let sub: Vec = units.iter().zip(&at).filter_map(|(u, m)| Some(WeighUnit { row: (*m)?, ..*u })).collect(); + let to = weigh_rows(&sub, &anchors, &movers.iter().map(|&n| w[active[n]]).collect::>()); + for ((u, _), m) in units.iter_mut().zip(&at).filter(|(_, m)| m.is_some()).zip(to) { + u.row = movers[m]; + } + } + let mut out = given_rows(p); + if weights.is_some() { + // Each row's colours: those that stayed, in their order, then those that came to it. + // A row's entry for a colour that moved to another row would take it back, so it goes. + let moved = |u: usize| active[units[u].row] != members[u].0; + let dropped: std::collections::HashSet<(usize, usize)> = + shadows.iter().filter(|(_, e, taken)| *e != 0 && owners(taken).into_iter().any(moved)).map(|(r, e, _)| (*r, *e)).collect(); + let old: Vec> = out.iter().map(|r| r["from"].as_array().cloned().unwrap_or_default()).collect(); + let mut stayed: Vec> = active.iter().map(|_| vec![]).collect(); + let mut came: Vec> = active.iter().map(|_| vec![]).collect(); + for (u, (r, entries)) in units.iter().zip(&members) { + let kept = entries.iter().copied().filter(|&e| !dropped.contains(&(*r, e))); + if active[u.row] == *r { + stayed[u.row].extend(kept); + } else { + came[u.row].extend(kept.filter_map(|e| old[*r].get(e).cloned())); + } + } + for (n, &r) in active.iter().enumerate() { + stayed[n].sort_unstable(); + let mut from: Vec = stayed[n].iter().filter_map(|&e| old[r].get(e).cloned()).collect(); + from.append(&mut came[n]); + if let Some(row) = out.get_mut(r) { + row["from"] = Value::Array(from); + } + } + } + let shares = row_shares(&units, active.len()); + let mut all = vec![0.0; rows.len()]; + for (n, &r) in active.iter().enumerate() { + all[r] = shares[n]; + } + Ok(json!({"map": out, "shares": all})) +} + /// The `method` parameter (`default` without one, or for null). A `method` that is not a string, /// such as `5`, names no method. fn method_param(p: &Value, cmd: &str, default: Method) -> Result { diff --git a/crates/engine/src/cmd/threads.rs b/crates/engine/src/cmd/threads.rs index 6c80c962d6..c1c3801e40 100644 --- a/crates/engine/src/cmd/threads.rs +++ b/crates/engine/src/cmd/threads.rs @@ -135,6 +135,7 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) { let mut story: Vec = vec![]; let mut sources: Vec = vec![]; let mut later_wins = vec![]; + let mut earlier_wins = vec![]; let mut live = vec![]; for id in &thread { match (text_of(doc, *id), text_of(before, *id)) { @@ -143,6 +144,9 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) { // A frame whose first paragraph was just restyled gives the paragraph it // shares with the frame before it that style. later_wins.push(old.is_some_and(|o| o.para_at(0) != t.para_at(0))); + // A frame whose last paragraph was just restyled keeps that style in the + // paragraph it shares with the frame after it, even when it is empty. + earlier_wins.push(old.is_some_and(|o| o.para_at(o.paragraph_count() - 1) != t.para_at(t.paragraph_count() - 1))); sources.push(t.clone()); live.push(*id); } @@ -151,6 +155,7 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) { (None, Some(old)) => { story.extend(old.runs.iter().cloned()); later_wins.push(false); + earlier_wins.push(false); sources.push(old.clone()); } (None, None) => {} @@ -160,7 +165,7 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) { continue; } let source_refs: Vec<&TextObject> = sources.iter().collect(); - let paras = vectorcraft_text::thread::story_paras(&source_refs, &later_wins); + let paras = vectorcraft_text::thread::story_paras_restyled(&source_refs, &later_wins, &earlier_wins); vectorcraft_text::edit::normalize(&mut story); if live.len() >= 2 { // Threaded frames keep their size: Auto Size is off for them (as in Illustrator). diff --git a/crates/engine/src/cmd/threads/tests.rs b/crates/engine/src/cmd/threads/tests.rs index b6ea41df3e..a622901c01 100644 --- a/crates/engine/src/cmd/threads/tests.rs +++ b/crates/engine/src/cmd/threads/tests.rs @@ -60,6 +60,130 @@ fn a_restyled_empty_frame_keeps_its_style_before_an_unedited_empty_frame() { assert_eq!([hyphenates(a, 0), hyphenates(a, 1), hyphenates(b, 0), hyphenates(c, 0)], [false, true, true, true]); } +/// Every paragraph's left indent in frame `id`. +fn left_indents(s: &Session, id: u64) -> Vec { + match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.paragraph_styles().iter().map(|p| p.left_indent).collect(), + _ => panic!("not text"), + } +} + +/// Area type `height` high holding `text`, threaded into `empties` empty rectangles after it. +fn tail_thread(text: &str, height: f64, empties: usize) -> (Session, Vec) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 300})).unwrap(); + let a = new_id(s.execute("text.create", &json!({"x": 10, "y": 10, "text": text, "area": {"width": 150, "height": height}})).unwrap()); + let mut ids = vec![a]; + for k in 0..empties { + let x = 200.0 * (k + 1) as f64; + ids.push(new_id(s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 150, "height": 60})).unwrap())); + } + s.execute("select.set", &json!({"ids": ids})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + (s, ids) +} + +/// Restyling a frame's empty last paragraph (after its final paragraph break) gives that +/// paragraph the style in the next frame as well, instead of the next frame's old style. +#[test] +fn editing_a_frames_empty_last_paragraph_survives_thread_reflow() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 300})).unwrap(); + let a = + s.execute("text.create", &json!({"x": 10, "y": 10, "text": "a\n", "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap(); + let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 60})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + assert_eq!([text(&s, a), text(&s, b)], ["a\n", ""]); + let steps = s.doc().unwrap().history.undo.len(); + s.execute("text.setFormat", &json!({"ids": [a], "start": 2, "end": 2, "leftIndent": 30})).unwrap(); + assert_eq!((left_indents(&s, a), left_indents(&s, b)), (vec![0.0, 30.0], vec![30.0])); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + // The same format again changes nothing and records no undo step. + s.execute("text.setFormat", &json!({"ids": [a], "start": 2, "end": 2, "leftIndent": 30})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((left_indents(&s, a), left_indents(&s, b)), (vec![0.0, 0.0], vec![0.0])); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!((left_indents(&s, a), left_indents(&s, b)), (vec![0.0, 30.0], vec![30.0])); + s.execute("edit.undo", &json!({})).unwrap(); + + // A format of the whole frame changes its last paragraph as well. + s.execute("text.setFormat", &json!({"ids": [a], "leftIndent": 20})).unwrap(); + assert_eq!((left_indents(&s, a), left_indents(&s, b)), (vec![20.0, 20.0], vec![20.0])); + // Both frames formatted in one command agree. + s.execute("text.setFormat", &json!({"ids": [a, b], "leftIndent": 40})).unwrap(); + assert_eq!((left_indents(&s, a), left_indents(&s, b)), (vec![40.0, 40.0], vec![40.0])); +} + +/// The restyled empty last paragraph keeps its style when the next frame holds text that +/// continues it, and across an unedited empty frame; a later restyle of a later frame still wins. +#[test] +fn a_restyled_empty_last_paragraph_keeps_its_style_against_later_frames() { + // One line high: the text added to the next frame stays there. + let (mut s, ids) = tail_thread("a\n", 20.0, 1); + let (a, b) = (ids[0], ids[1]); + s.execute("text.editRange", &json!({"id": b, "start": 0, "end": 0, "insert": "def"})).unwrap(); + assert_eq!([text(&s, a), text(&s, b)], ["a\n", "def"]); + s.execute("text.setFormat", &json!({"ids": [a], "start": 2, "end": 2, "leftIndent": 30})).unwrap(); + assert_eq!([text(&s, a), text(&s, b)], ["a\n", "def"]); + assert_eq!((left_indents(&s, a), left_indents(&s, b)), (vec![0.0, 30.0], vec![30.0])); + + let (mut s, ids) = tail_thread("a\n", 60.0, 2); + s.execute("text.setFormat", &json!({"ids": [ids[0]], "start": 2, "end": 2, "leftIndent": 30})).unwrap(); + assert_eq!(ids.iter().map(|id| left_indents(&s, *id)).collect::>(), [vec![0.0, 30.0], vec![30.0], vec![30.0]]); + s.execute("text.setFormat", &json!({"ids": [ids[2]], "leftIndent": 10})).unwrap(); + assert_eq!(ids.iter().map(|id| left_indents(&s, *id)).collect::>(), [vec![0.0, 10.0], vec![10.0], vec![10.0]]); +} + +/// The restyled last paragraph keeps its style with type on a path on either side of the boundary. +#[test] +fn a_restyled_empty_last_paragraph_flows_onto_type_on_a_path() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 300})).unwrap(); + let a = new_id(s.execute("text.create", &json!({"x": 10, "y": 10, "text": "a\n", "area": {"width": 150, "height": 60}})).unwrap()); + let on_path = type_on_a_line(&mut s); + s.execute("text.thread.add", &json!({"from": a, "to": on_path})).unwrap(); + assert_eq!([text(&s, a), text(&s, on_path)], ["a\n", ""]); + s.execute("text.setFormat", &json!({"ids": [a], "start": 2, "end": 2, "leftIndent": 30})).unwrap(); + assert_eq!((left_indents(&s, a), left_indents(&s, on_path)), (vec![0.0, 30.0], vec![30.0])); + + // Type on a path before area type. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 300})).unwrap(); + let on_path = type_on_a_line(&mut s); + s.execute("text.editRange", &json!({"id": on_path, "start": 0, "end": 0, "insert": "a\n"})).unwrap(); + let b = new_id(s.execute("shape.rectangle", &json!({"x": 400, "y": 10, "width": 150, "height": 60})).unwrap()); + s.execute("text.thread.add", &json!({"from": on_path, "to": b})).unwrap(); + assert_eq!([text(&s, on_path), text(&s, b)], ["a\n", ""]); + s.execute("text.setFormat", &json!({"ids": [on_path], "start": 2, "end": 2, "leftIndent": 30})).unwrap(); + assert_eq!((left_indents(&s, on_path), left_indents(&s, b)), (vec![0.0, 30.0], vec![30.0])); +} + +/// A restyled empty last paragraph in a numbered list is counted once, and the next frame's +/// first paragraph does not continue the paragraph before the break. +#[test] +fn a_restyled_empty_last_list_paragraph_keeps_the_counts() { + let (mut s, ids) = tail_thread("One\nTwo\n", 60.0, 1); + let (a, b) = (ids[0], ids[1]); + s.execute("text.setFormat", &json!({"ids": [a, b], "list": "number"})).unwrap(); + s.execute("text.setFormat", &json!({"ids": [a], "start": 8, "end": 8, "leftIndent": 30})).unwrap(); + let doc = &s.doc().unwrap().doc; + let frame = |id| match &doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("not text"), + }; + let (ta, tb) = (frame(a), frame(b)); + let shown = [ta.plain_text(), tb.plain_text()].concat(); + assert_eq!(shown, "One\nTwo\n"); + let split = ta.paragraph_count() - 1; + assert_eq!(ta.para_at(split).left_indent, 30.0, "{:?}", [ta.plain_text(), tb.plain_text()]); + assert_eq!(tb.para_at(0).left_indent, 30.0); + assert!(tb.para_at(0).list.is_some()); + assert_eq!(tb.list_count as usize, split, "the paragraphs before the shared one are counted once"); + assert_eq!(tb.first_para_continues, !ta.plain_text().ends_with('\n')); +} + #[test] fn thread_flows_reflows_on_edit_and_survives_delete() { let (mut s, a, b) = setup(); diff --git a/crates/engine/src/cmd/views.rs b/crates/engine/src/cmd/views.rs index 560da3942c..6e26e9a9e6 100644 --- a/crates/engine/src/cmd/views.rs +++ b/crates/engine/src/cmd/views.rs @@ -1,5 +1,6 @@ //! View → New View… / Edit Views…: saved views stored in the document; per-document view -//! toggles (Show Transparency Grid); the Character panel's Snap to Glyph options. +//! toggles (Show Transparency Grid); the Character panel's Snap to Glyph options; the Pixel +//! Snapping Options. use serde_json::{Value, json}; use vectorcraft_apischema::{Bound, Param, ParamSchema, Type, Writes}; @@ -72,6 +73,18 @@ static GLYPH_SNAP: ParamSchema = ParamSchema::new( .returns("the options") .writes(Writes::Preferences); +static PIXEL_SNAP: ParamSchema = ParamSchema::new( + &[ + Param::new("drawing", Type::Boolean).optional(), + Param::new("moving", Type::Boolean).optional(), + Param::new("scaling", Type::Boolean).optional(), + ], + "the Pixel Snapping Options, kept in the preferences (the pixelSnap group, all on by default): which edits View › Snap to Pixel lands on whole pixels: drawing (the points the drawing tools place, the rulers' origin and measured points), moving (the selection, its anchors and segments, artboards and ruler guides moved, and the Rotate, Reflect and Shear tools' drags) and scaling (the edges a bounding-box, Free Transform, artboard or slice handle drags, and the Scale tool's drag); an edit whose option is off snaps as it does with Snap to Pixel off; {} reads them", +) +.returns("the options") +.writes(Writes::Preferences) +.since(4); + pub fn specs() -> Vec { vec![ cmd!( @@ -125,6 +138,16 @@ pub fn specs() -> Vec { glyph_snap_options, schema: &GLYPH_SNAP ), + cmd!( + query "view.snapToPixel.options", + "Pixel Snapping Options", + [], + None, + "{drawing?: bool, moving?: bool, scaling?: bool} the Pixel Snapping Options, kept in the preferences (the pixelSnap group, all on by default): which edits View › Snap to Pixel lands on whole pixels: drawing (the points the drawing tools place, the rulers' origin and measured points), moving (the selection, its anchors and segments, artboards and ruler guides moved, and the Rotate, Reflect and Shear tools' drags) and scaling (the edges a bounding-box, Free Transform, artboard or slice handle drags, and the Scale tool's drag); an edit whose option is off snaps as it does with Snap to Pixel off; {} reads them → the options", + always, + pixel_snap_options, + schema: &PIXEL_SNAP + ), ] } @@ -133,6 +156,11 @@ fn glyph_snap_options(s: &mut Session, p: &Value) -> Result { Ok(json!(s.prefs.glyph_snap)) } +fn pixel_snap_options(s: &mut Session, p: &Value) -> Result { + s.prefs.pixel_snap = s.prefs.pixel_snap.merged(p).map_err(|e| bad("view.snapToPixel.options", e))?; + Ok(json!(s.prefs.pixel_snap)) +} + fn caps_lock(s: &mut Session, p: &Value) -> Result { if let Some(on) = p.get("on") { s.caps_lock = on.as_bool().ok_or_else(|| bad("view.capsLock", "on must be true or false"))?; @@ -379,15 +407,17 @@ mod tests { ("view.saved.list", json!({"all": true}), "`all`"), ("view.transparencyGrid", json!({"on": 1}), "`on`"), ("view.snapToGlyph.options", json!({"bounds": "off"}), "`bounds`"), + ("view.snapToPixel.options", json!({"moving": "off"}), "`moving`"), + ("view.snapToPixel.options", json!({"drawing": false, "rotating": false}), "`rotating`"), ] { let st = s.doc().unwrap(); let doc = (st.doc.views.clone(), st.history.undo.len(), st.is_dirty()); - let (grid, caps, snap) = (st.transparency_grid, s.caps_lock, s.prefs.glyph_snap); + let (grid, caps, snap, pixel) = (st.transparency_grid, s.caps_lock, s.prefs.glyph_snap, s.prefs.pixel_snap); let e = s.execute(id, ¶ms).unwrap_err().to_string(); assert!(e.contains(id) && e.contains(named), "{id} {params}: {e}"); let st = s.doc().unwrap(); assert_eq!((&st.doc.views, st.history.undo.len(), st.is_dirty()), (&doc.0, doc.1, doc.2), "{id} {params}"); - assert_eq!((st.transparency_grid, s.caps_lock, s.prefs.glyph_snap), (grid, caps, snap), "{id} {params}"); + assert_eq!((st.transparency_grid, s.caps_lock, s.prefs.glyph_snap, s.prefs.pixel_snap), (grid, caps, snap, pixel), "{id} {params}"); } } diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs index a17fbaf3f8..89642a6e19 100644 --- a/crates/engine/src/command_sets.rs +++ b/crates/engine/src/command_sets.rs @@ -19,7 +19,9 @@ pub const ON_ACTIVE_ARTBOARD: [&str; 8] = [ /// The commands that resize the artboards the app passes (Object › Artboards): the app passes the /// selected artboards to Fit to Artwork Bounds as its `indices`, and the active artboard to Fit to /// Selected Art as its `index`. A `command.batch` given `artboard` passes it on, as `index`, to -/// each of their steps that names none. +/// each of their steps that names none; a Fit to Artwork Bounds step that names neither `index` nor +/// `indices`, while the Artboard tool is chosen with several artboards selected, gets those as its +/// `indices` instead. pub const FIT_ACTIVE_ARTBOARD: [&str; 2] = ["artboard.fitToArt", "artboard.fitToSelection"]; /// `(command, param)` pairs the journal records only so a replay reproduces the original run diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 3c3460ecb2..e3f2b91ee7 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -286,6 +286,9 @@ pub struct Session { /// While the active tool's actions run: their commands aren't "a command from outside the /// tool" ([`Session::after_command`]). pub(crate) in_tool_actions: bool, + /// The warnings of the previews that settling an interaction applied, while a top-level command + /// or the tool's actions collect them ([`Session::collect_settled_warnings`]). + settled_warnings: Option>, /// While [`Session::preview`] runs its command: its edits are the interaction's own. previewing: bool, /// The images Remove Background decoded during the interaction's preview steps, emptied when diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 05ef5e84f5..98813e999f 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -260,6 +260,9 @@ pub struct Prefs { /// Character panel › Show Snap to Glyph Options: which guides View › Snap to Glyph gives /// (`view.snapToGlyph.options`; a preference group, see [`cmd::prefscmds::PREF_GROUPS`]). pub glyph_snap: vectorcraft_tools::GlyphSnap, + /// Pixel Snapping Options: whether View › Snap to Pixel snaps drawing, moving and scaling + /// (`view.snapToPixel.options`; a preference group, see [`cmd::prefscmds::PREF_GROUPS`]). + pub pixel_snap: vectorcraft_tools::PixelSnap, /// Edit → Transparency Flattener Presets: the user's presets (the built-in ones aren't stored). /// Not a `prefs.set` key or group (resetting the preferences keeps them): `flattener.presets.*` /// edit it. @@ -523,6 +526,7 @@ impl Default for Prefs { eyedropper: Default::default(), pathfinder: Default::default(), glyph_snap: Default::default(), + pixel_snap: Default::default(), flattener_presets: vec![], trace_presets: vec![], gradient_presets: vec![], diff --git a/crates/engine/src/schemas.rs b/crates/engine/src/schemas.rs index 08bc0f719d..8be87b5ab8 100644 --- a/crates/engine/src/schemas.rs +++ b/crates/engine/src/schemas.rs @@ -26,10 +26,11 @@ use crate::cmd::{CommandSpec, bad, command_specs}; use crate::{EngineError, Result}; /// The API level of the commands' parameters. -pub const API_VERSION: u32 = 3; +pub const API_VERSION: u32 = 4; /// [`schema_hash`] at each API level, oldest first; the last row is [`API_VERSION`]'s. -pub const SCHEMA_HASHES: &[(u32, u64)] = &[(1, 0x9cdb_1087_7074_855c), (2, 0x0e31_5d96_7bc9_2653), (3, 0xffe0_58a3_2f0c_aa2a)]; +pub const SCHEMA_HASHES: &[(u32, u64)] = + &[(1, 0x9cdb_1087_7074_855c), (2, 0x0e31_5d96_7bc9_2653), (3, 0xffe0_58a3_2f0c_aa2a), (4, 0x1be4_be72_fe16_54c4)]; /// The hash of every built-in command's schema ([`vectorcraft_apischema::hash`]). pub fn schema_hash() -> u64 { @@ -311,12 +312,17 @@ mod tests { ("view.transparencyGrid", json!({"on": 1})), ("view.snapToGlyph.options", json!({"bounds": false, "angular": true})), ("view.snapToGlyph.options", json!({"bounds": null})), + ("view.snapToPixel.options", json!({"drawing": false, "scaling": true})), + ("view.snapToPixel.options", json!({"moving": null})), + ("view.snapToPixel.options", json!({"moving": "off"})), + ("view.snapToPixel.options", json!({"rotating": false})), ("view.capsLock", json!(null)), ("view.saved.new", json!(null)), ("view.saved.edit", json!(null)), ("view.saved.list", json!(null)), ("view.transparencyGrid", json!(null)), ("view.snapToGlyph.options", json!(null)), + ("view.snapToPixel.options", json!(null)), ("view.capsLock", json!([])), ("view.saved.new", json!(5)), ("view.transparencyGrid", json!("on")), @@ -325,7 +331,7 @@ mod tests { ("engine.apiReference", json!({"prefix": "view."})), ("engine.apiReference", json!([])), ]; - assert_eq!(schemas().len(), 7); + assert_eq!(schemas().len(), 8); for (id, schema) in schemas() { let written = schema.to_json(); check_schema(&written, id).unwrap_or_else(|e| panic!("{e}\n{written:#}")); @@ -423,6 +429,7 @@ mod tests { ("view.saved.list", "nothing"), ("view.transparencyGrid", "session"), ("view.snapToGlyph.options", "preferences"), + ("view.snapToPixel.options", "preferences"), ]; for (id, writes) in expected { let got = listed.iter().find(|(c, _)| *c == id).map(|(_, w)| w.clone()); diff --git a/crates/engine/src/script/include.rs b/crates/engine/src/script/include.rs index 4ec68dbbde..f1928228df 100644 --- a/crates/engine/src/script/include.rs +++ b/crates/engine/src/script/include.rs @@ -321,7 +321,8 @@ impl Files { std::env::var("JSINCLUDE").map(|v| v.split(';').map(str::trim).filter(|p| !p.is_empty()).map(PathBuf::from).collect()).unwrap_or_default() } - /// The file being run now, as `$.fileName` gives it (empty for a script given as text). + /// The file being run now: the script, or the file `$.evalFile` is running (empty for a script + /// given as text). `$.fileName` gives it to code that `eval` or `Function` compiled. pub(crate) fn file_name(&self) -> String { self.frames.last().map(|f| f.shown.to_string()).unwrap_or_default() } diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 53f6e18f75..ed5cd0f52d 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -672,6 +672,7 @@ impl Savepoint { s.pending_paint = self.pending_paint; self.choices.put(s); s.journal.truncate(self.journal); + s.sync_front_profiles(); exact } } @@ -822,6 +823,29 @@ impl Host { } } + /// `$.fileName` read by the code at `site`: the file that code is in, by the source map of the + /// source it came from (this run's script, a file `$.evalFile` gave, or code an earlier run of + /// the named engine compiled), so a function keeps the file it was defined in. Code from a file + /// `#include` inserted is in that file. A script given as text has no name, and neither has + /// code whose map the named engine no longer keeps. Code that `eval` or `Function` compiled has + /// no map, and is given the file being run now. + fn file_name_at(&self, site: vectorcraft_js::CallSite) -> String { + let name = |m: &include::SourceMap| m.locate(site.line, site.column).1.to_string(); + let tag = site.source; + if tag == vectorcraft_js::UNKNOWN_SOURCE { + return self.files.borrow().file_name(); + } + let script = self.script_tag.get(); + match tag.checked_sub(script).filter(|_| script != vectorcraft_js::UNKNOWN_SOURCE) { + Some(0) => name(&self.script_map.borrow()), + Some(n) => self.eval_maps.borrow().get(n as usize - 1).map(name).unwrap_or_default(), + None => { + let kept = self.kept_maps.as_ref().map(|k| k.borrow()); + kept.as_ref().and_then(|k| k.get(tag)).map(|k| name(&k.map)).unwrap_or_default() + } + } + } + /// Adds a line to the run's console and, during a slice, to the session's. fn line(&self, entry: console::Entry, cut: bool) { let line = console::ConsoleLine { run: self.run, name: self.name.clone(), entry }; @@ -1254,9 +1278,9 @@ fn each_line(text: &str, mut done: impl FnMut(String, bool)) { /// The `$` object: `$.write(...values)` writes the values to the Script Console as `String(value)` /// gives them, one after another, and `$.writeln(...values)` does the same and ends the line. -/// `$.evalFile(path[, timeout])` runs a file and gives its last value, `$.fileName` is the file -/// being run and `$.includePath` the `#includepath` list. Its other members are -/// [`dollar::members`]. +/// `$.evalFile(path[, timeout])` runs a file and gives its last value, `$.fileName` is the file the +/// code reading it is in ([`Host::file_name_at`]) and `$.includePath` the `#includepath` list. Its +/// other members are [`dollar::members`]. fn dollar_object(link: &Link, info: dollar::RunInfo, localization: &Rc) -> Vec<(String, HostItem)> { let writer = |end: bool| { let l = link.clone(); @@ -1278,6 +1302,15 @@ fn dollar_object(link: &Link, info: dollar::RunInfo, localization: &Rc String { fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result, String> { let depth = std::mem::replace(&mut s.depth, 0); job.world.swap(s); + // The run's front document draws and converts through its own profiles, and the interface's + // again after the slice. + s.sync_front_profiles(); s.script_in_run = true; let cell = job.host.session.clone(); std::mem::swap(s, &mut *cell.borrow_mut()); @@ -2221,6 +2257,7 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result self.refresh_document_text_bounds(index, |t| t.cached_bounds.is_none() && !sets_in_any(t, &names)), - None => self.sync_opened_composite_fonts(index), + None => { + self.sync_opened_composite_fonts(index); + self.sync_front_profiles(); + } } true } @@ -403,6 +418,7 @@ impl Session { } self.active = if self.docs.is_empty() { None } else { Some(index.min(self.docs.len() - 1)) }; self.sync_front_composite_fonts(); + self.sync_front_profiles(); true } diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 3d0d9ba1c6..73977f7d64 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -234,6 +234,27 @@ impl Session { self.active().and_then(|d| d.interaction.as_ref().filter(|it| std::sync::Arc::ptr_eq(&it.doc, &d.doc)).and_then(|it| it.preview.clone())) } + /// Keep `warning`, from a preview that settling an interaction applied, for whatever collects + /// such warnings now ([`Session::collect_settled_warnings`]). Nothing keeps it when nothing + /// collects, so it is never reported with a later, unrelated command. + pub(crate) fn note_settled_warning(&mut self, warning: &str) { + if let Some(kept) = &mut self.settled_warnings + && !kept.iter().any(|w| w == warning) + { + kept.push(warning.to_string()); + } + } + + /// Run `f`, and → its result with the warnings of the previews that settling an interaction + /// applied while it ran ([`Session::note_settled_warning`]). Warnings an outer `f` collects are + /// kept for it. + pub(crate) fn collect_settled_warnings(&mut self, f: impl FnOnce(&mut Self) -> R) -> (R, Vec) { + let outer = self.settled_warnings.replace(Vec::new()); + let r = f(self); + let settled = std::mem::replace(&mut self.settled_warnings, outer).unwrap_or_default(); + (r, settled) + } + pub fn begin_interaction(&mut self, label: &str) -> Result<()> { if self.script_running() { return Err(EngineError::Busy); @@ -311,6 +332,8 @@ impl Session { self.paint = paint.clone(); } self.pending_paint = None; + // The previous preview's Assign Profile is undone with it. + self.sync_front_profiles(); let rw = cmd::distortcmds::perspective_rewrite(self, cmd, params).or_else(|| cmd::bounds_rewrite(self, cmd, params)); let (cmd, params) = rw.as_ref().map_or((cmd, params), |(c, p)| (c.as_str(), p)); // A selected object's converted appearance must not replace the current paints while @@ -436,6 +459,8 @@ impl Session { st.undo_interaction(); // Guides locked and slices locked or hidden during the interaction stay deselected. deselect_hidden(&menu, &st.doc, &mut st.selection); + // A canceled preview's Assign Profile is undone with it. + self.sync_front_profiles(); // With New Art Has Basic Appearance off, new art takes the appearance of the selection as // the document has it again, not as a preview left it. self.inherit_new_art(); diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 23079fe901..d6e85cbdd9 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -3,6 +3,27 @@ use super::{ strip_replay_only, waits_for_tool_edit, }; +/// A command's result `r` with the warnings of the previews that settling an interaction applied +/// before it ran: `previewWarning` holds them, and `warning` too when the command gives none of its +/// own, so the status bar shows the command's own warning when there is one. A null result becomes +/// an object holding them; any other result that isn't an object is returned as it is. +fn with_settled_warnings(mut r: Value, settled: &[String]) -> Value { + if settled.is_empty() { + return r; + } + if r.is_null() { + r = Value::Object(serde_json::Map::new()); + } + if let Value::Object(m) = &mut r { + let w = Value::String(settled.join("; ")); + if m.get("warning").is_none_or(Value::is_null) { + m.insert("warning".into(), w.clone()); + } + m.insert("previewWarning".into(), w); + } + r +} + impl Session { /// `spec`'s `enabled` with `ids` selected instead of the selection, which is then put back. fn enabled_with_selection(&mut self, spec: &CommandSpec, ids: Vec) -> std::result::Result<(), String> { @@ -54,7 +75,14 @@ impl Session { self.finish_tool_edit_later()?; } let outer = std::mem::replace(&mut self.reading, !spec.journal || JOURNALED_READS.contains(&id)); - let r = self.execute_spec(spec, id, params); + // A preview that a top-level command applied first (a drag with Real-time Drawing off, kept + // before Undo) reports its warning in the command's result. + let r = if self.depth == 0 { + let (r, settled) = self.collect_settled_warnings(|s| s.execute_spec(spec, id, params)); + r.map(|v| with_settled_warnings(v, &settled)) + } else { + self.execute_spec(spec, id, params) + }; self.reading = outer; r } @@ -168,6 +196,10 @@ impl Session { let (doc, journal, grouped) = (self.active().map(|d| d.uid), self.journal.len(), self.undo_group_docs()); let open = (self.depth == 0).then(|| self.docs.iter().map(|d| d.uid).collect::>()); let r = if self.depth == 0 { self.run_guarded(id, run) } else { self.run_nested(run) }; + // Colors are drawn and converted through the profiles of the document in front now, also + // after an undone or redone Assign Profile, a failed or panicked command's documents put + // back, and a batch step, before the next step converts through them. + self.sync_front_profiles(); if r.is_err() && self.depth == 0 { self.batch_paint_docs.clear(); // A failed or panicked command's documents are put back: type is drawn in their @@ -364,3 +396,25 @@ impl Session { r } } + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::with_settled_warnings; + + /// The command's own warning stays the one the status bar shows, and the settled preview's is + /// kept beside it; a null result holds the preview's; other results are left as they are. + #[test] + fn settled_warnings_join_the_result() { + let settled = ["a".to_string(), "b".to_string()]; + assert_eq!( + with_settled_warnings(json!({"ran": 1, "warning": "own"}), &settled), + json!({"ran": 1, "warning": "own", "previewWarning": "a; b"}) + ); + assert_eq!(with_settled_warnings(json!({"warning": null}), &settled), json!({"warning": "a; b", "previewWarning": "a; b"})); + assert_eq!(with_settled_warnings(json!(null), &settled[..1]), json!({"warning": "a", "previewWarning": "a"})); + assert_eq!(with_settled_warnings(json!([1]), &settled), json!([1])); + assert_eq!(with_settled_warnings(json!({"ran": 1}), &[]), json!({"ran": 1})); + } +} diff --git a/crates/engine/src/session/undo.rs b/crates/engine/src/session/undo.rs index d06934926c..3af4cafe5f 100644 --- a/crates/engine/src/session/undo.rs +++ b/crates/engine/src/session/undo.rs @@ -164,6 +164,10 @@ impl Session { if self.depth == 0 { self.trim_histories(); } + // A canceled group's Assign Profile is undone with it. + if cancel { + self.sync_front_profiles(); + } } /// When journal entry `n` is a `command.batch` with `steps` noted in canceled undo groups and @@ -280,5 +284,7 @@ impl Session { g.journal.retain(|&(n, _)| n < scope.journal); g.steps.retain(|&(n, _)| n < scope.journal); } + // A canceled scope's Assign Profile is undone with it. + self.sync_front_profiles(); } } diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index 4943353ee0..8a18ce9824 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -421,6 +421,8 @@ impl Session { if safe_mode::active() { return; } + // A `plugin.install` in another session writes the store before this reads it. + let _held = crate::cmd::plugin::hold_plugin_changes(); let grants = self.counted_grants(&dir); let limits = vectorcraft_plugins::Limits::default(); let mut left = MAX_PLUGIN_STORE; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 2352776651..6c231dc7e5 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4033,6 +4033,38 @@ fn snap_to_pixel_rounds_drawing_and_moves() { assert_eq!((b.x0, b.y0), (17.0, 16.0)); } +/// Pixel Snapping Options (`view.snapToPixel.options`): with While Drawing off a rectangle drawn +/// with Snap to Pixel on keeps its fractional corners while a move still lands on whole pixels, and +/// with While Moving off a move keeps its fractional offset while drawing snaps again. +#[test] +fn pixel_snapping_options_choose_the_edits_snap_to_pixel_rounds() { + let mut s = session(); + let v = ViewInfo { snap_to_pixel: true, smart_guides: false, snap_to_point: false, ..Default::default() }; + let drag = |s: &mut Session, tool: &str, from: (f64, f64), to: (f64, f64)| { + s.select_tool(tool, v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, from.0, from.1), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, to.0, to.1), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, to.0, to.1), v).unwrap(); + }; + let bounds = |s: &Session, id| { + let b = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap(); + (b.x0, b.y0, b.x1, b.y1) + }; + s.execute("view.snapToPixel.options", &json!({"drawing": false})).unwrap(); + drag(&mut s, "rectangle", (10.25, 10.5), (60.5, 40.25)); + let id = s.doc().unwrap().selection.objects[0]; + assert_eq!(bounds(&s, id), (10.25, 10.5, 60.5, 40.25), "drawing does not snap"); + drag(&mut s, "selection", (30.0, 30.0), (37.5, 34.75)); + assert_eq!(bounds(&s, id).0, 18.0, "moving still snaps the left edge"); + assert_eq!(bounds(&s, id).1, 15.0, "moving still snaps the top edge"); + s.execute("view.snapToPixel.options", &json!({"drawing": true, "moving": false})).unwrap(); + drag(&mut s, "selection", (40.0, 30.0), (45.25, 33.5)); + assert_eq!((bounds(&s, id).0, bounds(&s, id).1), (23.25, 18.5), "moving does not snap"); + drag(&mut s, "rectangle", (100.25, 100.5), (140.5, 130.75)); + let drawn = s.doc().unwrap().selection.objects[0]; + assert_eq!(bounds(&s, drawn), (100.0, 101.0, 141.0, 131.0), "drawing snaps again"); +} + #[test] fn shaper_turns_rough_strokes_into_live_shapes_and_scribbles_punch_fills() { let mut s = session(); diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 49a806b258..21cbf678eb 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -3788,6 +3788,103 @@ fn a_trace_run_needs_the_library_colours_it_traced_with() { assert!(!run.current(&s), "{name} changed"); } +/// `image_doc`'s image with its disc 20 px to the left: the same size, other pixels. +fn moved_disc_png() -> Vec { + vectorcraft_trace::Raster::from_fn(100, 100, |x, y| { + let (dx, dy) = (x as f64 + 0.5 - 30.0, y as f64 + 0.5 - 50.0); + if dx * dx + dy * dy <= 900.0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] } + }) + .encode_png() +} + +/// Puts `bytes` under the image key `key`, or takes the key's image data away (`None`). +fn set_image_data(s: &mut Session, key: &str, bytes: Option>) { + s.edit("image data", |d, _| { + match bytes { + Some(b) => d.images.insert(key.into(), ImageBlob::new("image/png", b)), + None => d.images.remove(key), + }; + Ok(()) + }) + .unwrap(); +} + +/// The middle of the first traced path of the Image Trace object the reply `r` names, in x. +fn traced_center_x(s: &Session, r: &Value) -> f64 { + outline(&traced_paths(&node(s, NodeId(r["id"].as_u64().unwrap())))[0]).0.bounds().unwrap().center().x +} + +/// A trace made away from its command no longer applies once the pixels under its image's key +/// change, though the object, its image record and the settings stay as they were; both commands +/// then trace the pixels there now. The same bytes in another allocation still apply. +#[test] +fn a_trace_run_needs_the_pixels_it_traced() { + let p = json!({"params": {"ignoreWhite": true}}); + for command in ["imageTrace.make", "imageTrace.makeAndExpand"] { + let mut s = session(); + image_doc(&mut s); + let run = cmd::TraceRun::prepare(&s, command, &p).unwrap(); + let traced = run.run(&|_, _| true).unwrap(); + // The same bytes, allocated anew: still current. + let same = s.doc().unwrap().doc.images["img1"].bytes.to_vec(); + set_image_data(&mut s, "img1", Some(same)); + assert!(run.current(&s), "{command}: equal bytes"); + // Other pixels under the same key: no longer current, and the hand-off is dropped. + set_image_data(&mut s, "img1", Some(moved_disc_png())); + assert!(!run.current(&s), "{command}: other pixels"); + traced.hand_in(&mut s); + let r = s.execute(command, run.params()).unwrap(); + assert!(s.trace_hand_off.is_none(), "{command}: dropped"); + // The disc is now at image x 30, which the ×2 placement at 50 puts at 110. + let x = traced_center_x(&s, &r); + assert!((x - 110.0).abs() < 1.5, "{command}: traced the pixels there now, at {x}"); + } +} + +/// Image data that is missing or empty: a run made before it went no longer applies, the run's +/// command gives the error it gives without a run, and nothing panics. +#[test] +fn a_trace_run_of_missing_or_empty_image_data() { + let p = json!({"params": {"ignoreWhite": true}}); + let mut s = session(); + image_doc(&mut s); + let run = cmd::TraceRun::prepare(&s, "imageTrace.make", &p).unwrap(); + let traced = run.run(&|_, _| true).unwrap(); + set_image_data(&mut s, "img1", None); + assert!(!run.current(&s), "missing"); + traced.hand_in(&mut s); + let e = s.execute(run.command(), run.params()).unwrap_err().to_string(); + assert!(e.contains("image data `img1` is missing"), "{e}"); + set_image_data(&mut s, "img1", Some(vec![])); + assert!(!run.current(&s), "empty"); + let empty = cmd::TraceRun::prepare(&s, "imageTrace.make", &p).unwrap(); + assert!(empty.current(&s), "two empty blobs are equal"); + assert!(matches!(empty.run(&|_, _| true), Err(EngineError::Other(_)))); + assert!(matches!(s.execute(run.command(), run.params()), Err(EngineError::Other(_)))); +} + +/// Tracing an Image Trace object again follows the same rule: once the pixels of the image it +/// holds change, a run made before no longer applies, and the command traces the pixels there now. +#[test] +fn a_trace_run_of_an_image_trace_object_needs_its_pixels() { + let p = json!({"params": {"ignoreWhite": true}}); + let mut s = session(); + image_doc(&mut s); + let g = s.execute("imageTrace.make", &p).unwrap()["id"].as_u64().unwrap(); + let again = json!({"id": g, "params": {"ignoreWhite": true}}); + let run = cmd::TraceRun::prepare(&s, "imageTrace.make", &again).unwrap(); + assert_eq!(run.target(), NodeId(g)); + let traced = run.run(&|_, _| true).unwrap(); + assert!(run.current(&s)); + set_image_data(&mut s, "img1", Some(moved_disc_png())); + assert!(!run.current(&s)); + traced.hand_in(&mut s); + let r = s.execute(run.command(), run.params()).unwrap(); + assert!(s.trace_hand_off.is_none(), "dropped"); + let x = traced_center_x(&s, &r); + assert!((x - 110.0).abs() < 1.5, "traced the pixels there now, at {x}"); +} + /// Shapes: the disc of the test image comes out as a live ellipse where the image lies, the same /// circle as its traced path; without the option it is a plain path. #[test] diff --git a/crates/engine/src/tests/dcs.rs b/crates/engine/src/tests/dcs.rs index c801401de0..5c806884d8 100644 --- a/crates/engine/src/tests/dcs.rs +++ b/crates/engine/src/tests/dcs.rs @@ -326,6 +326,31 @@ fn update_link_takes_the_files_clipping_path_into_symbols_too() { assert_eq!(symbol_clip_width(&s, "Pic"), None); } +#[test] +fn update_and_relink_by_id_keep_the_clipping_path_of_a_dcs_image_in_a_symbol() { + let dir = temp_dir("symbol-clip-by-id"); + 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(); + s.execute("symbol.new", &json!({ "name": "Pic", "ids": [r["ids"][0]] })).unwrap(); + let list = s.execute("links.list", &json!({})).unwrap(); + let row = list["links"].as_array().unwrap().iter().find(|r| r["owner"]["kind"] == "symbol").cloned().expect("the symbol's image is listed"); + let id = row["id"].as_u64().unwrap(); + assert_eq!(row["format"], "DCS", "{list}"); + let before = symbol_clip_width(&s, "Pic").expect("the file's clipping path"); + // The composite now drawn through the left quarter of the page (same length). + let text = String::from_utf8(two_plates()).unwrap().replacen("10 0 lineto 10 10 lineto", " 5 0 lineto 5 10 lineto", 1); + std::fs::write(&path, text.as_bytes()).unwrap(); + assert_eq!(s.execute("links.update", &json!({ "ids": [id] })).unwrap()["updated"], json!([id])); + let after = symbol_clip_width(&s, "Pic").expect("still clipped"); + assert!((after - before / 2.0).abs() < 1e-6, "the symbol's clipping path follows the file: {before} → {after}"); + // Relinked by its id to a plain image: the DCS file's clipping path goes. + let png = dir.join("plain.png"); + image::RgbImage::from_pixel(2, 2, image::Rgb([9, 9, 9])).save(&png).unwrap(); + s.execute("links.relink", &json!({ "ids": [id], "path": png.to_string_lossy() })).unwrap(); + assert_eq!(symbol_clip_width(&s, "Pic"), None); +} + #[test] fn a_file_that_lost_its_clipping_path_unclips_the_image() { let dir = temp_dir("update-lost-clip"); diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index fbf1b22d4a..a9035de1da 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -1367,6 +1367,37 @@ fn smooth_tool_reduces_jagged_path() { assert_eq!(p.subpaths[0].anchors[0].p, Point::new(100.0, 200.0)); } +/// A drag of the Smooth tool along a line jagged by up to 6 pt leaves no corner between a curve and +/// a line: every anchor between the path's ends turns by at most 1°. +#[test] +fn smooth_tool_leaves_no_corner_where_a_curve_meets_a_line() { + let mut s = session(); + let mut seed = 7u64; + let anchors: Vec<_> = (0..=60) + .map(|i| { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + let noise = ((seed >> 11) as f64 / (1u64 << 53) as f64) * 2.0 - 1.0; + json!({"x": 100.0 + f64::from(i) * 5.0, "y": 200.0 + 6.0 * noise}) + }) + .collect(); + let r = s.execute("path.create", &json!({"anchors": anchors})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + let drag_points: Vec<(f64, f64)> = (0..=64).map(|i| (90.0 + f64::from(i) * 5.0, 200.0)).collect(); + drag(&mut s, "smooth", &drag_points, Mods::default()); + let p = path(&s, id); + let sp = &p.subpaths[0]; + assert!(sp.anchors.len() < 61, "the path is smoothed: {}", sp.anchors.len()); + let dir = |v: kurbo::Vec2, w: kurbo::Vec2, chord: kurbo::Vec2| [v, w, chord].into_iter().find(|d| d.hypot() > 1e-9).unwrap_or(chord); + for i in 1..sp.segment_count() { + let (prev, next) = (sp.segment(i - 1), sp.segment(i)); + let arrive = dir(prev.p3 - prev.p2, prev.p3 - prev.p1, prev.p3 - prev.p0); + let leave = dir(next.p1 - next.p0, next.p2 - next.p0, next.p3 - next.p0); + let turn = arrive.cross(leave).atan2(arrive.dot(leave)).abs().to_degrees(); + let kinds = (sp.segment_is_line(i - 1), sp.segment_is_line(i)); + assert!(turn <= 1.0, "anchor {i} turns {turn}° (lines before and after: {kinds:?}): {:?}", sp.anchors[i]); + } +} + /// Smoothing a path with direct-selected anchors leaves the path selected whole: the selection no /// longer names anchors by indices into the anchors the smooth replaced. A selected path the drag /// does not reach keeps its anchors selected, and undo brings the old selection back. @@ -1412,6 +1443,169 @@ fn a_short_smooth_drag_leaves_the_rest_of_long_segments_alone() { } } +/// A selected path through `anchors` (x, y, and the in and out handles when given). +fn smooth_test_path(s: &mut Session, anchors: &[serde_json::Value], closed: bool) -> NodeId { + let r = s.execute("path.create", &json!({"anchors": anchors, "closed": closed})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + id +} + +/// `path.smoothRegion` along `drag` with the Smooth tool's reach (12 pt at 100%) and default Fidelity. +fn smooth_pass(s: &mut Session, drag: &[Point]) { + let pts: Vec<_> = drag.iter().map(|p| json!([p.x, p.y])).collect(); + s.execute("path.smoothRegion", &json!({"points": pts, "radius": 12, "fidelity": 2.5})).unwrap(); +} + +/// Points 1/32 of a segment apart along every segment of `p`. +fn smooth_test_samples(p: &PathData) -> Vec { + use kurbo::ParamCurve; + let mut v = vec![]; + for sp in &p.subpaths { + for i in 0..sp.segment_count() { + let c = sp.segment(i); + v.extend((0..32).map(|k| c.eval(f64::from(k) / 32.0))); + } + } + v +} + +/// How much `p` turns along its length, in radians: a wobbly path turns much more than a smooth one. +fn total_turning(p: &PathData) -> f64 { + let pts = smooth_test_samples(p); + pts.windows(3) + .map(|w| (w[1] - w[0], w[2] - w[1])) + .filter(|(u, v)| u.hypot() > 1e-9 && v.hypot() > 1e-9) + .map(|(u, v)| u.cross(v).atan2(u.dot(v)).abs()) + .sum() +} + +/// Deterministic noise in -1..1. +fn smooth_noise(seed: &mut u64) -> f64 { + *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (*seed >> 11) as f64 / (1u64 << 53) as f64 * 2.0 - 1.0 +} + +/// A drag along y = `y` from x = `x0` to `x1`, one point every 5 pt. +fn smooth_drag_along(y: f64, x0: f64, x1: f64) -> Vec { + let n = ((x1 - x0) / 5.0).ceil() as usize; + (0..=n).map(|i| Point::new(x0 + (x1 - x0) * i as f64 / n as f64, y)).collect() +} + +/// Each drag of the Smooth tool smooths the path under it, and a second drag over the same place +/// smooths it further, as the help page describes +/// (https://helpx.adobe.com/illustrator/using/tool-techniques/smooth-tool.html): a curve that wobbles +/// 4 pt either side of its line every 12 pt, with an anchor at each crest, wobbles less after each drag. +#[test] +fn each_smooth_drag_smooths_a_wobble_larger_than_fidelity_further() { + let mut s = session(); + let anchors: Vec<_> = (0..=20) + .map(|k| { + let (x, y) = (100.0 + 12.0 * f64::from(k), if k % 2 == 0 { 196.0 } else { 204.0 }); + json!({"x": x, "y": y, "in": [x - 4.4, y], "out": [x + 4.4, y]}) + }) + .collect(); + let id = smooth_test_path(&mut s, &anchors, false); + let drag = smooth_drag_along(200.0, 90.0, 350.0); + let wobble = + |p: &PathData| smooth_test_samples(p).iter().filter(|q| (130.0..=310.0).contains(&q.x)).map(|q| (q.y - 200.0).abs()).fold(0.0, f64::max); + let mut before = path(&s, id); + for pass in 1..=2 { + smooth_pass(&mut s, &drag); + let after = path(&s, id); + assert_ne!(after, before, "pass {pass} changes the path"); + let (t0, t1) = (total_turning(&before), total_turning(&after)); + assert!(t1 < 0.9 * t0, "pass {pass}: turning {t0} -> {t1}"); + let (w0, w1) = (wobble(&before), wobble(&after)); + assert!(w1 < 0.8 * w0, "pass {pass}: wobble {w0} -> {w1}"); + let (a, b) = (before.subpaths[0].anchors[0].p, after.subpaths[0].anchors[0].p); + assert_eq!(a, b, "pass {pass}: the path keeps its start"); + before = after; + } +} + +/// Smoothing a line with up to 1 pt of noise again and again, over all of it or over its middle, +/// keeps it close to the line under the noise: each refit stays near the path it smooths. +#[test] +fn repeated_smooth_drags_stay_close_to_the_line_under_the_noise() { + let off = |p: &PathData| { + let d: Vec = smooth_test_samples(p).iter().map(|q| (q.y - 200.0).abs()).collect(); + (d.iter().sum::() / d.len() as f64, d.iter().copied().fold(0.0, f64::max)) + }; + for (x0, x1) in [(90.0, 410.0), (150.0, 350.0)] { + let mut s = session(); + let mut seed = 7u64; + let anchors: Vec<_> = (0..=60).map(|i| json!({"x": 100.0 + 5.0 * f64::from(i), "y": 200.0 + smooth_noise(&mut seed)})).collect(); + let id = smooth_test_path(&mut s, &anchors, false); + let drag = smooth_drag_along(200.0, x0, x1); + let (mean0, _) = off(&path(&s, id)); + for pass in 1..=5 { + smooth_pass(&mut s, &drag); + let (mean, max) = off(&path(&s, id)); + assert!( + mean <= 1.1 * mean0 && max <= 1.5, + "drag {x0}-{x1}, pass {pass}: {mean} on average and {max} at most from the line, {mean0} before" + ); + } + } +} + +/// A drag over the whole of a noisy closed path leaves no corner where the path starts. +#[test] +fn smoothing_a_whole_closed_path_leaves_no_kink_at_its_start() { + let mut s = session(); + let mut seed = 5u64; + let (c, r) = (Point::new(300.0, 300.0), 80.0); + let anchors: Vec<_> = (0..64) + .map(|i| { + let a = f64::from(i) / 64.0 * std::f64::consts::TAU; + let rr = r + 2.5 * smooth_noise(&mut seed); + json!({"x": c.x + rr * a.cos(), "y": c.y + rr * a.sin()}) + }) + .collect(); + let id = smooth_test_path(&mut s, &anchors, true); + let ring: Vec = (0..=128).map(|i| f64::from(i) / 128.0 * std::f64::consts::TAU).map(|a| c + r * kurbo::Vec2::from_angle(a)).collect(); + smooth_pass(&mut s, &ring); + let p = path(&s, id); + let sp = &p.subpaths[0]; + assert!(sp.closed && sp.anchors.len() < 64, "{} anchors", sp.anchors.len()); + let (last, first) = (sp.segment(sp.segment_count() - 1), sp.segment(0)); + let tin = if last.p3.distance(last.p2) > 1e-9 { last.p3 - last.p2 } else { last.p3 - last.p1 }; + let tout = if first.p1.distance(first.p0) > 1e-9 { first.p1 - first.p0 } else { first.p2 - first.p0 }; + let kink = tin.cross(tout).atan2(tin.dot(tout)).abs().to_degrees(); + assert!(kink <= 1.0, "a {kink}° corner at the start"); +} + +/// A drag over the whole of a closed path smooths a bump at its first anchor as much as the same +/// bump on the far side of it. +#[test] +fn smoothing_a_whole_closed_path_smooths_a_bump_at_its_start() { + let mut s = session(); + let (c, r) = (Point::new(300.0, 300.0), 80.0); + let anchors: Vec<_> = (0..64) + .map(|i| { + let a = f64::from(i) / 64.0 * std::f64::consts::TAU; + let rr = if i % 32 == 0 { r + 6.0 } else { r }; + json!({"x": c.x + rr * a.cos(), "y": c.y + rr * a.sin()}) + }) + .collect(); + let id = smooth_test_path(&mut s, &anchors, true); + let ring: Vec = (0..=128).map(|i| f64::from(i) / 128.0 * std::f64::consts::TAU).map(|a| c + r * kurbo::Vec2::from_angle(a)).collect(); + // A Fidelity of 0.5 pt, so the refit follows the smoothed path closely on both sides. + let pts: Vec<_> = ring.iter().map(|p| json!([p.x, p.y])).collect(); + s.execute("path.smoothRegion", &json!({"points": pts, "radius": 12, "fidelity": 0.5})).unwrap(); + let p = path(&s, id); + use std::f64::consts::{PI, TAU}; + // How far the path rises above the circle within 0.3 radians of the angle `near`. + let bump = |near: f64| { + let off = |q: &Point| (((q.y - c.y).atan2(q.x - c.x) - near + PI).rem_euclid(TAU) - PI).abs(); + smooth_test_samples(&p).iter().filter(|q| off(q) < 0.3).map(|q| q.distance(c) - r).fold(0.0, f64::max) + }; + let (start, far) = (bump(0.0), bump(PI)); + assert!(far < 5.0, "the far bump stays {far} pt high"); + assert!(start <= far + 0.5, "the bump at the start stays {start} pt high, the far one {far} pt"); +} + #[test] fn join_tool_joins_two_lines() { let mut s = session(); @@ -2555,6 +2749,49 @@ fn remove_anchor_points_selects_one_next_anchor_per_subpath_and_per_path() { assert_eq!(selected_anchors(&s, other), [(0, 0)]); } +#[test] +fn remove_anchor_points_on_many_paths_and_subpaths_matches_removing_one_at_a_time() { + // Many anchors over many subpaths and paths, curved and straight, open and closed: each + // subpath ends as removing its anchors one at a time, the last first, leaves it. Paths left + // with nothing go, the rest stay selected in order, and one undo step brings all back. + let mut s = session(); + let curvy = "M0 0 C10 20 30 20 40 0 C50 -20 70 -20 80 0 C90 20 110 20 120 0 C130 -20 150 -20 160 0 Z \ + M0 100 L40 120 C60 140 80 80 100 100 L140 90 L180 110 L220 100"; + let ids: Vec = (0..4).map(|i| path_from(&mut s, if i == 2 { "M0 0 L10 0 L20 5" } else { curvy })).collect(); + let picks: [&[(usize, usize)]; 4] = + [&[(0, 0), (0, 2), (0, 3), (1, 1), (1, 2), (1, 5)], &[(0, 1), (1, 0), (1, 6)], &[(0, 0), (0, 1)], &[(0, 3), (1, 3), (1, 4)]]; + for (k, (&id, &anchors)) in ids.iter().zip(&picks).enumerate() { + let mode = if k == 0 { "set" } else { "add" }; + s.execute("select.anchors", &json!({"id": id.0, "anchors": anchors, "mode": mode})).unwrap(); + } + let before: Vec = ids.iter().map(|&id| path(&s, id)).collect(); + assert_eq!(s.execute("path.removeAnchors", &json!({})).unwrap()["removedObjects"], 1); + for (k, &id) in ids.iter().enumerate() { + let mut want = before[k].clone(); + let mut order = picks[k].to_vec(); + order.sort_unstable_by(|a, b| b.cmp(a)); + for (si, ai) in order { + vectorcraft_pathops::remove_anchor(&mut want.subpaths[si], ai); + } + want.subpaths.retain(|sp| sp.anchors.len() >= 2); + if want.subpaths.is_empty() { + assert!(s.doc().unwrap().doc.node(id).is_none(), "path {k} goes"); + } else { + assert_eq!(path(&s, id).subpaths, want.subpaths, "path {k}"); + } + } + let kept = [ids[0], ids[1], ids[3]]; + assert_eq!(s.doc().unwrap().selection.objects, kept); + s.execute("edit.undo", &json!({})).unwrap(); + for (k, &id) in ids.iter().enumerate() { + assert_eq!(path(&s, id), before[k]); + assert_eq!(selected_anchors(&s, id), picks[k]); + } + s.execute("edit.redo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(ids[2]).is_none()); + assert_eq!(s.doc().unwrap().selection.objects, kept); +} + #[test] fn remove_anchor_point_tool_and_delete_still_select_the_remainder_whole() { // Only Remove Anchor Points moves the selection on. The Delete Anchor Point tool leaves the diff --git a/crates/engine/src/tests/expand.rs b/crates/engine/src/tests/expand.rs index 3fd187016f..d853b91110 100644 --- a/crates/engine/src/tests/expand.rs +++ b/crates/engine/src/tests/expand.rs @@ -535,9 +535,9 @@ fn expanded_art_keeps_the_random_transforms_the_canvas_drew() { } /// The reply lists each object whose appearance expanded once, by the id it has in the document, -/// starting with the selected object. In "group copies" the two copies of the square share an id -/// until Expand Appearance gives them ids of their own, and the reply names the group, then each -/// copy by its new id. +/// starting with the selected object. In "group copies" the group's art holds the square with its +/// stroke's effect applied, so the reply names the group alone; the two copies of the square share +/// ids until Expand Appearance gives every object in them an id of its own. #[test] fn the_reply_names_each_expanded_copy_by_its_own_id() { for case in RANDOM_CASES { @@ -551,8 +551,17 @@ fn the_reply_names_each_expanded_copy_by_its_own_id() { assert!(ids.iter().all(|&i| s.doc().unwrap().doc.node(NodeId(i)).is_some()), "{case}: {ids:?}"); if case == "group copies" { let art = node(&s, id); - let copies: Vec = art.children().unwrap()[0].children().unwrap().iter().map(|c| c.id.0).collect(); - assert_eq!(ids, [vec![id.0], copies].concat(), "{case}"); + assert_eq!(ids, [id.0], "{case}"); + let copies = art.children().unwrap(); + assert_eq!(copies.len(), 2, "{case}"); + let mut seen = std::collections::HashSet::new(); + let mut repeated = vec![]; + art.walk(&mut |n| { + if !seen.insert(n.id) { + repeated.push(n.id); + } + }); + assert!(repeated.is_empty(), "{case}: {repeated:?}"); } } } diff --git a/crates/engine/src/tests/journal.rs b/crates/engine/src/tests/journal.rs index f6ee8015be..5eb66ec6c8 100644 --- a/crates/engine/src/tests/journal.rs +++ b/crates/engine/src/tests/journal.rs @@ -192,6 +192,87 @@ fn fit_steps_take_the_batchs_artboard_and_actions_leave_out_their_index() { assert_eq!(action, [fit("artboard.fitToArt"), fit("artboard.fitToArt"), fit("artboard.fitToSelection")]); } +/// A document of three artboards with art of its own on each → its artboards before any fit. +fn three_artboards_with_art(s: &mut Session) -> Vec { + s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3, "created": null})).unwrap(); + for (x, h) in [(10, 30), (130, 20), (250, 40)] { + s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": h})).unwrap(); + } + s.execute("select.all", &json!({})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect() +} + +/// The artboards of [`three_artboards_with_art`], each fitted to its art. +fn three_fitted_artboards() -> [vectorcraft_geom::Rect; 3] { + let rect = vectorcraft_geom::Rect::new; + [rect(10.0, 10.0, 30.0, 40.0), rect(130.0, 10.0, 150.0, 30.0), rect(250.0, 10.0, 270.0, 50.0)] +} + +/// A Fit to Artwork Bounds step that names neither `index` nor `indices`, while the Artboard tool +/// is chosen with several artboards selected, fits each of those (not the batch's artboard), as the +/// command does on its own; a step's own `index` or `indices` wins, and with one artboard or none +/// selected the step takes the batch's artboard. +#[test] +fn a_batch_fit_step_uses_the_artboard_tool_selection() { + let fitted = three_fitted_artboards(); + let boards = |s: &Session| s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect::>(); + let fit = |params: Value| json!({"artboard": 1, "commands": [{"command": "artboard.fitToArt", "params": params}]}); + let session = |picks: &Value| { + let mut s = Session::new(); + let was = three_artboards_with_art(&mut s); + s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); + s.set_tool_option("selected", picks); + (s, was) + }; + let (mut s, was) = session(&json!([2, 0])); + s.execute("command.batch", &fit(json!({}))).unwrap(); + assert_eq!(boards(&s), [fitted[0], was[1], fitted[2]], "artboards 1 and 3, the selected ones, and not the batch's artboard 2"); + let (mut s, was) = session(&json!([2, 0])); + s.execute("command.batch", &fit(json!({"index": 1}))).unwrap(); + assert_eq!(boards(&s), [was[0], fitted[1], was[2]], "a step's own index"); + let (mut s, was) = session(&json!([2, 0])); + s.execute("command.batch", &fit(json!({"indices": [1, 2]}))).unwrap(); + assert_eq!(boards(&s), [was[0], fitted[1], fitted[2]], "a step's own indices"); + for picks in [json!([2]), json!([])] { + let (mut s, was) = session(&picks); + s.execute("command.batch", &fit(json!({}))).unwrap(); + assert_eq!(boards(&s), [was[0], fitted[1], was[2]], "the batch's artboard with {picks} selected"); + } +} + +/// The journal records the artboards a batch's Fit to Artwork Bounds step took from the Artboard +/// tool, so a replay in a new session fits the same ones; an action leaves them out and fits the +/// artboards selected when it plays. +#[test] +fn a_batch_fit_selection_replays_but_an_action_uses_the_current_selection() { + let fitted = three_fitted_artboards(); + let boards = |s: &Session| s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect::>(); + let mut s = Session::new(); + let was = three_artboards_with_art(&mut s); + s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); + s.set_tool_option("selected", &json!([0, 2])); + let start = s.journal.len(); + let steps = json!([{"command": "artboard.fitToArt", "params": {}}]); + s.execute("command.batch", &json!({"artboard": 1, "commands": steps})).unwrap(); + assert_eq!(boards(&s), [fitted[0], was[1], fitted[2]]); + let (id, p) = s.journal.last().unwrap().clone(); + assert_eq!((id.as_str(), &p["commands"][0]["params"]), ("command.batch", &json!({"indices": [0, 2]}))); + let r = replayed(&s); + assert_ne!(r.tool_id(), "artboard", "the new session's tool selects no artboards"); + assert_eq!(boards(&r), boards(&s), "the replay fits the recorded artboards"); + let action = s.journal_for_action(start); + assert_eq!(action, [("command.batch".to_string(), json!({"commands": steps}))]); + // Played on a fresh copy of the document with other artboards selected. + let mut a = Session::new(); + three_artboards_with_art(&mut a); + a.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); + a.set_tool_option("selected", &json!([1, 2])); + a.execute("command.batch", &json!({"artboard": 0, "commands": action[0].1["commands"]})).unwrap(); + assert_eq!(boards(&a), [was[0], fitted[1], fitted[2]], "the action fits the artboards selected when it plays"); +} + #[test] fn a_save_records_its_date_and_replays_it() { let path = vectorcraft_testkit::temp_dir("journal-save").join("a.vectorcraft").to_string_lossy().into_owned(); diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index 9787401285..e683b156e1 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -5,7 +5,7 @@ use std::path::{Path, PathBuf}; use serde_json::{Value, json}; -use vectorcraft_doc::{Document, ImageObject, LinkInfo, NodeKind}; +use vectorcraft_doc::{Document, ImageObject, LinkInfo, NodeKind, StoredRoot}; use vectorcraft_geom::Rect; use crate::*; @@ -446,8 +446,8 @@ fn links_outside_the_layers_find_their_files_after_the_folder_moves() { } /// With Update Links: Automatically, a file in a symbol and in the layers that changed and moved -/// with the document is read again for the layers' image and for the symbol's, and both links take -/// its new path, size and hash. +/// with the document is read again for the layers' image and for the symbol's, both are listed by +/// their ids, and both links take its new path, size and hash. #[test] fn a_symbols_link_to_a_moved_and_modified_file_takes_its_new_path() { let a = Folder::new("nested-modified-a"); @@ -458,13 +458,14 @@ fn a_symbols_link_to_a_moved_and_modified_file_takes_its_new_path() { s.execute("prefs.set", &json!({"key": "updateLinks", "value": "automatically"})).unwrap(); let id = place(&mut s, &pic); s.execute("symbol.new", &json!({"name": "Mark", "ids": [id.0]})).unwrap(); + let in_symbol = stored_image_in(&s, StoredRoot::Symbol(0)); let id = place(&mut s, &pic); save(&mut s, &a.file("poster.vectorcraft")); write(&pic, &png(30, 30, BLUE)); std::fs::remove_dir_all(&b.0).unwrap(); std::fs::rename(&a.0, &b.0).unwrap(); let r = open(&mut s, &b.file("poster.vectorcraft")); - assert_eq!((r["modifiedLinks"].clone(), r["updatedLinks"][0]["ids"].clone()), (json!([]), json!([id.0])), "{r}"); + assert_eq!((r["modifiedLinks"].clone(), r["updatedLinks"][0]["ids"].clone()), (json!([]), json!([id.0, in_symbol.0])), "{r}"); let moved = PathBuf::from(b.file("art/photo.png")); let blue = png(30, 30, BLUE); let mut images = vec![]; @@ -521,7 +522,8 @@ fn a_symbols_link_without_a_relative_path_follows_the_moved_file() { /// Update Links reads a changed file again for the images inside symbols, patterns and opacity /// masks too: those showing the same content as an image in the layers, and those no object in the -/// layers shows. Each takes the file's place as its own Placement Options say, in one undo step. +/// layers shows. Each takes the file's place as its own Placement Options say, in one undo step, +/// and the reply lists each by its id. #[test] fn update_links_reads_files_again_inside_symbols_patterns_and_masks() { let dir = Folder::new("nested-update"); @@ -533,11 +535,13 @@ fn update_links_reads_files_again_inside_symbols_patterns_and_masks() { let id = place(&mut s, &photo); s.execute("links.placementOptions", &json!({"ids": [id.0], "preserve": "fill", "clip": true})).unwrap(); s.execute("symbol.new", &json!({"name": "Mark", "ids": [id.0]})).unwrap(); + let in_symbol = stored_image_in(&s, StoredRoot::Symbol(0)); let id = place(&mut s, &photo); // logo.png only in a pattern and in an opacity mask. let p = place(&mut s, &logo); s.execute("object.pattern.make", &json!({"ids": [p.0], "edit": false})).unwrap(); s.execute("edit.clear", &json!({"ids": [p.0]})).unwrap(); + let p = stored_image_in(&s, StoredRoot::Pattern { pattern: 0, art: 0 }); let masked = super::rect(&mut s, 10.0, 10.0, 60.0, 60.0); let mask = place(&mut s, &logo); s.execute("transparency.makeOpacityMask", &json!({"ids": [masked.0, mask.0]})).unwrap(); @@ -546,7 +550,8 @@ fn update_links_reads_files_again_inside_symbols_patterns_and_masks() { write(&photo, &blue); write(&logo, &green); let u = s.execute("links.update", &json!({})).unwrap(); - assert_eq!(u, json!({"updated": [id.0], "missing": []})); + // By file: photo.png in the layers and the symbol, then logo.png in the mask and the pattern. + assert_eq!(u, json!({"updated": [id.0, in_symbol.0, mask.0, p.0], "missing": []})); // (name, size, hash, pixel size) of each image, which shows its file's pixels. let images = |s: &Session| { let d = &s.doc().unwrap().doc; @@ -576,6 +581,193 @@ fn update_links_reads_files_again_inside_symbols_patterns_and_masks() { assert!(images(&s).iter().all(|(_, _, _, size)| *size == (20, 10)), "{:?}", images(&s)); } +/// The files only art outside the layers shows: one in a symbol, a graph design, a pattern and an +/// opacity mask each, no object in the layers linked to any of them. +const NESTED: [&str; 4] = ["symbol.png", "design.png", "pattern.png", "mask.png"]; + +/// A document whose only links are [`NESTED`]'s files in `dir`. +fn nested_links(dir: &Folder) -> Session { + for (i, name) in (0u8..).zip(NESTED) { + write(&dir.file(name), &png(20, 10, [20 + 50 * i, 90, 160])); + } + let mut s = session(); + let id = place(&mut s, &dir.file("symbol.png")); + s.execute("symbol.new", &json!({"name": "Mark", "ids": [id.0]})).unwrap(); + s.execute("edit.clear", &json!({"ids": [s.doc().unwrap().selection.objects[0].0]})).unwrap(); + let id = place(&mut s, &dir.file("design.png")); + s.execute("graph.design", &json!({"new": "Bar"})).unwrap(); + s.execute("edit.clear", &json!({"ids": [id.0]})).unwrap(); + let id = place(&mut s, &dir.file("pattern.png")); + s.execute("object.pattern.make", &json!({"ids": [id.0], "edit": false})).unwrap(); + s.execute("edit.clear", &json!({"ids": [id.0]})).unwrap(); + let masked = super::rect(&mut s, 10.0, 10.0, 60.0, 60.0); + let mask = place(&mut s, &dir.file("mask.png")); + s.execute("transparency.makeOpacityMask", &json!({"ids": [masked.0, mask.0]})).unwrap(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + s +} + +/// The id of the `links.list` row of file `name`. +fn row_id(s: &mut Session, name: &str) -> u64 { + let list = s.execute("links.list", &json!({})).unwrap(); + let row = list["links"].as_array().unwrap().iter().find(|r| r["name"] == name).unwrap_or_else(|| panic!("{name} in {list}")); + row["id"].as_u64().unwrap() +} + +/// The link of stored object `id`. +fn stored_link(s: &Session, id: u64) -> Option { + match &s.doc().unwrap().doc.stored_node(NodeId(id)).unwrap().0.kind { + NodeKind::Image(im) => im.link.clone(), + k => panic!("not an image: {k:?}"), + } +} + +/// The id of the first image stored in the art of `root`. +fn stored_image_in(s: &Session, root: StoredRoot) -> NodeId { + let mut found = None; + s.doc().unwrap().doc.visit_stored(|n, place| { + if found.is_none() && place.root == root && matches!(n.kind, NodeKind::Image(_)) { + found = Some(n.id); + } + }); + found.unwrap_or_else(|| panic!("no image in {root:?}")) +} + +/// Images in symbols, graph designs, patterns and opacity masks are listed and checked with ids of +/// their own, one row each with what holds it, and the missing filter counts them. +#[test] +fn links_outside_the_layers_are_listed_and_checked_with_ids() { + let dir = Folder::new("nested-ids"); + let mut s = nested_links(&dir); + let list = s.execute("links.list", &json!({})).unwrap(); + let rows = list["links"].as_array().unwrap(); + let owners: Vec<(&str, &str)> = rows.iter().map(|r| (r["name"].as_str().unwrap(), r["owner"]["kind"].as_str().unwrap_or("-"))).collect(); + assert_eq!(owners, [("mask.png", "layers"), ("symbol.png", "symbol"), ("design.png", "graphDesign"), ("pattern.png", "pattern")], "{list}"); + assert_eq!(rows[1]["owner"]["name"], "Mark"); + let masked = s.doc().unwrap().doc.layers[0].children().unwrap().iter().find(|n| n.extras().mask.is_some()).unwrap().id; + assert_eq!(rows[0]["owner"]["maskOf"], json!(masked.0)); + let ids: std::collections::BTreeSet = rows.iter().map(|r| r["id"].as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 4, "{list}"); + assert!(rows.iter().all(|r| r["status"] == "ok" && r["linked"] == true), "{list}"); + let check = s.execute("links.check", &json!({})).unwrap(); + let checked: Vec<(&str, &Value)> = check["links"].as_array().unwrap().iter().map(|l| (l["name"].as_str().unwrap(), &l["ids"])).collect(); + assert_eq!(checked.len(), 4, "{check}"); + for (name, ids) in checked { + assert_eq!(*ids, json!([row_id(&mut s, name)]), "{check}"); + } + std::fs::remove_file(dir.file("design.png")).unwrap(); + let check = s.execute("links.check", &json!({})).unwrap(); + assert_eq!((check["missing"].as_u64(), check["modified"].as_u64()), (Some(1), Some(0)), "{check}"); + let design = row_id(&mut s, "design.png"); + let missing = s.execute("links.list", &json!({"show": "missing"})).unwrap(); + assert_eq!((missing["missing"].as_u64(), &missing["links"][0]["id"]), (Some(1), &json!(design)), "{missing}"); + let one = s.execute("links.check", &json!({"ids": [design]})).unwrap(); + assert_eq!(one["links"][0]["status"], "missing", "{one}"); +} + +/// Every links command takes the id of an image outside the layers and acts on that object: Link +/// Info, Go To (which clears the selection and names the symbol), Placement Options, Relink, Update and +/// Embed. +#[test] +fn links_commands_act_on_images_outside_the_layers_by_id() { + let dir = Folder::new("nested-act"); + let mut s = nested_links(&dir); + let symbol = row_id(&mut s, "symbol.png"); + let info = s.execute("links.info", &json!({"id": symbol})).unwrap(); + assert_eq!((info["fileName"].as_str(), info["status"].as_str(), info["id"].as_u64()), (Some("symbol.png"), Some("ok"), Some(symbol)), "{info}"); + let other = super::rect(&mut s, 0.0, 0.0, 5.0, 5.0); + s.execute("select.set", &json!({"ids": [other.0]})).unwrap(); + let go = s.execute("links.goTo", &json!({"id": symbol})).unwrap(); + assert_eq!( + (go["onCanvas"].clone(), go["owner"]["kind"].clone(), go["owner"]["name"].clone()), + (json!(false), json!("symbol"), json!("Mark")), + "{go}" + ); + assert!(s.doc().unwrap().selection.objects.is_empty(), "nothing on the canvas is selected"); + s.execute("links.placementOptions", &json!({"ids": [symbol], "preserve": "fit"})).unwrap(); + let placement = s.execute("links.placementOptions", &json!({"ids": [symbol]})).unwrap(); + assert_eq!(placement["placement"]["preserve"], "fit"); + // Relink: the symbol's image shows the new file. + let other = dir.file("other.png"); + write(&other, &png(40, 20, BLUE)); + let r = s.execute("links.relink", &json!({"ids": [symbol], "path": other})).unwrap(); + assert_eq!(r["relinked"], json!([symbol]), "{r}"); + assert_eq!(stored_link(&s, symbol).unwrap().path, other); + // Update: a changed pattern file is read again for the pattern's image. + let pattern = row_id(&mut s, "pattern.png"); + let changed = png(30, 30, RED); + write(&dir.file("pattern.png"), &changed); + let r = s.execute("links.update", &json!({"ids": [pattern]})).unwrap(); + assert_eq!(r["updated"], json!([pattern]), "{r}"); + assert_eq!(stored_link(&s, pattern).unwrap().size, Some(changed.len() as u64)); + // Embed: the design's image keeps its pixels and no longer links. + let design = row_id(&mut s, "design.png"); + let r = s.execute("links.embed", &json!({"ids": [design]})).unwrap(); + assert_eq!(r["embedded"], json!([design]), "{r}"); + assert!(stored_link(&s, design).is_none()); + let row = s.execute("links.list", &json!({"show": "embedded"})).unwrap(); + assert_eq!(row["links"][0]["id"], json!(design), "{row}"); + // Relink All Instances takes the other stored objects linked to the same file. + let mask = row_id(&mut s, "mask.png"); + let r = s.execute("links.relink", &json!({"ids": [symbol], "path": dir.file("mask.png"), "scope": "all"})).unwrap(); + assert_eq!(r["relinked"], json!([symbol]), "{r}"); + let r = s.execute("links.relink", &json!({"ids": [mask], "path": other, "scope": "all"})).unwrap(); + let mut relinked: Vec = r["relinked"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + relinked.sort(); + let mut both = vec![symbol, mask]; + both.sort(); + assert_eq!(relinked, both, "{r}"); +} + +/// Opening a document reports missing and modified files that only art outside the layers shows, +/// by their objects' ids, and those ids stay the same after the document is saved and opened again. +#[test] +fn open_reports_links_outside_the_layers_by_id() { + let dir = Folder::new("nested-open"); + let mut s = nested_links(&dir); + let path = dir.file("poster.vectorcraft"); + save(&mut s, &path); + let ids: Vec = NESTED.iter().map(|name| row_id(&mut s, name)).collect(); + std::fs::remove_file(dir.file("symbol.png")).unwrap(); + write(&dir.file("pattern.png"), &png(30, 30, RED)); + let r = open(&mut s, &path); + let names = |k: &str| r[k].as_array().unwrap().iter().map(|l| (l["name"].as_str().unwrap().to_string(), l["ids"].clone())).collect::>(); + assert_eq!(names("missingLinks"), [("symbol.png".to_string(), json!([ids[0]]))], "{r}"); + assert_eq!(names("modifiedLinks"), [("pattern.png".to_string(), json!([ids[2]]))], "{r}"); + let again: Vec = NESTED.iter().map(|name| row_id(&mut s, name)).collect(); + assert_eq!(again, ids, "the ids are saved"); +} + +/// A document whose symbol and mask art repeat the ids of objects in the layers (or have none) +/// opens with ids of their own there, the layer tree's kept; the links commands then tell them apart. +#[test] +fn nested_objects_that_repeat_ids_open_with_ids_of_their_own() { + let dir = Folder::new("nested-repeat"); + let mut s = nested_links(&dir); + let layer_image = place(&mut s, &dir.file("symbol.png")); + let path = dir.file("poster.vectorcraft"); + save(&mut s, &path); + // The symbol's image takes the id of the image in the layers, the mask's image none. + let mut saved: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + saved["document"]["symbols"][0]["art"]["id"] = json!(layer_image.0); + let layer = &mut saved["document"]["layers"][0]["kind"]["children"]; + let masked = layer.as_array_mut().unwrap().iter_mut().find(|n| n.get("mask").is_some() || n["extras"].get("mask").is_some()).unwrap(); + let mask = if masked.get("mask").is_some() { &mut masked["mask"] } else { &mut masked["extras"]["mask"] }; + mask["art"]["id"] = json!(0); + std::fs::write(&path, serde_json::to_vec(&saved).unwrap()).unwrap(); + open(&mut s, &path); + let list = s.execute("links.list", &json!({})).unwrap(); + let ids: Vec = list["links"].as_array().unwrap().iter().map(|r| r["id"].as_u64().unwrap()).collect(); + let unique: std::collections::BTreeSet = ids.iter().copied().collect(); + assert_eq!((ids.len(), unique.len()), (5, 5), "{list}"); + assert!(!ids.contains(&0), "{list}"); + assert_eq!(list["links"][0]["id"], json!(layer_image.0), "the layer tree keeps its ids: {list}"); + let symbol = list["links"].as_array().unwrap().iter().find(|r| r["owner"]["kind"] == "symbol").unwrap()["id"].as_u64().unwrap(); + s.execute("links.embed", &json!({"ids": [symbol]})).unwrap(); + assert!(stored_link(&s, symbol).is_none()); + assert!(image(&s, layer_image).link.is_some(), "the image in the layers stays linked"); +} + /// 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. diff --git a/crates/engine/src/tests/linkspanel.rs b/crates/engine/src/tests/linkspanel.rs index f029eccd3d..a9a3a17ec7 100644 --- a/crates/engine/src/tests/linkspanel.rs +++ b/crates/engine/src/tests/linkspanel.rs @@ -213,7 +213,7 @@ fn go_to_selects_the_image() { run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})); assert_ne!(s.doc().unwrap().selection.objects, vec![id]); let r = run(&mut s, "links.goTo", json!({"id": id.0})); - assert_eq!(r, json!({"id": id.0, "bounds": [-100.0, 0.0, 500.0, 300.0]})); + assert_eq!(r, json!({"id": id.0, "bounds": [-100.0, 0.0, 500.0, 300.0], "onCanvas": true})); assert_eq!(s.doc().unwrap().selection.objects, vec![id]); let rect = s.doc().unwrap().doc.layers[0].children().unwrap()[1].id; assert!(s.execute("links.goTo", &json!({"id": rect.0})).is_err(), "not an image"); diff --git a/crates/engine/src/tests/linkwatch.rs b/crates/engine/src/tests/linkwatch.rs index 7fc8f0a4ba..0a5b9d7dbe 100644 --- a/crates/engine/src/tests/linkwatch.rs +++ b/crates/engine/src/tests/linkwatch.rs @@ -47,6 +47,30 @@ fn update_changed_reads_changed_files_again_once() { assert_eq!(s.execute("links.check", &json!({})).unwrap()["modified"], 1); } +/// A file only a symbol's art shows is watched too, and read again by the id of the symbol's image. +#[test] +fn update_changed_reads_a_file_only_a_symbol_shows() { + let dir = Folder::new("watch-symbol"); + let path = dir.file("art.png"); + std::fs::write(&path, png(40, 40, RED)).unwrap(); + let mut s = session(); + let id = place(&mut s, &path); + s.execute("symbol.new", &json!({"name": "Mark", "ids": [id.0]})).unwrap(); + let instance = s.doc().unwrap().selection.objects[0]; + s.execute("edit.clear", &json!({"ids": [instance.0]})).unwrap(); + let mut in_symbol = None; + s.doc().unwrap().doc.symbols[0].art.walk(&mut |n| { + if matches!(n.kind, vectorcraft_doc::NodeKind::Image(_)) { + in_symbol = Some(n.id.0); + } + }); + let in_symbol = in_symbol.expect("the symbol's image"); + assert_eq!(s.execute("links.updateChanged", &json!({})).unwrap()["updated"], json!([])); + save(&path, &png(40, 40, BLUE)); + assert_eq!(s.execute("links.updateChanged", &json!({})).unwrap()["updated"], json!([in_symbol])); + assert_eq!(s.execute("links.check", &json!({})).unwrap()["modified"], 0); +} + #[test] fn a_background_look_follows_update_links() { for (mode, key) in [("automatically", "updated"), ("askWhenModified", "ask"), ("manually", "modified")] { diff --git a/crates/engine/src/tests/live.rs b/crates/engine/src/tests/live.rs index 10939d4b2a..c372bcf784 100644 --- a/crates/engine/src/tests/live.rs +++ b/crates/engine/src/tests/live.rs @@ -643,6 +643,32 @@ fn envelope_top_object_shares_a_side_by_control_polygon_length() { assert!(near(Point::new(500.0, 200.0)) < 0.5, "the middle of the bottom: {pts:?}"); } +#[test] +fn envelope_top_object_keeps_its_look_when_anchors_are_added() { + // Add Anchor Points splits each segment of the top object in two without changing its shape. + // The top curve's parameter runs fast at its start, so its halves have control polygons of + // different lengths; the envelope still bends the two rectangles as the unsplit curve does. + let made = |add_anchors: bool| { + let mut s = session(); + let left = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + let right = rect(&mut s, 200.0, 100.0, 100.0, 100.0); + let d = "M400 100 C520 40 590 70 600 100 L600 200 L400 200 Z"; + let t = id_of(&s.execute("path.create", &json!({ "d": d })).unwrap()); + if add_anchors { + sel(&mut s, &[t]); + s.execute("object.path.addAnchorPoints", &json!({})).unwrap(); + assert_eq!(node(&s, t).path_data().map(|p| p.anchor_count()), Some(8)); + } + sel(&mut s, &[left, right, t]); + let e = id_of(&s.execute("object.envelope.makeWithTopObject", &json!({})).unwrap()); + all_anchors(&live::expand_live(&node(&s, e))) + }; + let (plain, split) = (made(false), made(true)); + assert_eq!(plain.len(), split.len()); + let off = plain.iter().zip(&split).map(|(p, q)| p.distance(*q)).fold(0.0, f64::max); + assert!(off < 1e-6, "the art moves by up to {off} pt"); +} + #[test] fn envelope_release_and_expand() { let mut s = session(); diff --git a/crates/engine/src/tests/objexpand.rs b/crates/engine/src/tests/objexpand.rs index 38918cf2c4..1c931e0de8 100644 --- a/crates/engine/src/tests/objexpand.rs +++ b/crates/engine/src/tests/objexpand.rs @@ -257,6 +257,25 @@ fn shadows_under_a_groups_or_an_objects_transform_expand_appearance_as_the_canva } } +/// A group's Transform effect runs after its member's own Offset Path in Expand Appearance as on +/// the canvas: the 100 pt square offset to 120 pt and scaled by half expands 60 pt wide. +#[test] +fn a_groups_effects_after_its_members_own_expand_as_the_canvas_draws_them() { + let mut s = session(); + run(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})); + run(&mut s, "effect.apply", json!({"effect": "path.offsetPath", "params": {"offset": 10}})); + run(&mut s, "object.group", json!({})); + run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": {"scaleH": 50, "scaleV": 50}})); + let before = render(&s); + run(&mut s, "effect.expandAppearance", json!({})); + let after = render(&s); + let diff = differing(&before, &after, 64); + assert_eq!(diff, 0, "{diff} pixels differ"); + let doc = &s.doc().unwrap().doc; + let w = doc.node(doc.layers[0].id).and_then(|l| l.geometric_bounds()).unwrap().width(); + assert!((w - 60.0).abs() < 1e-6, "{w}"); +} + #[test] fn a_placed_gradient_moved_by_a_warp_expands_as_the_canvas_draws_it() { // The object's own effect, and the fill's (the first appearance item). diff --git a/crates/engine/src/tests/place.rs b/crates/engine/src/tests/place.rs index a0a8ededa0..ab80255376 100644 --- a/crates/engine/src/tests/place.rs +++ b/crates/engine/src/tests/place.rs @@ -662,6 +662,101 @@ fn placed_art_brings_its_symbols_and_swatches_renaming_on_conflict() { assert!(linked, "still linked to the swatch it brought"); } +/// The symbol and pattern art placed art brings takes ids of the document's own: the file's ids +/// already name other objects there, and the Links panel names linked art in symbols by its id. +#[test] +fn placed_art_brings_its_symbols_and_patterns_with_ids_of_the_documents_own() { + let mut src = session(); + src.execute("shape.ellipse", &json!({"x": 50, "y": 10, "width": 20, "height": 20})).unwrap(); + src.execute("symbol.new", &json!({"name": "Star"})).unwrap(); + src.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap(); + let tile = src.doc().unwrap().selection.objects[0]; + src.execute("object.pattern.make", &json!({"ids": [tile.0], "edit": false, "name": "Dots"})).unwrap(); + src.execute("paint.setFill", &json!({"ids": [tile.0], "swatch": "Dots"})).unwrap(); + let bytes = serialize(&mut src, "vectorcraft"); + // The document's objects take the same ids the file's do. + let mut s = session(); + for x in [0, 20, 40, 60] { + s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 5, "height": 5})).unwrap(); + } + s.execute("symbol.new", &json!({"name": "Box"})).unwrap(); + place(&mut s, "logo.vectorcraft", &bytes, json!({})); + let doc = &s.doc().unwrap().doc; + assert!(doc.symbols.iter().any(|x| x.name == "Star") && doc.pattern("Dots").is_some()); + let mut ids = vec![]; + doc.visit_stored(|n, _| ids.push(n.id.0)); + let unique: std::collections::BTreeSet = ids.iter().copied().collect(); + assert_eq!(unique.len(), ids.len(), "{ids:?}"); +} + +/// Placing the same file again shares the symbols and patterns the first placement brought: their +/// art differs from the file's only in its ids, so no `Star 2` or `Dots 2` joins the document. +#[test] +fn placing_the_same_art_again_shares_its_symbols_and_patterns() { + let mut src = session(); + src.execute("shape.ellipse", &json!({"x": 50, "y": 10, "width": 20, "height": 20})).unwrap(); + src.execute("symbol.new", &json!({"name": "Star"})).unwrap(); + src.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap(); + let tile = src.doc().unwrap().selection.objects[0]; + src.execute("object.pattern.make", &json!({"ids": [tile.0], "edit": false, "name": "Dots"})).unwrap(); + src.execute("paint.setFill", &json!({"ids": [tile.0], "swatch": "Dots"})).unwrap(); + let bytes = serialize(&mut src, "vectorcraft"); + let mut s = session(); + let counts = |s: &Session| { + let doc = &s.doc().unwrap().doc; + (doc.symbols.len(), doc.patterns.len()) + }; + place(&mut s, "logo.vectorcraft", &bytes, json!({})); + let once = counts(&s); + for _ in 0..2 { + place(&mut s, "logo.vectorcraft", &bytes, json!({})); + } + assert_eq!(counts(&s), once); + let doc = &s.doc().unwrap().doc; + assert!(!doc.symbols.iter().any(|x| x.name == "Star 2") && doc.pattern("Dots 2").is_none()); +} + +/// A symbol whose art matches the document's own but uses a pattern the document defines +/// differently is not shared: it comes in under a free name, using the pattern it brings. +#[test] +fn placed_art_does_not_share_a_symbol_whose_pattern_moves() { + let mut src = session(); + src.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap(); + let tile = src.doc().unwrap().selection.objects[0]; + src.execute("object.pattern.make", &json!({"ids": [tile.0], "edit": false, "name": "Dots"})).unwrap(); + src.execute("paint.setFill", &json!({"ids": [tile.0], "swatch": "Dots"})).unwrap(); + src.execute("symbol.new", &json!({"name": "Star", "ids": [tile.0]})).unwrap(); + let bytes = serialize(&mut src, "vectorcraft"); + let mut s = session(); + place(&mut s, "logo.vectorcraft", &bytes, json!({})); + // The document's "Dots" changes; its "Star" still matches the file's. + let st = s.doc_mut().unwrap(); + let d = Arc::make_mut(&mut st.doc); + let dots = d.pattern_mut("Dots").unwrap(); + dots.tile = Rect::new(0.0, 0.0, 50.0, 50.0); + let r = place(&mut s, "logo.vectorcraft", &bytes, json!({})); + let mut symbol = None; + node(&s, &r["ids"][0]).walk(&mut |n| { + if let NodeKind::SymbolInstance { symbol: name, .. } = &n.kind { + symbol = Some(name.clone()); + } + }); + assert_eq!(symbol.as_deref(), Some("Star 2")); + let doc = &s.doc().unwrap().doc; + let star2 = doc.symbols.iter().find(|x| x.name == "Star 2").unwrap(); + let mut fills = vec![]; + star2.art.walk(&mut |n| { + fills.extend(n.appearance.items.iter().filter_map(|i| match i { + AppearanceItem::Fill(f) => match &f.paint { + Paint::Pattern { pattern, .. } => Some(pattern.clone()), + _ => None, + }, + _ => None, + })) + }); + assert_eq!(fills, ["Dots 2"]); +} + #[test] fn placed_art_brings_its_brushes_renaming_on_conflict() { // The file: a path with its own brush, and one with a brush the defaults hold. diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index cc4460d250..2661e85787 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -2820,6 +2820,188 @@ fn a_failed_store_write_keeps_the_stored_module_with_its_grant() { vectorcraft_plugins::registry::revoke(id); } +/// An install refused because another session revoked the grant its checks relied on writes +/// nothing: a store that kept the grant and lost the module gets no module back, its grants stay as +/// they were, and the plug-in installed with the id and the other session's revoke stand. `grant` +/// approves the module by itself. +#[test] +fn a_grant_revoked_while_installing_leaves_the_store_as_it_was() { + use vectorcraft_plugins::permissions::sha256_hex; + use vectorcraft_plugins::registry; + let folder = crate::tests_links::Folder::new("plugin-store-revoked-while-installing"); + let id = "test.engine.permissions.revokedwhileinstalling"; + let bytes = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&bytes); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let grants = folder.0.join("grants.json"); + let recorded = std::fs::read(&grants).unwrap(); + let module = std::path::PathBuf::from(s.stored_plugin_file(id).unwrap()); + std::fs::remove_file(&module).unwrap(); + + crate::cmd::plugin::BEFORE_INSTALL.set(Some(Box::new(move || { + registry::revoke(id); + }))); + let e = s.execute("plugin.install", &json!({"dataBase64": data})).unwrap_err().to_string(); + assert!(e.contains("asks for the permissions doc.read"), "{e}"); + assert!(!module.exists(), "no module is stored"); + assert_eq!(std::fs::read(&grants).unwrap(), recorded, "the grants stay as they were"); + assert!(registry::granted(id).is_none(), "the other session's revoke stands"); + assert_eq!(registry::get(id).map(|p| p.hash().to_string()), Some(sha256_hex(&bytes)), "the installed plug-in stays"); + + crate::cmd::plugin::BEFORE_INSTALL.set(Some(Box::new(move || { + registry::revoke(id); + }))); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + assert_eq!(std::fs::read(&module).unwrap(), bytes, "a module `grant` approves is stored"); + assert!(registry::granted(id).is_some_and(|g| g.hash == sha256_hex(&bytes))); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A plug-in another session installs with the id while a module is checked takes the place the +/// checks found free. Without `replace`, or with `replace: false`, the install is refused, writes no +/// module and leaves that plug-in installed; with `replace: true` the module takes its place. +#[test] +fn a_plug_in_installed_while_installing_needs_replace() { + use vectorcraft_plugins::permissions::sha256_hex; + use vectorcraft_plugins::registry; + let folder = crate::tests_links::Folder::new("plugin-store-installed-while-installing"); + let id = "test.engine.installedwhileinstalling"; + let ours = asking(id, "[]", &json!({"objects": []})); + let theirs = asking(id, "[]", &json!({"objects": [], "documentData": null})); + let data = vectorcraft_format::base64_encode(&ours); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + let module = std::path::PathBuf::from(s.stored_plugin_file(id).unwrap()); + let installed = || registry::get(id).map(|p| p.hash().to_string()); + let meanwhile = |theirs: Vec| -> Option> { + Some(Box::new(move || { + registry::install_bytes(&theirs).unwrap(); + })) + }; + + for (replace, why) in [(Value::Null, "is another module than"), (json!(false), "is already installed")] { + crate::cmd::plugin::BEFORE_INSTALL.set(meanwhile(theirs.clone())); + let e = s.execute("plugin.install", &json!({"dataBase64": data, "replace": replace})).unwrap_err().to_string(); + assert!(e.contains(why), "{replace}: {e}"); + assert!(!module.exists(), "{replace}: no module is stored"); + assert_eq!(installed(), Some(sha256_hex(&theirs)), "{replace}: the other plug-in stays installed"); + registry::remove(id); + } + + crate::cmd::plugin::BEFORE_INSTALL.set(meanwhile(theirs)); + run(&mut s, "plugin.install", json!({"dataBase64": data, "replace": true})); + assert_eq!(std::fs::read(&module).unwrap(), ours); + assert_eq!(installed(), Some(sha256_hex(&ours))); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// Without a plug-in store, the install's approval comes from the grant it read first, the one it +/// checks again before it installs: a grant another session records after that read approves +/// nothing, so a revoke that follows it can't be undone by the install recording it again. +#[test] +fn a_grant_recorded_and_revoked_while_installing_approves_nothing() { + use vectorcraft_plugins::permissions::{Grant, GrantToken, Permission, sha256_hex}; + use vectorcraft_plugins::registry; + let id = "test.engine.permissions.recordedwhileinstalling"; + let bytes = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&bytes); + let mut s = session(); + let g = Grant { id: id.into(), hash: sha256_hex(&bytes), permissions: vec![Permission::DocRead] }; + crate::cmd::plugin::AFTER_GRANT_READ.set(Some(Box::new(move || { + registry::grant(GrantToken::after_engine_approval(g)); + }))); + let e = s.execute("plugin.install", &json!({"dataBase64": data})).unwrap_err().to_string(); + assert!(e.contains("asks for the permissions doc.read"), "{e}"); + assert!(registry::get(id).is_none(), "nothing is installed"); + registry::revoke(id); +} + +/// A `plugin.remove` in another session while a module is installed waits until the install has +/// written the store, then removes the module, its grant and the plug-in: nothing of it stays in +/// the store for the next launch. +#[test] +fn a_removal_while_installing_leaves_nothing_in_the_store() { + use vectorcraft_plugins::registry; + let folder = crate::tests_links::Folder::new("plugin-store-removed-while-installing"); + let id = "test.engine.permissions.removedwhileinstalling"; + let bytes = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&bytes); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + let module = std::path::PathBuf::from(s.stored_plugin_file(id).unwrap()); + let grants = folder.0.join("grants.json"); + + let (said, heard) = std::sync::mpsc::channel::<&'static str>(); + let (handed, remover) = std::sync::mpsc::channel(); + let dir = folder.0.clone(); + crate::cmd::plugin::BEFORE_STORE.set(Some(Box::new(move || { + let thread = std::thread::spawn(move || { + let tell = said.clone(); + crate::cmd::plugin::WHILE_WAITING.set(Some(Box::new(move || { + let _ = tell.send("waiting"); + }))); + let mut other = session(); + other.attach_plugin_store(dir); + let removed = other.execute("plugin.remove", &json!({"id": id})).map(|_| ()).map_err(|e| e.to_string()); + let _ = said.send("removed"); + removed + }); + // The removal has finished, or waits for this install. + let first = heard.recv().unwrap_or("gone"); + let _ = handed.send((first, thread)); + }))); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let (first, thread) = remover.recv().unwrap(); + assert_eq!(thread.join().unwrap(), Ok(())); + assert!(registry::get(id).is_none() && registry::granted(id).is_none(), "the plug-in and its grant are gone"); + assert!(!module.exists(), "no module stays in the store"); + assert!(!std::fs::read_to_string(&grants).is_ok_and(|g| g.contains(id)), "no grant stays in the store"); + assert_eq!(first, "waiting", "the removal waits for the install"); +} + +/// Another session that attaches the plug-in store while a new version is installed loads the +/// stored plug-ins once the install has written the store: the version that runs is the one the +/// store keeps for the next launch. +#[test] +fn a_store_loaded_while_installing_loads_the_new_version() { + use vectorcraft_plugins::permissions::sha256_hex; + use vectorcraft_plugins::registry; + let folder = crate::tests_links::Folder::new("plugin-store-loaded-while-installing"); + let id = "test.engine.permissions.loadedwhileinstalling"; + let old = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let new = asking(id, r#"["doc.read"]"#, &json!({"objects": [], "documentData": null})); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&old), "grant": ["doc.read"]})); + + let (said, heard) = std::sync::mpsc::channel::<&'static str>(); + let (handed, loader) = std::sync::mpsc::channel(); + let dir = folder.0.clone(); + crate::cmd::plugin::BEFORE_STORE.set(Some(Box::new(move || { + let thread = std::thread::spawn(move || { + let tell = said.clone(); + crate::cmd::plugin::WHILE_WAITING.set(Some(Box::new(move || { + let _ = tell.send("waiting"); + }))); + session().attach_plugin_store(dir); + let _ = said.send("loaded"); + }); + // The load has finished, or waits for this install. + let first = heard.recv().unwrap_or("gone"); + let _ = handed.send((first, thread)); + }))); + let data = vectorcraft_format::base64_encode(&new); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"], "replace": true})); + let (first, thread) = loader.recv().unwrap(); + thread.join().unwrap(); + assert_eq!(registry::get(id).map(|p| p.hash().to_string()), Some(sha256_hex(&new)), "the new version runs"); + assert_eq!(std::fs::read(s.stored_plugin_file(id).unwrap()).unwrap(), new, "the store keeps the new version"); + assert_eq!(first, "waiting", "the load waits for the install"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + /// Runs the test `name` of this module again in a process of its own → whether this is that /// process. The list of disabled plug-ins is kept for the whole process, and the other tests here /// read it again each time they attach a plug-in store. diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index 14669fd357..3808d06797 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -753,6 +753,9 @@ fn precise_cursors_replace_every_pen_state() { Cursor::ShapeBuilderErase, Cursor::AnchorPoint, Cursor::Curvature, + Cursor::LivePaintBucket, + Cursor::LivePaintBucketFace, + Cursor::LivePaintBucketEdge, ] { assert_eq!(c.precise(), Cursor::Crosshair, "{c:?}"); } @@ -2473,6 +2476,65 @@ fn deferred_commit_forwards_preview_warnings() { assert!(ui.iter().any(|r| matches!(r, UiRequest::Status(m) if m.contains("type"))), "{ui:?}"); } +/// A session with a rectangle selected, and type too with `with_type`, tool `tool` chosen, +/// Real-time Drawing off, and an interaction labeled `label` whose deferred Bloat preview warns +/// that type is skipped when type is selected. +fn deferred_bloat(label: &str, with_type: bool, tool: &str) -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let rect = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 200, "height": 200})).unwrap(); + let text = s.execute("text.create", &json!({"x": 300, "y": 200, "text": "Hi"})).unwrap(); + let ids = if with_type { json!([rect["id"], text["id"]]) } else { json!([rect["id"]]) }; + s.execute("select.set", &json!({ "ids": ids })).unwrap(); + s.select_tool(tool, ViewInfo::default()).unwrap(); + set_pref(&mut s, "realTimeDrawing", json!(false)); + s.begin_interaction(label).unwrap(); + let p = json!({"tool": "bloat", "points": [[290.0, 200.0]], "width": 200.0, "height": 200.0}); + s.doc_mut().unwrap().interaction.as_mut().unwrap().preview = Some(("object.liquify".into(), p)); + s +} + +/// A command that applies a deferred preview before it runs (Undo, Clear History) reports the +/// preview's warning in its result, as the tool's own commit reports it; the preview is its own +/// step, which Undo takes back. A preview without a warning adds none. +#[test] +fn settling_a_deferred_preview_keeps_its_warning() { + let mut s = deferred_bloat("Bloat", true, "selection"); + let before = s.doc().unwrap().history.undo.len(); + let r = s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(r["undone"], "Bloat", "{r}"); + assert!(r["warning"].as_str().is_some_and(|w| w.contains("type")), "{r}"); + assert_eq!(r["previewWarning"], r["warning"], "{r}"); + assert_eq!(s.doc().unwrap().history.undo.len(), before, "the preview was a step of its own, and Undo took it back"); + let r = s.execute("edit.redo", &json!({})).unwrap(); + assert!(r.get("warning").is_none() && r.get("previewWarning").is_none(), "nothing was settled: {r}"); + + let mut s = deferred_bloat("Bloat", true, "selection"); + let r = s.execute("edit.clearHistory", &json!({})).unwrap(); + assert!(r["warning"].as_str().is_some_and(|w| w.contains("type")), "{r}"); + + let mut s = deferred_bloat("Bloat", false, "selection"); + let r = s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(r, json!({"undone": "Bloat"})); +} + +/// Typing kept as its own step when a tool's drag begins, or when a Cmd press lends the Selection +/// tool, shows its applied preview's warning in the status bar. +#[test] +fn settling_typing_for_a_tool_shows_its_preview_warning() { + use vectorcraft_tools::{Action, Mods}; + let warned = |ui: &[UiRequest]| ui.iter().any(|r| matches!(r, UiRequest::Status(m) if m.contains("type"))); + let mut s = deferred_bloat("Typing", true, "selection"); + let ui = s.apply_actions(vec![Action::Begin("Move".into())]).unwrap(); + assert!(warned(&ui), "{ui:?}"); + + let mut s = deferred_bloat("Typing", true, "rectangle"); + let cmd = Mods { cmd: true, ..Default::default() }; + let ui = s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 380.0).with_mods(cmd), ViewInfo::default()).unwrap(); + assert!(warned(&ui), "{ui:?}"); + s.pointer(&PointerEvent::new(PointerKind::Up, 50.0, 380.0).with_mods(cmd), ViewInfo::default()).unwrap(); +} + /// File Handling › Use Low Resolution Proxy for Linked EPS (#394): off by default; toggling it does /// not replace full-resolution pixels already in the document. #[test] @@ -2736,3 +2798,33 @@ fn snap_to_glyph_options_read_set_and_reset() { s.execute("prefs.reset", &json!({})).unwrap(); assert_eq!(s.execute("view.snapToGlyph.options", &json!({})).unwrap(), all); } + +/// Pixel Snapping Options: `view.snapToPixel.options` reads and sets While Drawing, While Moving +/// and While Scaling, all on by default, kept as the `pixelSnap` preference group; bad keys and +/// values change nothing, preferences saved without the group read it as all on, and resetting the +/// preferences turns them all back on. +#[test] +fn pixel_snapping_options_read_set_and_reset() { + let mut s = Session::new(); + let all = json!({"drawing": true, "moving": true, "scaling": true}); + assert_eq!(s.execute("view.snapToPixel.options", &json!({})).unwrap(), all); + let set = json!({"drawing": true, "moving": false, "scaling": true}); + assert_eq!(s.execute("view.snapToPixel.options", &json!({"moving": false})).unwrap(), set); + assert_eq!(s.execute("prefs.get", &json!({"key": "pixelSnap"})).unwrap(), set); + assert!(!s.prefs.pixel_snap.moving && s.prefs.pixel_snap.drawing && s.prefs.pixel_snap.scaling); + for bad in [json!({"moving": 1}), json!({"rotating": false})] { + assert!(s.execute("view.snapToPixel.options", &bad).is_err(), "{bad}"); + assert!(s.execute("prefs.set", &json!({"key": "pixelSnap", "value": bad})).is_err(), "{bad}"); + assert_eq!(s.execute("view.snapToPixel.options", &json!({})).unwrap(), set, "{bad}"); + } + s.execute("prefs.set", &json!({"key": "pixelSnap", "value": {"scaling": false}})).unwrap(); + let both = json!({"drawing": true, "moving": false, "scaling": false}); + assert_eq!(s.execute("view.snapToPixel.options", &json!({})).unwrap(), both); + // Preferences written before the group existed, and a group that names only some options. + let older: Prefs = serde_json::from_value(json!({"keyboardIncrement": 4})).unwrap(); + assert_eq!(older.pixel_snap, vectorcraft_tools::PixelSnap::default()); + let partial: Prefs = serde_json::from_value(json!({"pixelSnap": {"drawing": false}})).unwrap(); + assert_eq!(partial.pixel_snap, vectorcraft_tools::PixelSnap { drawing: false, moving: true, scaling: true }); + s.execute("prefs.reset", &json!({})).unwrap(); + assert_eq!(s.execute("view.snapToPixel.options", &json!({})).unwrap(), all); +} diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index 4707ae98fd..90e7822ef8 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -1348,3 +1348,159 @@ fn theme_picker_refuses_bad_params() { assert!(e.contains(msg), "{p}: {e}"); } } + +const RED: &str = "rgb 255 0 0"; +const PURPLE: &str = "rgb 128 0 204"; +const BLUE: &str = "rgb 0 0 255"; + +/// Two red rectangles, a purple one and a blue one, selected. +fn prominent_art(s: &mut Session) -> [NodeId; 4] { + let ids = [rect(s, json!("#ff0000")), rect(s, json!("#ff0000")), rect(s, json!("#8000cc")), rect(s, json!("#0000ff"))]; + select_all(s); + ids +} + +#[test] +fn weigh_gives_each_rows_share_of_the_uses() { + let mut s = session(); + prominent_art(&mut s); + let map = json!([{"from": [RED, PURPLE], "to": "#00ff00"}, {"from": BLUE, "to": null, "tint": 50}]); + let r = run(&mut s, "recolor.weigh", json!({"map": map})); + assert_eq!(r["shares"], json!([75.0, 25.0])); + assert_eq!( + r["map"], + json!([{"from": [RED, PURPLE], "to": "#00ff00"}, {"from": [BLUE], "to": null, "tint": 50}]), + "rows as given, from as a list" + ); + // An excluded row has no share, and the others share the uses. + let excl = json!([{"from": [RED, PURPLE], "to": null}, {"from": [BLUE], "to": null, "exclude": true}]); + assert_eq!(run(&mut s, "recolor.weigh", json!({"map": excl}))["shares"], json!([100.0, 0.0])); + // An excluded row before another that lists the same colour doesn't take its uses. + let first = json!([{"from": [RED], "exclude": true}, {"from": [RED]}, {"from": [BLUE, PURPLE]}]); + assert_eq!(run(&mut s, "recolor.weigh", json!({"map": first}))["shares"], json!([0.0, 50.0, 50.0])); + // A current colour that no art uses counts nothing, and a use counts for the first row only. + let twice = json!({"map": [{"from": [RED, "#123456"]}, {"from": [RED, PURPLE, BLUE]}]}); + assert_eq!(run(&mut s, "recolor.weigh", twice)["shares"], json!([50.0, 50.0])); + // As recolor.apply matches them: an exact colour before a hex one, a row with a new colour first. + let exact = json!({"map": [{"from": ["#ff0000", PURPLE], "to": "#00ff00"}, {"from": [RED, BLUE], "to": "#ffff00"}]}); + assert_eq!(run(&mut s, "recolor.weigh", exact)["shares"], json!([25.0, 75.0])); + let recolored = json!({"map": [{"from": [RED, PURPLE]}, {"from": [RED, BLUE], "to": "#ffff00"}]}); + assert_eq!(run(&mut s, "recolor.weigh", recolored)["shares"], json!([25.0, 75.0])); +} + +#[test] +fn weigh_moves_colors_to_the_rows_weights_and_changes_nothing() { + let mut s = session(); + let [_, _, purple, blue] = prominent_art(&mut s); + let map = json!([{"from": [RED, PURPLE], "to": "#00ff00"}, {"from": [BLUE], "to": "#ffff00"}]); + let r = run(&mut s, "recolor.weigh", json!({"map": map, "weights": [1, 1]})); + assert_eq!(r["map"], json!([{"from": [RED], "to": "#00ff00"}, {"from": [BLUE, PURPLE], "to": "#ffff00"}])); + assert_eq!(r["shares"], json!([50.0, 50.0])); + assert_eq!(fill(&s, purple).to_hex(), "#8000cc", "a query leaves the art alone"); + // Recoloring with the weighed rows gives the moved colour its new row's colour. + select_all(&mut s); + run(&mut s, "recolor.apply", json!({"map": r["map"]})); + assert_eq!(fill(&s, purple).to_hex(), "#ffff00"); + assert_eq!(fill(&s, blue).to_hex(), "#ffff00"); + // A row's first colour stays, however small its weight. + let mut s = session(); + prominent_art(&mut s); + let r = run(&mut s, "recolor.weigh", json!({"map": map, "weights": [0, 1]})); + assert_eq!(r["map"][0]["from"], json!([RED])); + assert_eq!(r["shares"], json!([50.0, 50.0])); + // Excluded rows keep their colours and take none; their weights are ignored. + let three = + json!([{"from": [RED, PURPLE], "to": "#000000"}, {"from": [BLUE], "to": "#000000", "exclude": true}, {"from": ["#00ff00"], "to": "#000000"}]); + let r = run(&mut s, "recolor.weigh", json!({"map": three, "weights": [1, 50, 1]})); + assert_eq!(r["map"][1]["from"], json!([BLUE])); + assert_eq!(r["map"][2]["from"], json!(["#00ff00", PURPLE])); + // A row without a new colour recolors nothing, so it neither gives nor takes colours. + let keep = json!([{"from": [RED, PURPLE], "to": "#000000"}, {"from": [BLUE]}, {"from": ["#00ff00"], "to": "#000000"}]); + let r = run(&mut s, "recolor.weigh", json!({"map": keep, "weights": [0, 1, 1]})); + assert_eq!(r["map"][1]["from"], json!([BLUE])); + assert_eq!(r["map"][2]["from"], json!(["#00ff00", PURPLE])); +} + +/// A colour that two rows list moves only where recolor.apply recolors it with the row it moved +/// to, so the shares describe the recolor. +#[test] +fn weigh_keeps_a_moved_color_from_rows_that_also_list_it() { + const GREEN: &str = "rgb 0 255 0"; + let mut s = session(); + let [_, _, purple, _] = prominent_art(&mut s); + rect(&mut s, json!("#00ff00")); + select_all(&mut s); + // The purple moves from the first row to the third; the second row's entry for it goes. + let map = json!([{"from": [RED, PURPLE], "to": "#000000"}, {"from": [BLUE, PURPLE], "to": "#ffffff"}, {"from": [GREEN], "to": "#ffff00"}]); + let r = run(&mut s, "recolor.weigh", json!({"map": map, "weights": [2, 1, 2]})); + assert_eq!(r["map"][0]["from"], json!([RED])); + assert_eq!(r["map"][1]["from"], json!([BLUE])); + assert_eq!(r["map"][2]["from"], json!([GREEN, PURPLE])); + assert_eq!(r["shares"], json!([40.0, 20.0, 40.0])); + run(&mut s, "recolor.apply", json!({"map": r["map"], "method": "exact"})); + assert_eq!(fill(&s, purple).to_hex(), "#ffff00", "the purple takes the row it moved to"); + // A colour that another row lists first stays: that row would take it back. + let mut s = session(); + let [_, _, purple, _] = prominent_art(&mut s); + rect(&mut s, json!("#00ff00")); + select_all(&mut s); + let map = json!([{"from": [RED, PURPLE], "to": "#000000"}, {"from": [PURPLE, BLUE], "to": "#ffffff"}, {"from": [GREEN], "to": "#ffff00"}]); + let r = run(&mut s, "recolor.weigh", json!({"map": map, "weights": [2, 1, 2]})); + assert_eq!(r["map"][0]["from"], json!([RED, PURPLE])); + assert_eq!(r["map"][1]["from"], json!([PURPLE, BLUE])); + assert_eq!(r["shares"], json!([60.0, 20.0, 20.0])); + run(&mut s, "recolor.apply", json!({"map": r["map"], "method": "exact"})); + assert_eq!(fill(&s, purple).to_hex(), "#000000", "the purple keeps the first row's colour"); +} + +#[test] +fn weigh_moves_the_tints_of_a_global_swatch_together() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Brand", "color": {"c": 0, "m": 80, "y": 90, "k": 0}, "global": true})); + rect(&mut s, json!("#ff0000")); + let full = rect(&mut s, json!("#00ff00")); + let tint = rect(&mut s, json!("#00ff00")); + rect(&mut s, json!("#0000ff")); + run(&mut s, "paint.setFill", json!({"ids": [full.0], "swatch": "Brand"})); + run(&mut s, "paint.setFill", json!({"ids": [tint.0], "swatch": "Brand", "tint": 50})); + select_all(&mut s); + let brand: Vec = run(&mut s, "recolor.colors", json!({}))["colors"] + .as_array() + .unwrap() + .iter() + .filter(|c| c["swatch"] == "Brand") + .map(|c| c["key"].clone()) + .collect(); + assert_eq!(brand.len(), 2); + let map = json!([{"from": [RED, brand[0], brand[1]], "to": "#000000"}, {"from": [BLUE], "to": "#ffffff"}]); + // Even weights would take one tint alone, which would split the swatch: nothing moves. + let r = run(&mut s, "recolor.weigh", json!({"map": map, "weights": [1, 1]})); + assert_eq!(r["map"][1]["from"], json!([BLUE])); + // The swatch's two colours move to the blue row as one. + let r = run(&mut s, "recolor.weigh", json!({"map": map, "weights": [1, 3]})); + assert_eq!(r["map"][1]["from"], json!([BLUE, brand[0], brand[1]])); + assert_eq!(r["shares"], json!([25.0, 75.0])); + // Colours that stay keep their order, a swatch's colours with another between them included. + let split = json!([{"from": [brand[0], RED, brand[1]], "to": "#000000"}, {"from": [BLUE], "to": "#ffffff"}]); + let r = run(&mut s, "recolor.weigh", json!({"map": split, "weights": [3, 1]})); + assert_eq!(r["map"][0]["from"], json!([brand[0], RED, brand[1]])); +} + +#[test] +fn weigh_refuses_bad_weights() { + let mut s = session(); + prominent_art(&mut s); + let map = json!([{"from": [RED]}, {"from": [BLUE], "exclude": true}]); + for (p, msg) in [ + (json!({"map": map, "weights": [1]}), "`weights` must be a list of 2 numbers, one per row"), + (json!({"map": map, "weights": "1, 1"}), "`weights` must be a list of 2 numbers"), + (json!({"map": map, "weights": [1, -1]}), "each weight must be a number of 0 or more (got -1)"), + (json!({"map": map, "weights": [1, "2"]}), "each weight must be a number of 0 or more"), + (json!({"map": map, "weights": [0, 5]}), "at least one row that isn't excluded needs a weight above 0"), + (json!({"weights": [1, 1]}), "missing `map`"), + (json!({"map": [{"to": "#ff0000"}]}), "each row needs `from`"), + ] { + let e = s.execute("recolor.weigh", &p).unwrap_err().to_string(); + assert!(e.contains(msg), "{p}: {e}"); + } +} diff --git a/crates/engine/src/tests/script_engines.rs b/crates/engine/src/tests/script_engines.rs index 7e768c5875..dd27d9ff1f 100644 --- a/crates/engine/src/tests/script_engines.rs +++ b/crates/engine/src/tests/script_engines.rs @@ -202,6 +202,52 @@ fn an_error_in_code_an_earlier_run_kept_is_at_that_runs_file_and_line() { let _ = std::fs::remove_dir_all(base); } +/// `$.fileName` in code an earlier run of a named engine kept names the file that code is in: that +/// run's script, a file it included or a file `$.evalFile` gave, not the file of the run that calls +/// it. Code from a script given as text, and code whose place the engine no longer keeps, has no +/// name; a dropped engine takes its functions with it. +#[test] +fn a_kept_function_reads_the_file_name_of_the_file_it_is_in() { + let base: PathBuf = std::env::temp_dir().join(format!("vc-script-engines-file-name-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + for dir in ["a", "b"] { + std::fs::create_dir_all(base.join(dir)).unwrap(); + } + std::fs::write(base.join("a/inc.jsxinc"), "function fromInclude() { return $.fileName; }").unwrap(); + std::fs::write(base.join("a/ev.jsxinc"), "\nfunction fromEval() { return $.fileName; }").unwrap(); + let def = base.join("a/def.jsx"); + std::fs::write(&def, "#targetengine e\nfunction where() { return $.fileName; }\n#include \"inc.jsxinc\"\n$.evalFile('ev.jsxinc');").unwrap(); + let caller = base.join("b/caller.jsx"); + let call = |s: &mut Session, text: &str| -> Vec { + std::fs::write(&caller, text).unwrap(); + let r = s.execute("script.run", &json!({"path": caller.to_string_lossy()})).unwrap(); + r["log"][0].as_array().unwrap().iter().map(|v| v.as_str().unwrap().replace('\\', "/")).collect() + }; + let mut s = Session::new(); + s.execute("script.run", &json!({"path": def.to_string_lossy()})).unwrap(); + let from_file = call(&mut s, "#targetengine e\nvc.log([where(), fromInclude(), fromEval(), $.fileName]);"); + let from_text = log(&mut s, "#targetengine e\nvc.log([where(), $.fileName, eval('where()'), eval('$.fileName')]);"); + run(&mut s, "#targetengine e\nfunction fromText() { return $.fileName; }").unwrap(); + let text_kept = call(&mut s, "#targetengine e\nvc.log([fromText(), $.fileName]);"); + // Each run's own place takes the room of the ones before, so def.jsx's places go. + TEST_KEPT_MAP_BYTES.with(|b| b.set(Some(300))); + for _ in 0..20 { + run(&mut s, "#targetengine e\nvar x = 1;").unwrap(); + } + let evicted = call(&mut s, "#targetengine e\nvc.log([where(), fromEval(), $.fileName]);"); + TEST_KEPT_MAP_BYTES.with(|b| b.set(None)); + s.execute("script.engine.drop", &json!({"name": "e"})).unwrap(); + let dropped = log(&mut s, "#targetengine e\nvc.log(typeof where);"); + let _ = std::fs::remove_dir_all(&base); + let ends = |names: &[String], ends: &[&str]| names.len() == ends.len() && names.iter().zip(ends).all(|(n, e)| n.ends_with(e)); + assert!(ends(&from_file, &["a/def.jsx", "a/inc.jsxinc", "a/ev.jsxinc", "b/caller.jsx"]), "{from_file:?}"); + let shown: Vec = from_text[0].as_array().unwrap().iter().map(|v| v.as_str().unwrap().replace('\\', "/")).collect(); + assert!(ends(&shown, &["a/def.jsx", "", "a/def.jsx", ""]) && shown[1].is_empty() && shown[3].is_empty(), "{shown:?}"); + assert!(text_kept[0].is_empty() && text_kept[1].ends_with("b/caller.jsx"), "{text_kept:?}"); + assert!(evicted[0].is_empty() && evicted[1].is_empty() && evicted[2].ends_with("b/caller.jsx"), "{evicted:?}"); + assert_eq!(dropped, json!(["undefined"])); +} + /// A named engine keeps the places of its earlier runs' code within its budget, the oldest going /// first, and the code still runs once its place is gone. #[test] diff --git a/crates/engine/src/tests/script_include.rs b/crates/engine/src/tests/script_include.rs index e5acc536cc..1bf259409d 100644 --- a/crates/engine/src/tests/script_include.rs +++ b/crates/engine/src/tests/script_include.rs @@ -374,6 +374,48 @@ fn script_eval_file_returns_last_value_and_shares_globals() { let _ = std::fs::remove_dir_all(base); } +/// `$.fileName` names the file the code reading it is in: a function `$.evalFile` gave names its +/// file after the file has returned, through nested files, and code an included file inserted names +/// that file. Code that `eval` compiled names the file being run. +#[test] +fn script_file_name_names_the_file_of_the_code_that_reads_it() { + let base = folder("filename"); + write(&base.join("main/inc.jsxinc"), "function fromInclude() { return $.fileName; }\nvar includedTop = $.fileName;"); + write( + &base.join("main/sub/outer.jsx"), + "function fromOuter() { return $.fileName; }\nvar before = $.fileName;\n$.evalFile('inner.jsx');\nvar after = $.fileName;\nfromInner();", + ); + write(&base.join("main/sub/inner.jsx"), "function fromInner() { return $.fileName; }\n$.fileName;"); + let r = run( + &base, + "#include \"inc.jsxinc\"\nvar nested = $.evalFile('sub/outer.jsx');\n\ + vc.log([fromInclude(), includedTop, before, after, nested, fromOuter(), fromInner(), $.fileName, eval('$.fileName')]);", + ) + .unwrap(); + let names: Vec = r["log"][0].as_array().unwrap().iter().map(|v| v.as_str().unwrap().replace('\\', "/")).collect(); + let ends = [ + "main/inc.jsxinc", + "main/inc.jsxinc", + "sub/outer.jsx", + "sub/outer.jsx", + "sub/inner.jsx", + "sub/outer.jsx", + "sub/inner.jsx", + "main/main.jsx", + "main/main.jsx", + ]; + assert_eq!(names.len(), ends.len(), "{names:?}"); + for (name, end) in names.iter().zip(ends) { + assert!(name.ends_with(end), "{name} ends with {end}: {names:?}"); + } + // A script given as text has no name, and neither have the functions it defines. + let r = Session::new() + .execute("script.run", &json!({"source": "function f() { return $.fileName; }\nvc.log([f(), $.fileName]);", "name": "t.js"})) + .unwrap(); + assert_eq!(r["log"], json!([["", ""]])); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn script_eval_file_outside_scope_refused() { let base = folder("evaloutside"); diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index ad1549140f..0452251a09 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -25,7 +25,8 @@ pub struct ViewInfo { /// View → Pixel Preview: while it is on, the tools use no Smart Guides. pub pixel_preview: bool, pub show_bbox: bool, - /// View → Snap to Pixel: drawing and moving land on whole pixels (points at 72 ppi). + /// View → Snap to Pixel: drawing, moving and scaling land on whole pixels (points at 72 ppi), + /// each while its Pixel Snapping option (`view.snapToPixel.options`) is on. pub snap_to_pixel: bool, /// View → Snap to Point: picked points (a transform's reference point) land on anchors. pub snap_to_point: bool, @@ -75,6 +76,15 @@ fn nine_slice_guide_preview(cmd: &str, p: &Value) -> bool { && p.as_object().is_some_and(|m| m.contains_key("nineSliceGuides") && m.keys().all(|k| k == "name" || k == "nineSliceGuides")) } +/// `ui` with a status message first for each of `warnings` (which came before its requests) that it +/// doesn't already show. +fn with_status(mut ui: Vec, warnings: Vec) -> Vec { + let new: Vec = + warnings.into_iter().filter(|w| !ui.iter().any(|r| matches!(r, UiRequest::Status(s) if s == w))).map(UiRequest::Status).collect(); + ui.splice(0..0, new); + ui +} + /// Requests from tools that only the frontend can fulfil. #[derive(Clone, Debug, PartialEq)] pub enum UiRequest { @@ -227,24 +237,28 @@ impl Session { /// A press with Cmd held (Ctrl elsewhere) and any other tool than a selection tool: the /// selection tool [`Self::lent_tool`] takes the gesture, pressing without Cmd (a plain click, - /// not Select Behind). The tool lent to stays as it was, unaware, until the release. - fn lend_selection_tool(&mut self, ev: &PointerEvent) -> PointerEvent { + /// not Select Behind). The tool lent to stays as it was, unaware, until the release. → the event + /// for the tool, and the warnings of a preview that keeping the typing applied. + fn lend_selection_tool(&mut self, ev: &PointerEvent) -> Result<(PointerEvent, Vec)> { if ev.kind != PointerKind::Down || !ev.mods.cmd || self.lender.is_some() { - return *ev; + return Ok((*ev, vec![])); } - let Some(id) = self.lent_tool(self.tool.id(), &ev.mods) else { return *ev }; + let Some(id) = self.lent_tool(self.tool.id(), &ev.mods) else { return Ok((*ev, vec![])) }; // Typing in progress is kept as its own step first: the lent tool's drag previews from the - // document its interaction started from, which would drop the typing (#1881). + // document its interaction started from, which would drop the typing (#1881). When it + // can't be kept, the press is not lent. + let mut settled = vec![]; if crate::cmd::typing_in_progress(self) { - // Fails only without a document, and then there is no typing to keep. - let _ = crate::cmd::settle_interaction(self); + let (r, warnings) = self.collect_settled_warnings(crate::cmd::settle_interaction); + r?; + settled = warnings; } // The Selection and Group Selection tools act on the instance whole. self.select_whole_instance(id); let lent = self.make_tool(id); self.selection_at_lend = self.active().map(|d| (d.uid, d.selection.clone())); self.lender = Some(std::mem::replace(&mut self.tool, lent)); - PointerEvent { mods: Mods { cmd: false, ..ev.mods }, ..*ev } + Ok((PointerEvent { mods: Mods { cmd: false, ..ev.mods }, ..*ev }, settled)) } /// The lent selection tool's gesture is over: the tool it was lent to is back as it was (the @@ -355,6 +369,7 @@ impl Session { // Snap to Grid and Snap to Pixel are exclusive, as in Illustrator; left both on, the grid // wins instead of pixels quietly rounding every drag to whole points (#1816). snap_to_pixel: view.snap_to_pixel && !view.snap_to_grid, + pixel_snap: self.prefs.pixel_snap, snap_to_point: view.snap_to_point, snap_tangent: self.prefs.snap_tangent, snap_perpendicular: self.prefs.snap_perpendicular, @@ -659,7 +674,8 @@ impl Session { } self.leave_draw_inside(ev, view)?; self.tell_tool_history_moved(); - let ev = &self.lend_selection_tool(ev); + let (ev, settled) = self.lend_selection_tool(ev)?; + let ev = &ev; let lent = self.lender.is_some(); let mut acts = self.with_tool_cx(view, |t, cx| t.pointer(cx, ev)); if !keep { @@ -670,7 +686,7 @@ impl Session { if keep && ev.kind == PointerKind::Up { self.keep_tool_settings(); } - self.apply_actions(acts) + self.apply_actions(acts).map(|ui| with_status(ui, settled)) }); // The tool's own edits do not move the history for it. A selection tool that Cmd lends // edits for the lender, which hears of the edit at its next event. @@ -1375,7 +1391,14 @@ impl Session { /// Apply tool actions. Errors from previews are reported but keep the interaction alive. pub fn apply_actions(&mut self, acts: Vec) -> Result> { let outer = std::mem::replace(&mut self.in_tool_actions, true); - let r = self.apply_tool_actions(acts); + // A preview that settling applied (typing kept as its own step before a drag begins) shows + // its warning in the status bar, as the tool's own commit shows its preview's. + let r = if !outer && self.depth == 0 { + let (r, settled) = self.collect_settled_warnings(|s| s.apply_tool_actions(acts)); + r.map(|ui| with_status(ui, settled)) + } else { + self.apply_tool_actions(acts) + }; self.in_tool_actions = outer; if !outer && self.depth == 0 { self.trim_histories(); diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index 6c7e90a188..fe56377d4e 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -180,6 +180,106 @@ fn a_batch_converts_through_the_profile_it_assigns() { assert_eq!(converted, fill(&device, b)); } +/// The profiles a document is assigned are in use while it is in front: a new or opened document +/// assigned none draws through the working spaces, switching back to the assigned document puts its +/// profile in use again, and closing a document puts the profiles of the document left in front, or +/// with none open the working spaces, in use. +#[test] +fn assigned_profiles_follow_the_front_document() { + let _g = settings(); + let dir = fresh_dir("front-profiles"); + let _reset = ColorSettingsReset { profile: None, paths: vec![dir.clone()] }; + std::fs::create_dir_all(&dir).unwrap(); + let tagged = dir.join("tagged.vectorcraft"); + let mut s = session(); + let working = cms::working_settings(); + assert_ne!(working.cmyk, cms::DEVICE_CMYK); + exec(&mut s, "edit.assignProfile", json!({"cmyk": cms::DEVICE_CMYK})); + exec(&mut s, "file.saveAs", json!({"path": tagged.to_str().unwrap()})); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + assert_eq!(cms::active_settings(), working, "a new document draws through the working spaces"); + exec(&mut s, "document.activate", json!({"index": 0})); + assert_eq!(cms::active_settings().cmyk, cms::DEVICE_CMYK, "back in front, the document draws through its profile"); + assert!(s.set_active(1)); + assert_eq!(cms::active_settings(), working, "a tab switch to the untagged document"); + exec(&mut s, "file.close", json!({})); + assert_eq!(cms::active_settings().cmyk, cms::DEVICE_CMYK, "the document left in front draws through its profile"); + exec(&mut s, "file.close", json!({})); + assert_eq!(cms::active_settings(), working, "no document open: the working spaces"); + exec(&mut s, "document.open", json!({"path": tagged.to_str().unwrap()})); + assert_eq!(cms::active_settings().cmyk, cms::DEVICE_CMYK, "an opened document draws through its saved profile"); +} + +/// Undo and Redo of Assign Profile, and File › Revert to a file assigned no profile, put the +/// profiles the document has then in use. +#[test] +fn undo_redo_and_revert_put_the_document_profiles_in_use() { + let _g = settings(); + let dir = fresh_dir("undo-profiles"); + let _reset = ColorSettingsReset { profile: None, paths: vec![dir.clone()] }; + std::fs::create_dir_all(&dir).unwrap(); + let untagged = dir.join("untagged.vectorcraft"); + let mut s = session(); + let working = cms::working_settings(); + exec(&mut s, "file.saveAs", json!({"path": untagged.to_str().unwrap()})); + exec(&mut s, "edit.assignProfile", json!({"cmyk": cms::DEVICE_CMYK})); + assert_eq!(cms::active_settings().cmyk, cms::DEVICE_CMYK); + exec(&mut s, "edit.undo", json!({})); + assert_eq!(doc_profiles(&s.doc().unwrap().doc), (None, None)); + assert_eq!(cms::active_settings(), working, "undone: the working spaces"); + exec(&mut s, "edit.redo", json!({})); + assert_eq!(doc_profiles(&s.doc().unwrap().doc), (None, Some(cms::DEVICE_CMYK.to_string()))); + assert_eq!(cms::active_settings().cmyk, cms::DEVICE_CMYK, "redone: the assigned profile"); + exec(&mut s, "file.revert", json!({})); + assert_eq!(doc_profiles(&s.doc().unwrap().doc), (None, None)); + assert_eq!(cms::active_settings(), working, "reverted: the working spaces"); +} + +/// A batch that assigns a profile and then fails puts the document back without it, and the +/// working spaces back in use. +#[test] +fn a_failed_batch_puts_the_profiles_in_use_back() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + let working = cms::working_settings(); + let steps = json!([ + {"command": "edit.assignProfile", "params": {"cmyk": cms::DEVICE_CMYK}}, + {"command": "document.activate", "params": {"index": 99}}, + ]); + assert!(s.execute("command.batch", &json!({"commands": steps})).is_err()); + assert_eq!(doc_profiles(&s.doc().unwrap().doc), (None, None)); + assert_eq!(cms::active_settings(), working); +} + +/// A batch step that switches documents makes the next step convert through the profiles of the +/// document it switched to, not those of the document the batch began in. +#[test] +fn a_batch_converts_the_document_it_switches_to_through_its_profiles() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let blue = |s: &mut Session| { + let id = rect(s, 10.0, 10.0, 50.0, 50.0); + exec(s, "paint.setFill", json!({"ids": [id.0], "color": "#3366cc"})); + id + }; + let fill = |s: &Session, id| s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint().color(); + let mut working = session(); + let w = blue(&mut working); + exec(&mut working, "file.documentColorMode", json!({"mode": "cmyk"})); + let mut s = session(); + let b = blue(&mut s); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + exec(&mut s, "edit.assignProfile", json!({"cmyk": cms::DEVICE_CMYK})); + let steps = json!([ + {"command": "document.activate", "params": {"index": 0}}, + {"command": "file.documentColorMode", "params": {"mode": "cmyk"}}, + ]); + exec(&mut s, "command.batch", json!({"commands": steps})); + assert_eq!(s.active_index(), Some(0)); + assert_eq!(fill(&s, b), fill(&working, w), "converted through the working CMYK space"); +} + /// View › Proof Setup › Working CMYK simulates the working CMYK space of Color Settings in a /// document assigned another CMYK profile, in Proof Colors and in Separations Preview, and a change /// of the working CMYK space shows in the next proof while the document keeps its profile. diff --git a/crates/engine/tests/it/delete_path_pieces.rs b/crates/engine/tests/it/delete_path_pieces.rs index 0d8b7171f7..afc304e99f 100644 --- a/crates/engine/tests/it/delete_path_pieces.rs +++ b/crates/engine/tests/it/delete_path_pieces.rs @@ -2,7 +2,7 @@ use serde_json::json; use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, Paint}; -use vectorcraft_doc::{Appearance, NodeId, NodeKind}; +use vectorcraft_doc::{Appearance, NodeId, NodeKind, selection::Selection}; use vectorcraft_engine::Session; use vectorcraft_geom::{Affine, Anchor, PathData, Rect, SubPath}; use vectorcraft_testkit::{invariants::check_session, raster::render_artboard}; @@ -226,6 +226,151 @@ fn deletion_split_preserves_gradient_placement() { } } +/// Subpath `i` of a multi-subpath test path: four cubic anchors on their own row, so every piece +/// that survives a deletion can be matched exactly. +fn row(i: usize, closed: bool) -> SubPath { + let y = 10.0 + 3.0 * i as f64; + let anchors = (0..4) + .map(|k| { + let mut a = Anchor::corner((10.0 + 20.0 * f64::from(k), y).into()); + a.h_in = a.p + (-3.0, -1.0); + a.h_out = a.p + (3.0, 1.0); + a + }) + .collect(); + SubPath::new(anchors, closed) +} + +/// An open piece made of `indexes` of `sp`, its unused end handles retracted as deletion leaves them. +fn piece(sp: &SubPath, indexes: &[usize]) -> SubPath { + let mut run: Vec = indexes.iter().map(|&i| sp.anchors[i]).collect(); + if let Some(first) = run.first_mut() { + first.h_in = first.p; + } + if let Some(last) = run.last_mut() { + last.h_out = last.p; + } + SubPath::new(run, false) +} + +/// Put `subpaths` into a new path object and return its ID. +fn multi_subpath_path(s: &mut Session, subpaths: Vec) -> NodeId { + let id = rectangle(s); + *std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().path_data_mut().unwrap() = PathData::new(subpaths); + id +} + +/// Run `command` on the current selection, check the path's surviving subpaths and that one Undo +/// restores the document and `before_selection` and one Redo repeats the edit, then check that a +/// second Clear removes the survivors. +fn delete_and_check(s: &mut Session, command: &str, id: NodeId, expected: &[SubPath], before_selection: &Selection) { + let before_doc = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let history = s.doc().unwrap().history.undo.len(); + s.execute(command, &json!({})).unwrap(); + let st = s.doc().unwrap(); + assert_eq!(st.doc.node(id).unwrap().path_data().unwrap().subpaths, expected, "{command}"); + assert_eq!(st.selection.objects, [id], "{command}: a multi-subpath path keeps its object"); + assert!(st.selection.anchors.is_empty() && st.selection.segments.is_empty()); + assert_eq!(st.history.undo.len(), history + 1); + let after_doc = serde_json::to_value(&st.doc).unwrap(); + let after_selection = st.selection.clone(); + check_session(s).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before_doc); + assert_eq!(&s.doc().unwrap().selection, before_selection); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), after_doc); + assert_eq!(s.doc().unwrap().selection, after_selection); + s.execute("edit.clear", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(id).is_none(), "{command}: the second Clear removes the survivors"); +} + +/// Selected anchors on many subpaths each remove only their own subpath's anchors; anchors named on +/// a subpath or index the path does not have remove nothing. +#[test] +fn deleting_anchors_on_many_subpaths_removes_each_subpaths_own_anchors() { + for command in ["edit.clear", "path.deleteAnchors", "edit.cut"] { + let mut s = session(); + let subpaths: Vec = (0..6).map(|i| row(i, i % 2 == 1)).collect(); + let id = multi_subpath_path(&mut s, subpaths.clone()); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 1], [1, 2], [2, 0], [2, 9], [4, 3], [5, 1], [7, 1]]})).unwrap(); + // Subpath 3 has no selected anchor and stays closed and unchanged. + let expected = [ + piece(&subpaths[0], &[2, 3]), + piece(&subpaths[1], &[3, 0, 1]), + piece(&subpaths[2], &[1, 2, 3]), + subpaths[3].clone(), + piece(&subpaths[4], &[0, 1, 2]), + piece(&subpaths[5], &[2, 3, 0]), + ]; + let before = s.doc().unwrap().selection.clone(); + delete_and_check(&mut s, command, id, &expected, &before); + } +} + +/// Selected segments on many subpaths each cut only their own subpath; a segment reference to a +/// subpath or segment the path does not have cuts nothing. +#[test] +fn deleting_segments_on_many_subpaths_cuts_each_subpaths_own_segments() { + for command in ["edit.clear", "path.deleteAnchors", "edit.cut"] { + let mut s = session(); + let subpaths: Vec = (0..6).map(|i| row(i, i % 2 == 1)).collect(); + let id = multi_subpath_path(&mut s, subpaths.clone()); + s.execute("select.segments", &json!({"id": id.0, "segments": [[0, 1], [1, 3], [4, 0], [5, 1]]})).unwrap(); + // Undo prunes the restored selection (`Selection::prune`), which drops references to + // segments the path does not have, so it restores the selection as it is here. + let before = s.doc().unwrap().selection.clone(); + // `select.segments` refuses references to missing segments, so these are added directly. + let refs = s.doc_mut().unwrap().selection.segments.get_mut(&id).unwrap(); + refs.extend([(2, 9), (7, 0)]); + let expected = [ + piece(&subpaths[0], &[0, 1]), + piece(&subpaths[0], &[2, 3]), + piece(&subpaths[1], &[0, 1, 2, 3]), + subpaths[2].clone(), + subpaths[3].clone(), + piece(&subpaths[4], &[1, 2, 3]), + piece(&subpaths[5], &[2, 3, 0, 1]), + ]; + delete_and_check(&mut s, command, id, &expected, &before); + } +} + +/// One selected interior anchor on each of many subpaths removes exactly that anchor from each, +/// keeping the subpaths in their original order. +#[test] +fn deleting_one_anchor_on_each_of_many_subpaths_keeps_subpath_order() { + let mut s = session(); + let subpaths: Vec = (0..400).map(|i| row(i, false)).collect(); + let id = multi_subpath_path(&mut s, subpaths.clone()); + let refs: Vec<[usize; 2]> = (0..400).filter(|i| i % 7 != 3).map(|i| [i, 1]).collect(); + s.execute("select.anchors", &json!({"id": id.0, "anchors": refs})).unwrap(); + let expected: Vec = subpaths.iter().enumerate().map(|(i, sp)| if i % 7 == 3 { sp.clone() } else { piece(sp, &[2, 3]) }).collect(); + let before = s.doc().unwrap().selection.clone(); + delete_and_check(&mut s, "edit.clear", id, &expected, &before); +} + +/// Cut Path cuts each subpath of a multi-subpath path only at that subpath's selected anchors. +#[test] +fn cutting_at_anchors_on_many_subpaths_cuts_each_subpath_at_its_own_anchors() { + let mut s = session(); + let subpaths: Vec = (0..6).map(|i| row(i, i % 2 == 1)).collect(); + let id = multi_subpath_path(&mut s, subpaths.clone()); + let refs = [(0, 1), (1, 2), (2, 9), (4, 2), (5, 0), (5, 2), (7, 1)]; + s.execute("select.anchors", &json!({"id": id.0, "anchors": refs.map(|(a, b)| [a, b])})).unwrap(); + s.execute("path.cutAtAnchors", &json!({})).unwrap(); + let expected: Vec = subpaths + .iter() + .enumerate() + .flat_map(|(si, sp)| sp.cut_at(&refs.iter().filter(|r| r.0 == si).map(|r| r.1).collect::>())) + .collect(); + // Subpaths 0 and 4 become two pieces each, closed subpath 1 opens into one, closed subpath 5 + // becomes two, and subpaths 2 and 3 stay as they were. + assert_eq!(expected.len(), 9); + assert_eq!(s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths, expected); + check_session(&s).unwrap(); +} + /// A connected remainder keeps automatic fitting; pinning is needed only for separate objects. #[test] fn deleting_one_segment_keeps_unplaced_gradients() { diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 8c4e95f4e6..ab39f467d2 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -1038,7 +1038,7 @@ fn nested_symbol_instances_stop_at_the_symbol_art_limit() { /// The documents [`the_writer_counts_objects_as_the_reader_reads_them`] writes: groups, compound /// paths, guides, sublayers, clipping groups and layers, painted clipping paths, opacity masks, /// gradients, pattern definitions and tiles, images, type, symbol definitions and instances, -/// objects with art styles and objects bound to variables. +/// objects with art styles, objects bound to variables and live envelopes. fn counted() -> Vec<(&'static str, Document)> { vec![ ("sample", sample()), @@ -1053,6 +1053,7 @@ fn counted() -> Vec<(&'static str, Document)> { ("painted clips", painted_clips()), ("blend", blend_doc()), ("brushes", brushes_document()), + ("envelopes", envelopes_document()), ] } @@ -7109,6 +7110,124 @@ fn every_effect_a_graphic_style_holds_is_read_back() { assert!(p.contains("7.5 /Real (moveV_Pts) ,") && p.contains("0.5236 /Real (rotate_Radians) ,"), "{p}"); } +/// An embedded 8 × 8 image of a color ramp, `Photo`, 80 pt square at (20, 10) in `doc`, at half +/// opacity, with `effects`. +fn warped_photo(doc: &mut Document, effects: Vec) -> Node { + let ramp = image::RgbImage::from_fn(8, 8, |x, y| image::Rgb([(x * 32) as u8, (y * 32) as u8, 160])); + let mut photo = image_node(doc, ImageBlob::png(png_of(ramp.into())), (8, 8), Affine::new([10.0, 0.0, 0.0, 10.0, 20.0, 10.0]), None); + photo.name = Some("Photo".into()); + photo.opacity = 0.5; + photo.appearance = Appearance { effects, ..Appearance::default() }.into(); + photo +} + +/// A 200 × 100 document holding `photo`, made by [`warped_photo`]. +fn photo_doc(photo: impl FnOnce(&mut Document) -> Node) -> Document { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let n = photo(&mut doc); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + doc +} + +/// An embedded image with one Warp is written with an art style of that Warp, its bent pieces as its +/// drawn look and the image itself on `%_` lines: it reads back as the image, its pixels, placement, +/// name and opacity as they were, with its Warp live and its settings kept. +#[test] +fn an_image_with_a_warp_reads_back_with_its_warp_live() { + // GUARDS: an image with a Warp was written as its drawn pieces alone, and read back without its Warp. + for (id, params) in [ + ("warp.arc", serde_json::json!({"bend": 40.0})), + ("warp.flag", serde_json::json!({"bend": -30.0, "horizontal": 10.0, "vertical": 0.0, "orientation": "vertical"})), + ] { + let doc = photo_doc(|d| warped_photo(d, vec![fx(id, params.clone())])); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::EFFECTS), "{id}: {:?}", out.warnings); + let back = read_back(&doc); + let art = back.layers[0].children().unwrap(); + assert_eq!(art.len(), 1, "{id}: {:#?} {:?}", lines(&back), out.warnings); + let (mut want, mut got) = (vec![], vec![]); + pictures(&doc, doc.layers[0].children().unwrap(), "", &mut want); + pictures(&back, art, "", &mut got); + assert_eq!(got, want, "{id}"); + let [warp] = art[0].appearance.effects.as_slice() else { panic!("{id}: {:?}", art[0].appearance) }; + assert_eq!(warp.id, id); + let (w, g) = (vectorcraft_effects::merged_params(id, ¶ms), vectorcraft_effects::merged_params(&warp.id, &warp.params)); + for key in ["bend", "horizontal", "vertical"] { + assert!((g[key].as_f64().unwrap() - w[key].as_f64().unwrap()).abs() < 6e-3, "{id} {key}: {g} for {w}"); + } + assert_eq!(g["orientation"], w["orientation"], "{id}"); + } +} + +/// An image whose style's Warp bends it another way than its drawn look keeps that look, with the +/// note, and the file as written opens with the image. +#[test] +fn an_image_whose_warp_draws_otherwise_than_its_look_keeps_its_look() { + // GUARDS: an image read with its Warp live whatever its drawn look showed. + let doc = photo_doc(|d| warped_photo(d, vec![fx("warp.arc", serde_json::json!({"bend": 40.0}))])); + let program = export_ai_editing(&doc, &opts()).unwrap().program; + let (from, to) = (b"0.4 /Real (DeformValue)".as_slice(), b"-0.4 /Real (DeformValue)".as_slice()); + let at = program.windows(from.len()).position(|w| w == from).expect("the warp's bend"); + let mut other = program.clone(); + other.splice(at..at + from.len(), to.iter().copied()); + let (back, warnings) = crate::ai_alone(&other).unwrap(); + let art = back.layers[0].children().unwrap(); + assert_eq!(art.len(), 1, "{art:#?}"); + assert!(matches!(art[0].kind, NodeKind::Group { .. }), "the drawn look: {:?}", art[0].kind); + assert!(art[0].appearance.effects.is_empty(), "{:?}", art[0].appearance); + assert!(warnings.iter().any(|w| w.contains("drawn look")), "{warnings:?}"); + let (back, _) = crate::ai_alone(&program).unwrap(); + assert!(matches!(back.layers[0].children().unwrap()[0].kind, NodeKind::Image(_))); +} + +/// An image on `%_` lines is the copy of a styled object, as other objects there are: with a style +/// the file doesn't define, its drawn look stands for it, named as it is, and the image doesn't come +/// in beside the look. +#[test] +fn an_image_on_hidden_lines_does_not_come_in_beside_its_look() { + // GUARDS: an image whose samples were on `%_` lines came in as a second, visible object. + let doc = photo_doc(|d| warped_photo(d, vec![fx("warp.arc", serde_json::json!({"bend": 40.0}))])); + let program = export_ai_editing(&doc, &opts()).unwrap().program; + let (from, to) = (b"1 (Anon 1) XW".as_slice(), b"1 (Unknown) XW".as_slice()); + let at = program.windows(from.len()).position(|w| w == from).expect("the image's style"); + let mut unknown = program.clone(); + unknown.splice(at..at + from.len(), to.iter().copied()); + let (back, _) = crate::ai_alone(&unknown).unwrap(); + let art = back.layers[0].children().unwrap(); + assert_eq!(art.len(), 1, "{:#?}", lines(&back)); + assert!(matches!(art[0].kind, NodeKind::Group { .. }), "the drawn look: {:?}", art[0].kind); + assert_eq!(art[0].name.as_deref(), Some("Photo")); +} + +/// A linked image, an image with an opacity mask, and an image with a Warp and another effect are +/// written as their drawn art, with no art style. +#[test] +fn other_warped_images_are_written_as_their_drawn_art() { + let arc = || fx("warp.arc", serde_json::json!({"bend": 40.0})); + let linked = photo_doc(|d| { + let mut n = warped_photo(d, vec![arc()]); + if let NodeKind::Image(im) = &mut n.kind { + im.link = Some(vectorcraft_doc::LinkInfo::new("/art/photo.png")); + } + n + }); + let masked = photo_doc(|d| { + let mut n = warped_photo(d, vec![arc()]); + let white = + Node::path(d.alloc_id(), shapes::rectangle(Rect::new(20.0, 10.0, 100.0, 90.0)), Appearance::basic(solid(Color::WHITE), Paint::None, 0.0)); + n.extras_mut().mask = Some(Box::new(OpacityMask::new(white, false))); + n + }); + let stacked = photo_doc(|d| warped_photo(d, vec![arc(), fx("stylize.feather", serde_json::json!({"radius": 2.0}))])); + for (what, doc) in [("linked", linked), ("masked", masked), ("stacked", stacked)] { + assert!(!program_shown(&doc).contains("1 (Anon"), "{what}"); + let back = read_back(&doc); + let art = back.layers[0].children().unwrap(); + assert!(art.iter().all(|n| n.appearance.effects.is_empty()), "{what}: {art:#?}"); + } +} + /// Every kind of appearance a style isn't written for is written as its drawn look, with a warning. #[test] fn appearances_written_as_their_drawn_look() { @@ -9055,3 +9174,446 @@ fn spread_gradients_past_the_stops_the_reader_reads_stay_gradients() { let Some(Paint::Gradient(swatch)) = back.swatch("Bands").map(|s| &s.paint) else { panic!("the swatch is lost") }; assert!((200..=crate::import::MAX_GRADIENT_STOPS).contains(&swatch.gradient.stops.len()), "{} stops", swatch.gradient.stops.len()); } + +/// An envelope named `Bent` of `kind` around a red rectangle (40, 20)-(100, 80) and a blue one +/// (100, 20)-(160, 80), with Fidelity `fidelity`, Edit Contents `editing` and `options`. +fn envelope_node( + doc: &mut Document, + kind: vectorcraft_doc::live::EnvelopeKind, + fidelity: f64, + editing: bool, + options: vectorcraft_doc::live::EnvelopeOptions, +) -> Node { + let content = vec![ + Arc::new(square(doc, Rect::new(40.0, 20.0, 100.0, 80.0), Color::rgb(1.0, 0.0, 0.0))), + Arc::new(square(doc, Rect::new(100.0, 20.0, 160.0, 80.0), Color::rgb(0.0, 0.0, 1.0))), + ]; + let kind = NodeKind::Envelope { content, kind: Box::new(kind), fidelity, editing, options, frame: Box::default() }; + named(Node::new(doc.alloc_id(), kind), "Bent") +} + +/// A 200 × 100 document of envelope `kind` ([`envelope_node`]) alone. +fn envelope_doc( + kind: vectorcraft_doc::live::EnvelopeKind, + fidelity: f64, + editing: bool, + options: vectorcraft_doc::live::EnvelopeOptions, +) -> Document { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let envelope = envelope_node(&mut doc, kind, fidelity, editing, options); + doc.insert(Some(layer), usize::MAX, envelope).unwrap(); + doc +} + +/// A grid of `rows`×`cols` patches over (30, 10)-(170, 90), row by row from the top left, with its +/// sixth point moved. +fn envelope_points(rows: u32, cols: u32) -> Vec { + let mut points: Vec = (0..=rows) + .flat_map(|r| { + (0..=cols).map(move |c| kurbo::Point::new(30.0 + 140.0 * f64::from(c) / f64::from(cols), 10.0 + 80.0 * f64::from(r) / f64::from(rows))) + }) + .collect(); + points[5] += kurbo::Vec2::new(5.0, -8.0); + points +} + +/// The envelopes written live: warps (vertical, with distortions, and twisted), meshes (with +/// handles of their own, one handle uneven, and with the smooth ones), top objects (a curved top +/// side, and two segments to the top and bottom sides), with Edit Contents off and on. +fn live_envelope_kinds() -> Vec<(&'static str, vectorcraft_doc::live::EnvelopeKind)> { + use vectorcraft_doc::live::{EnvelopeKind, H_RIGHT, WARP_NET, smooth_handles}; + let warp = |style: &str, bend: f64, h: f64, v: f64, horizontal: bool| EnvelopeKind::Warp { + style: style.into(), + bend, + h, + v, + horizontal, + version: WARP_NET, + }; + let points = envelope_points(2, 3); + let mut handles = smooth_handles(2, 3, &points); + handles[5][H_RIGHT] += kurbo::Vec2::new(4.0, 6.0); + let mut curved = kurbo::BezPath::new(); + curved.move_to((30.0, 10.0)); + curved.curve_to((70.0, -5.0), (130.0, -5.0), (170.0, 10.0)); + curved.line_to((170.0, 90.0)); + curved.line_to((30.0, 90.0)); + curved.close_path(); + let mut six = kurbo::BezPath::new(); + six.move_to((30.0, 10.0)); + for p in [(100.0, 0.0), (170.0, 10.0), (170.0, 90.0), (100.0, 95.0), (30.0, 90.0)] { + six.line_to(p); + } + six.close_path(); + vec![ + ("arc", warp("arc", 50.0, -20.0, 30.0, false)), + ("twist", warp("twist", -35.0, 0.0, 0.0, true)), + ("mesh", EnvelopeKind::Mesh { rows: 2, cols: 3, points: points.clone(), handles }), + ("smooth mesh", EnvelopeKind::Mesh { rows: 2, cols: 3, points, handles: vec![] }), + ("curved top object", EnvelopeKind::TopObject { path: PathData::from_bezpath(&curved), corners: None }), + ("six-anchor top object", EnvelopeKind::TopObject { path: PathData::from_bezpath(&six), corners: None }), + ] +} + +/// `doc` written and read back from its editing data: the top object on its first layer, the +/// writer's warnings and the reader's notes. +fn envelope_back(doc: &Document) -> (Node, Vec, Vec) { + let (p, warnings) = private_data(doc, &opts()).unwrap(); + let (back, notes) = crate::ai_alone(&p.data).unwrap(); + let a = back.layers[0].children().unwrap(); + assert_eq!(a.len(), 1, "{a:#?}"); + ((*a[0]).clone(), warnings, notes) +} + +/// Does reopened envelope kind `got` have the shape of `want`: a warp's style, bend, distortions +/// and orientation; a mesh's grid and the handles that draw (those inside the grid); the patch a top +/// object's outline makes? +fn same_envelope_kind(want: &vectorcraft_doc::live::EnvelopeKind, got: &vectorcraft_doc::live::EnvelopeKind) -> bool { + use vectorcraft_doc::live::{Coons, EnvelopeKind, H_DOWN, H_LEFT, H_RIGHT, H_UP, smooth_handles}; + let near = |a: kurbo::Point, b: kurbo::Point| a.distance(b) < 1e-3; + match (want, got) { + ( + EnvelopeKind::Warp { style, bend, h, v, horizontal, version }, + EnvelopeKind::Warp { style: s, bend: b, h: dh, v: dv, horizontal: hz, version: ver }, + ) => style == s && horizontal == hz && version == ver && [(bend, b), (h, dh), (v, dv)].iter().all(|(x, y)| (*x - *y).abs() < 1e-9), + (EnvelopeKind::Mesh { rows, cols, points, handles }, EnvelopeKind::Mesh { rows: r, cols: c, points: p, handles: hs }) => { + let own = if handles.is_empty() { smooth_handles(*rows, *cols, points) } else { handles.clone() }; + let inside = |i: usize, slot: usize| { + let (row, col) = (i / (*cols as usize + 1), i % (*cols as usize + 1)); + match slot { + s if s == H_LEFT => col > 0, + s if s == H_RIGHT => col < *cols as usize, + s if s == H_UP => row > 0, + s if s == H_DOWN => row < *rows as usize, + _ => false, + } + }; + (rows, cols) == (r, c) + && points.len() == p.len() + && points.iter().zip(p).all(|(a, b)| near(*a, *b)) + && own.iter().zip(hs).enumerate().all(|(i, (a, b))| (0..4).all(|s| !inside(i, s) || near(a[s].to_point(), b[s].to_point()))) + } + (EnvelopeKind::TopObject { path, corners }, EnvelopeKind::TopObject { path: p, corners: c }) => { + let (Some(a), Some(b)) = (Coons::from_top_object(path, *corners), Coons::from_top_object(p, *c)) else { return false }; + (0..=8).all(|j| { + (0..=8).all(|i| a.eval(f64::from(i) / 8.0, f64::from(j) / 8.0).distance(b.eval(f64::from(i) / 8.0, f64::from(j) / 8.0)) < 1e-2) + }) + } + _ => false, + } +} + +/// A PDF-compatible `.ai`'s editing data keeps a warp, a mesh and a top object envelope live, with +/// Edit Contents off and on: VectorCraft's reader opens each as the same envelope, its contents, +/// Fidelity, Edit Contents, Envelope Options and shape as saved, and its name, the drawn art saved +/// with it drawing as the envelope does. +#[test] +fn envelopes_are_read_back_live() { + use vectorcraft_doc::live::EnvelopeOptions; + for (name, kind) in live_envelope_kinds() { + for editing in [false, true] { + let doc = envelope_doc(kind.clone(), 50.0, editing, EnvelopeOptions::NEW); + let (back, warnings, notes) = envelope_back(&doc); + let what = format!("{name}, editing {editing}"); + assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{what}: {warnings:?}"); + assert!(!notes.iter().any(|w| w == crate::import::ENVELOPE_DRAWN), "{what}: {notes:?}"); + let NodeKind::Envelope { content, kind: got, fidelity, editing: e, options, frame } = &back.kind else { panic!("{what}: {back:#?}") }; + assert_eq!((*fidelity, *e, *options, **frame), (50.0, editing, EnvelopeOptions::NEW, Affine::IDENTITY), "{what}"); + assert!(same_envelope_kind(&kind, got), "{what}: {got:?}"); + assert_eq!(back.name.as_deref(), Some("Bent"), "{what}"); + let colors: Vec> = content.iter().map(|c| c.appearance.fill_paint().color()).collect(); + assert_eq!(colors, [Some(Color::rgb(1.0, 0.0, 0.0)), Some(Color::rgb(0.0, 0.0, 1.0))], "{what}"); + // Saved again as it opened (a top object now with the corners the file gives it), it + // opens as the same envelope again. + let mut again = Document::new(200.0, 100.0); + let layer = again.layers[0].id; + again.insert(Some(layer), usize::MAX, back.clone()).unwrap(); + let (twice, warnings, notes) = envelope_back(&again); + assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{what}, saved again: {warnings:?}"); + let NodeKind::Envelope { kind: twice, .. } = &twice.kind else { panic!("{what}, saved again: {twice:#?} {notes:?}") }; + assert!(same_envelope_kind(&kind, twice), "{what}, saved again: {twice:?}"); + } + } +} + +/// An envelope that is a symbol's art is written live in the symbol's definition, and the symbol +/// opens with it as a live envelope. +#[test] +fn an_envelope_in_a_symbol_is_read_back_live() { + use vectorcraft_doc::live::EnvelopeOptions; + let kinds = live_envelope_kinds(); + for (name, kind) in kinds { + let mut doc = Document::new(200.0, 100.0); + let art = envelope_node(&mut doc, kind.clone(), 50.0, false, EnvelopeOptions::NEW); + doc.symbols.push(Symbol { dynamic: false, name: "Bent".into(), art: Arc::new(art) }); + let instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Bent".into(), xf: Affine::translate((10.0, 5.0)) }); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, instance).unwrap(); + let (p, warnings) = private_data(&doc, &opts()).unwrap(); + assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{name}: {warnings:?}"); + let (back, notes) = crate::ai_alone(&p.data).unwrap(); + let symbol = back.symbols.iter().find(|s| s.name == "Bent").unwrap_or_else(|| panic!("{name}: {:?}", back.symbols)); + let mut envelopes = vec![]; + symbol.art.walk(&mut |n| { + if let NodeKind::Envelope { kind, .. } = &n.kind { + envelopes.push((**kind).clone()); + } + }); + assert!(matches!(envelopes.as_slice(), [k] if same_envelope_kind(&kind, k)), "{name}: {envelopes:?} {notes:?}"); + } +} + +/// An envelope with an opacity mask comes back live with its mask, and the plugin's `XP` follows +/// the envelope's dictionary rather than its mask's art. +#[test] +fn an_envelope_with_an_opacity_mask_is_read_back_live() { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions}; + let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] }; + let mut doc = Document::new(200.0, 100.0); + let mut envelope = envelope_node(&mut doc, kind.clone(), 50.0, false, EnvelopeOptions::NEW); + let gray = square(&mut doc, Rect::new(40.0, 20.0, 160.0, 80.0), Color::gray(0.5)); + let art = group(&mut doc, vec![gray], false); + envelope.extras_mut().mask = Some(Box::new(OpacityMask::new(art, false))); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, envelope).unwrap(); + let text = program(&doc); + let (xp, mask) = (text.find(") 1 0 0 XP").unwrap_or(0), text.find("(AI9_Mask)").unwrap_or(usize::MAX)); + assert!(mask < xp, "{text}"); + let (back, warnings, notes) = envelope_back(&doc); + assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}"); + let NodeKind::Envelope { kind: got, .. } = &back.kind else { panic!("{back:#?} {notes:?}") }; + assert!(same_envelope_kind(&kind, got), "{got:?}"); + assert!(back.extras().mask.is_some(), "{back:#?}"); +} + +/// As many envelopes are written live as the reader checks in one file, and the ones after them +/// as their art, with a warning. +#[test] +fn envelopes_past_the_readers_checks_are_written_as_their_art() { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions}; + let limit = crate::import::ENVELOPE_CHECKS; + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + for _ in 0..=limit { + let points = [(30.0, 10.0), (170.0, 0.0), (30.0, 90.0), (170.0, 90.0)].map(kurbo::Point::from).to_vec(); + let kind = EnvelopeKind::Mesh { rows: 1, cols: 1, points, handles: vec![] }; + let envelope = envelope_node(&mut doc, kind, 50.0, false, EnvelopeOptions::NEW); + doc.insert(Some(layer), usize::MAX, envelope).unwrap(); + } + let (p, warnings) = private_data(&doc, &opts()).unwrap(); + assert!(warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}"); + let (back, notes) = crate::ai_alone(&p.data).unwrap(); + let a = back.layers[0].children().unwrap(); + let live = a.iter().filter(|n| matches!(n.kind, NodeKind::Envelope { .. })).count(); + assert_eq!((a.len(), live), (limit + 1, limit), "{notes:?}"); + assert!(!notes.iter().any(|n| n == crate::import::ENVELOPE_DRAWN), "{notes:?}"); +} + +/// Every Envelope Options switch and the ends of Fidelity come back as saved. +#[test] +fn envelope_options_and_fidelity_are_read_back() { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions, PreserveShape}; + let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] }; + let new = EnvelopeOptions::NEW; + let all = [ + (new, 50.0), + (EnvelopeOptions { anti_alias: false, ..new }, 0.0), + (EnvelopeOptions { preserve_shape: PreserveShape::Transparency, ..new }, 100.0), + (EnvelopeOptions { distort_linear_gradients: true, distort_pattern_fills: true, ..new }, 30.0), + (EnvelopeOptions { distort_appearance: false, ..new }, 50.0), + ]; + for (options, fidelity) in all { + let (back, _, notes) = envelope_back(&envelope_doc(kind.clone(), fidelity, false, options)); + let NodeKind::Envelope { options: o, fidelity: f, .. } = &back.kind else { panic!("{options:?}: {back:#?} {notes:?}") }; + assert_eq!((*o, *f), (options, fidelity)); + } +} + +/// With Distort Appearance, an envelope whose contents map from their bounds with their strokes +/// saves that box's size, and opens mapping from the same box. +#[test] +fn an_envelope_mapping_from_its_contents_strokes_is_read_back() { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions, envelope_content_boxes, envelope_stroke_margin}; + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut envelope = envelope_node( + &mut doc, + EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] }, + 50.0, + false, + EnvelopeOptions::NEW, + ); + let NodeKind::Envelope { content, options, .. } = &mut envelope.kind else { unreachable_envelope() }; + for c in content.iter_mut() { + let fill = Arc::make_mut(c).appearance.fill_paint(); + Arc::make_mut(c).appearance = Appearance::basic(fill, solid(Color::BLACK), 8.0).into(); + } + let (stroked, plain) = envelope_content_boxes(content, Affine::IDENTITY).unwrap(); + options.bounds_margin = envelope_stroke_margin(stroked, plain).unwrap(); + let margin = options.bounds_margin; + assert!(margin.iter().all(|m| *m > 0.0), "{margin:?}"); + doc.insert(Some(layer), usize::MAX, envelope).unwrap(); + let (back, warnings, notes) = envelope_back(&doc); + assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}"); + let NodeKind::Envelope { options, .. } = &back.kind else { panic!("{back:#?} {notes:?}") }; + assert!(options.bounds_margin.iter().zip(margin).all(|(a, b)| (a - b).abs() < 1e-4), "{:?} {margin:?}", options.bounds_margin); +} + +/// A test's stand-in for a node that must be an envelope. +fn unreachable_envelope() -> ! { + panic!("not an envelope") +} + +/// The record is written in the order the reader reads it: on `%_` lines the group holding the +/// grid, its dictionary with the options, the contents' block and the kind, then the distorted art +/// on plain lines and the plugin's `XP`. While the contents are edited, the group holds them and +/// the dictionary the grid. +#[test] +fn an_envelope_is_written_in_the_order_the_reader_reads_it() { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions}; + let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] }; + for editing in [false, true] { + let text = program(&envelope_doc(kind.clone(), 50.0, editing, EnvelopeOptions::NEW)); + let at = |s: &str| text.find(s).unwrap_or_else(|| panic!("{s} missing: {text}")); + let (group, mesh, dictionary, block, key, style, xp) = ( + at("%_u\n"), + at("%_/Mesh X!"), + at("%_131073 /Int (AIDeformOptionsKey) ,\n%_50 /Int (AIDeformFidelityKey) ,\n"), + at("%_X=\n"), + at("%_ (AIDeformArtKey) ,\n"), + at("%_2 /Int (AIDeformStyle) ,\n%_;\n%_\n%_9 () XW\n"), + at("(Adobe Deform Plugin) 1 0 0 XP\n"), + ); + assert!(group < dictionary && dictionary < block && block < key && key < style && style < xp, "{text}"); + assert_eq!(block < mesh, editing, "{text}"); + assert!(text.contains(&format!("%_{} /Bool (AIDeformEditModeKey) ,\n", u8::from(editing))), "{text}"); + // The distorted art is one group on plain lines, named as the envelope, right before the `XP`. + let drawn = &text[style..xp]; + assert!(drawn.contains("\nu\n") && drawn.contains("(Bent) ; (AI10_ArtUID) ,"), "{drawn}"); + // The contents are on `%_` lines only: drawn once on plain lines, as the distorted art. + assert_eq!(text.matches("(Adobe Deform Plugin)").count(), 1, "{text}"); + } +} + +/// Envelopes the reader would open in another shape, or not at all, are written as their distorted +/// art with a warning, and open as that art: an envelope of type, one in a turned frame, a warp drawn +/// without its style's net, a mesh the reader would lay out the other way round, a top object +/// whose sides don't pair up, a Fidelity that isn't a whole number and bounds margins kept with +/// Distort Appearance off. Other live objects keep their own warning. +#[test] +fn envelopes_the_reader_cannot_open_live_are_written_as_their_art() { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions}; + let base = + || envelope_doc(EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] }, 50.0, false, EnvelopeOptions::NEW); + let change = |f: &dyn Fn(&mut NodeKind)| { + let mut doc = base(); + let id = doc.layers[0].children().unwrap()[0].id; + f(&mut doc.node_mut(id).unwrap().kind); + doc + }; + let typed = change(&|k| { + if let NodeKind::Envelope { content, .. } = k { + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(50.0, 50.0), "Type", vectorcraft_doc::CharStyle::default()); + content.push(Arc::new(Node::new(vectorcraft_doc::NodeId(9_000), NodeKind::Text(Box::new(t))))); + } + }); + let turned = change(&|k| { + if let NodeKind::Envelope { frame, .. } = k { + **frame = Affine::rotate(0.3); + } + }); + let old_warp = change(&|k| { + if let NodeKind::Envelope { kind, .. } = k { + **kind = EnvelopeKind::Warp { style: "arc".into(), bend: 50.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }; + } + }); + // Columns down the page and rows across: the reader turns the grid round. + let sideways = change(&|k| { + if let NodeKind::Envelope { kind, .. } = k { + let points = + (0..=3).flat_map(|r| (0..=2).map(move |c| kurbo::Point::new(30.0 + 70.0 * f64::from(c), 10.0 + 80.0 * f64::from(r) / 3.0))).collect(); + **kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: transpose(points, 3, 2), handles: vec![] }; + } + }); + let mut uneven = kurbo::BezPath::new(); + uneven.move_to((30.0, 10.0)); + for p in [(100.0, 0.0), (170.0, 10.0), (170.0, 90.0), (30.0, 90.0)] { + uneven.line_to(p); + } + uneven.close_path(); + let lopsided = change(&|k| { + if let NodeKind::Envelope { kind, .. } = k { + **kind = EnvelopeKind::TopObject { path: PathData::from_bezpath(&uneven), corners: None }; + } + }); + let fractional = change(&|k| { + if let NodeKind::Envelope { fidelity, .. } = k { + *fidelity = 50.5; + } + }); + let margin_kept = change(&|k| { + if let NodeKind::Envelope { options, .. } = k { + options.distort_appearance = false; + options.bounds_margin = [0.5; 4]; + } + }); + let cases = [ + ("type", typed), + ("turned", turned), + ("old warp", old_warp), + ("sideways mesh", sideways), + ("lopsided top object", lopsided), + ("fractional fidelity", fractional), + ("margin kept", margin_kept), + ]; + for (what, doc) in cases { + let text = program(&doc); + assert!(!text.contains("AIDeformOptionsKey"), "{what}: {text}"); + let (back, warnings, _) = envelope_back(&doc); + assert!(warnings.iter().any(|w| w == writer::ENVELOPES), "{what}: {warnings:?}"); + assert!(!warnings.iter().any(|w| w == writer::LIVE), "{what}: {warnings:?}"); + assert!(matches!(back.kind, NodeKind::Group { .. }), "{what}: {back:#?}"); + } + let blend = export_ai_editing(&blend_doc(), &opts()).unwrap(); + assert!(blend.warnings.iter().any(|w| w == writer::LIVE) && !blend.warnings.iter().any(|w| w == writer::ENVELOPES), "{:?}", blend.warnings); +} + +/// `points`, a grid of `rows + 1` rows of `cols + 1` points, as `cols + 1` rows of `rows + 1`. +fn transpose(points: Vec, rows: usize, cols: usize) -> Vec { + (0..=cols).flat_map(|c| (0..=rows).map(move |r| (r, c))).map(|(r, c)| points[r * (cols + 1) + c]).collect() +} + +/// An envelope with its contents in an opacity mask's art is written as its art there, and an +/// envelope in a group stays live. +#[test] +fn envelopes_in_masks_are_written_as_their_art_and_in_groups_stay_live() { + let doc = envelopes_document(); + let (p, warnings) = private_data(&doc, &opts()).unwrap(); + let (back, notes) = crate::ai_alone(&p.data).unwrap(); + assert!(warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}"); + let mut live = 0; + back.walk(|n| live += usize::from(matches!(n.kind, NodeKind::Envelope { .. }))); + assert_eq!(live, 3, "{notes:?}"); +} + +/// A warp, a mesh envelope with its contents edited, a top object in a group, and an envelope in an +/// opacity mask's art. +fn envelopes_document() -> Document { + use vectorcraft_doc::live::EnvelopeOptions; + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let kinds = live_envelope_kinds(); + let kind = |name: &str| kinds.iter().find(|(n, _)| *n == name).map(|(_, k)| k.clone()).unwrap(); + let warp = envelope_node(&mut doc, kind("arc"), 50.0, false, EnvelopeOptions::NEW); + let mesh = envelope_node(&mut doc, kind("mesh"), 50.0, true, EnvelopeOptions::NEW); + let top = envelope_node(&mut doc, kind("six-anchor top object"), 50.0, false, EnvelopeOptions::NEW); + let top = group(&mut doc, vec![top], false); + let mut masked = square(&mut doc, Rect::new(0.0, 0.0, 200.0, 100.0), Color::gray(0.5)); + let mask_art = envelope_node(&mut doc, kind("twist"), 50.0, false, EnvelopeOptions::NEW); + masked.extras_mut().mask = Some(Box::new(OpacityMask::new(mask_art, false))); + for n in [warp, mesh, top, masked] { + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + doc +} diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index c78c3e6542..cd0455f10f 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -16,6 +16,7 @@ use crate::ai_ops::{self, unit}; use crate::ps; mod brushes; +mod envelopes; mod images; mod paints; mod styles; @@ -25,6 +26,8 @@ mod variables; #[cfg(test)] pub(super) use brushes::BRUSHES; +#[cfg(test)] +pub(super) use envelopes::ENVELOPES; pub(super) use styles::{LARGE_CANVAS_STYLES, style_links, styled_objects}; #[cfg(test)] pub(super) use styles::{PANEL_EMPTY, PANEL_STYLES, STYLE_LINKS, same_appearance}; @@ -52,8 +55,7 @@ pub(super) const PATTERN_TILES: &str = "pattern fills with more tiles than a fil pub(super) const CLIPPING: &str = "clipping groups and clipping layers whose clipping object isn't a path, and the clipping groups inside them, are written as their art cut to that object in the editing data for other apps"; pub(super) const CLIP_PAINT: &str = "the fills and strokes of clipping paths that a plain fill and line can't draw are written as paths of their own inside the clipping (fills under the clipped art, strokes over it) in the editing data for other apps"; pub(super) const CLIP_PAINT_MASKS: &str = "the opacity masks of clipping paths whose fills and strokes are written as paths of their own stay on the clipping path, not on those paths, in the editing data for other apps"; -pub(super) const LIVE: &str = - "blends, envelopes, meshes, repeats, placed documents and intertwines are written as their art in the editing data for other apps"; +pub(super) const LIVE: &str = "blends, meshes, repeats, placed documents and intertwines are written as their art in the editing data for other apps"; pub(super) const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps"; pub(super) const ITEM_TRANSPARENCY: &str = "the opacity and blending modes of single fills and strokes are left out of the editing data for other apps"; @@ -262,6 +264,12 @@ pub(super) struct Writer<'a> { brush_set: brushes::Brushes, /// Brushes may be written; false on a large canvas, where they are left out. pub(super) brushes_live: bool, + /// The object just written is an envelope's distorted art, which the plugin's `XP` follows + /// ([`Self::envelope`]). + deform: bool, + /// How many more envelopes may be written live: as many as the reader checks in one file + /// ([`crate::import::ENVELOPE_CHECKS`]). + envelopes_left: usize, } impl<'a> Writer<'a> { @@ -319,6 +327,8 @@ impl<'a> Writer<'a> { in_look: false, brush_set: brushes::Brushes::default(), brushes_live: true, + deform: false, + envelopes_left: crate::import::ENVELOPE_CHECKS, objects: 0, left_out: 0, definition_objects: 0, @@ -694,29 +704,16 @@ impl<'a> Writer<'a> { } self.end_group("U", xy); } - NodeKind::Blend { .. } - | NodeKind::Envelope { .. } - | NodeKind::Mesh(_) - | NodeKind::Repeat(_) - | NodeKind::PlacedDocument(_) - | NodeKind::Intertwine { .. } => { - if !self.open_group("u") { - return; - } - self.warn(LIVE); - if self.nest < MAX_NEST { - let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n); - self.nest += 1; - for c in g.children().map(Vec::as_slice).unwrap_or_default() { - self.node(c); - } - self.nest -= 1; - } - self.end_group("U", xy); + NodeKind::Envelope { .. } if self.envelope(n, xy) => {} + NodeKind::Envelope { .. } => self.drawn_art(n, xy, Some(envelopes::ENVELOPES)), + NodeKind::Blend { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) | NodeKind::Intertwine { .. } => { + self.drawn_art(n, xy, Some(LIVE)); } // Ruler guides are kept in the document's native copy only. NodeKind::RulerGuide { .. } => {} } + // Taken before the dictionary, whose opacity mask art may hold envelopes of its own. + let deform = std::mem::take(&mut self.deform); if self.body.len() > start { // A group's dictionary goes between its end and its state block. let block = (self.block_end == self.body.len() && self.block_start >= start).then(|| self.body.split_off(self.block_start)); @@ -726,6 +723,29 @@ impl<'a> Writer<'a> { self.body.push_str(&b); } } + // An envelope's plugin `XP` follows its distorted art, after the art's state block. + if deform { + self.line(&envelopes::plugin_line()); + } + } + + /// Live object `n`, of transparency `xy`, as a group of its art, with `warning` when it is given. + fn drawn_art(&mut self, n: &Node, xy: Xy, warning: Option<&str>) { + if !self.open_group("u") { + return; + } + if let Some(w) = warning { + self.warn(w); + } + if self.nest < MAX_NEST { + let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n); + self.nest += 1; + for c in g.children().map(Vec::as_slice).unwrap_or_default() { + self.node(c); + } + self.nest -= 1; + } + self.end_group("U", xy); } /// `n`'s `/ArtDictionary`, after it, when it has a name (`AI10_ArtUID`, see [`Self::take_id`]), diff --git a/crates/eps/src/ai_editing/writer/envelopes.rs b/crates/eps/src/ai_editing/writer/envelopes.rs new file mode 100644 index 0000000000..dcd7274291 --- /dev/null +++ b/crates/eps/src/ai_editing/writer/envelopes.rs @@ -0,0 +1,395 @@ +//! Envelopes (see [`crate::ai_editing`] for the form), written in the form VectorCraft's `.ai` +//! reader opens as live envelopes again: on `%_` lines a group holding the grid that shapes the +//! envelope (while its contents are edited, the contents), then that group's `/ArtDictionary` with +//! Envelope Options as a bit word (`AIDeformOptionsKey`), Fidelity (`AIDeformFidelityKey`), Edit +//! Contents (`AIDeformEditModeKey`), a warp's style, bend, distortions and orientation +//! (`DeformStyle`, `DeformValue`, `DeformHoriz`, `DeformVert`, `Rotate`), with Distort Appearance +//! the size of the box the contents map from (`AIDeformArtWidthKey`, `AIDeformArtHeightKey`), the +//! contents in an `X=` … `X+` block (while they are edited, the grid) as `AIDeformArtKey`, and the +//! kind (`AIDeformStyle`: 1 a warp, 2 a mesh, 3 a top object); then the distorted art on plain +//! lines, and the plugin's `XP` after it. A top object's outline is the edge of the grid written +//! for it, one grid edge to each segment of its sides. An envelope the reader would open in another +//! shape is written as its distorted art. + +use std::fmt::Write; +use std::sync::Arc; + +use kurbo::{Point, Vec2}; +use vectorcraft_doc::live::{ + Coons, EnvelopeKind, EnvelopeOptions, GradientMesh, H_DOWN, H_LEFT, H_RIGHT, H_UP, MeshPoint, PreserveShape, WARP_NET, envelope_content_boxes, + envelope_grid, envelope_stroke_margin, warp_grid, +}; +use vectorcraft_doc::{Node, NodeKind}; +use vectorcraft_geom::{Affine, PathData}; + +use super::{MAX_NEST, Writer, Xy, hide}; +use crate::import::{DEFORM_PLUGIN, EnvelopeGridPoint as GridPoint, envelope_outline, envelope_upright, warp_number}; +use crate::ps; + +pub(in crate::ai_editing) const ENVELOPES: &str = "envelopes of type, envelopes without contents, envelopes in opacity masks, pattern tiles, art cut to a clipping object or other envelopes' contents, envelopes on the layers of a large canvas or in a turned or mirrored frame, warps drawn without their style's net, meshes and top objects that the data would open in another shape, envelopes with a Fidelity that isn't a whole number, envelopes that map from a box other than their contents' bounds with or without strokes or keep bounds margins with Distort Appearance off, envelopes after the first 256, and envelopes nested more than 8 deep are written as their art in the editing data for other apps"; + +/// The most rows or columns of an envelope's grid written (Make with Mesh's own limit, and the +/// reader's). +const MAX_GRID: usize = 50; +/// How far, as a share of the diagonal of a top object's patch, the patch on the outline written for +/// it may lie from its own at any of the places checked. +const TOP_OBJECT_TOLERANCE: f64 = 1e-6; +/// How far apart two bounds margins may be and still count as the same. +const MARGIN_SLACK: f32 = 1e-5; + +/// What an envelope's dictionary holds besides its contents: the entries before the contents' block, +/// each on a line of its own, the kind (`AIDeformStyle`) and the grid that shapes it (`rows`, `cols` +/// and its points with their handles, row by row from the top left, in the document), when it has +/// one. +struct Record { + keys: String, + style: u8, + grid: Option<(usize, usize, Vec)>, +} + +/// The `XP` that ends an envelope, after its distorted art. +pub(super) fn plugin_line() -> String { + format!("{} 1 0 0 XP", ps::bytes(DEFORM_PLUGIN.as_bytes())) +} + +/// Does `n`, or anything in it, hold type? +fn holds_type(n: &Node) -> bool { + matches!(n.kind, NodeKind::Text(_)) || n.children().is_some_and(|c| c.iter().any(|k| holds_type(k))) +} + +/// The record of envelope `n` (its parts given), or `None` where the reader would open it in +/// another shape than it has, or not as an envelope. +fn record( + n: &Node, + content: &[Arc], + kind: &EnvelopeKind, + fidelity: f64, + editing: bool, + options: &EnvelopeOptions, + frame: Affine, +) -> Option { + // The reader reads Fidelity as a whole number from 0 to 100, and bounds margins only with + // Distort Appearance on. + let whole = (0.0..=100.0).contains(&fidelity) && fidelity.fract() == 0.0; + let margin_kept = !options.distort_appearance && options.bounds_margin != [0.0; 4]; + if content.is_empty() || frame != Affine::IDENTITY || !whole || margin_kept || content.iter().any(|c| holds_type(c)) { + return None; + } + let mut keys = String::new(); + let bit = |on: bool, at: u32| i64::from(on) << at; + let word = bit(options.distort_appearance, 0) + | bit(options.distort_pattern_fills, 1) + | bit(options.distort_linear_gradients, 2) + | bit(!options.anti_alias, 16) + | bit(options.preserve_shape == PreserveShape::ClippingMask, 17); + let _ = writeln!(keys, "{word} /Int (AIDeformOptionsKey) ,"); + let _ = writeln!(keys, "{} /Int (AIDeformFidelityKey) ,", fidelity as i64); + let _ = writeln!(keys, "{} /Bool (AIDeformEditModeKey) ,", u8::from(editing)); + let real = |keys: &mut String, v: f64, key: &str| { + ps::push_num_places(keys, v, 9); + let _ = writeln!(keys, " /Real ({key}) ,"); + }; + let (style, grid) = match kind { + EnvelopeKind::Warp { style, bend, h, v, horizontal, version } => { + let fraction = |p: f64| (p.is_finite() && (-100.0..=100.0).contains(&p)).then_some(p / 100.0); + let (number, bend, h, v) = (warp_number(style)?, fraction(*bend)?, fraction(*h)?, fraction(*v)?); + if *version != WARP_NET { + return None; + } + let _ = writeln!(keys, "{number} /Int (DeformStyle) ,"); + real(&mut keys, h, "DeformHoriz"); + real(&mut keys, bend, "DeformValue"); + real(&mut keys, v, "DeformVert"); + let _ = writeln!(keys, "{} /Bool (Rotate) ,", u8::from(!*horizontal)); + // The grid of the warp's shape, for apps that read it. + (1, warp_grid(n).and_then(|m| as_read(&m)).and_then(|(rows, cols, pts)| sized(rows, cols).map(|(r, c)| (r, c, pts)))) + } + EnvelopeKind::Mesh { rows, cols, points, handles } => { + let (r, c) = sized(*rows, *cols)?; + let mesh = envelope_grid(*rows, *cols, points, handles)?; + let pts = as_read(&mesh)?.2; + // The reader lays the grid out with its first row at the top and its first column at the + // left: a grid it would lay out another way round would map the contents another way. + if !reads_as_written(r, c, &pts) { + return None; + } + (2, Some((r, c, pts))) + } + EnvelopeKind::TopObject { path, corners } => (3, Some(top_object_grid(path, *corners)?)), + }; + if options.distort_appearance { + let (stroked, plain) = envelope_content_boxes(content, Affine::IDENTITY)?; + let margin = options.bounds_margin; + let same = |m: [f32; 4]| m.iter().zip(margin).all(|(a, b)| (a - b).abs() <= MARGIN_SLACK); + // The reader maps from the size written when it matches the contents' bounds with their + // strokes, and from their geometric bounds otherwise. + let size = if margin == [0.0; 4] { + plain + } else if stroked != plain && envelope_stroke_margin(stroked, plain).is_some_and(same) { + stroked + } else { + return None; + }; + real(&mut keys, size.height(), "AIDeformArtHeightKey"); + real(&mut keys, size.width(), "AIDeformArtWidthKey"); + } + Some(Record { keys, style, grid }) +} + +/// `rows` and `cols` as sizes, when the reader reads a grid of them. +fn sized(rows: u32, cols: u32) -> Option<(usize, usize)> { + let (r, c) = (usize::try_from(rows).ok()?, usize::try_from(cols).ok()?); + ((1..=MAX_GRID).contains(&r) && (1..=MAX_GRID).contains(&c)).then_some((r, c)) +} + +/// The points of grid `m` with their handles as the reader reads them back: the handles that point +/// out of the grid, which nothing draws with, are left at the point. `None` for a grid of points +/// or handles that aren't finite. +fn as_read(m: &GradientMesh) -> Option<(u32, u32, Vec)> { + let (rows, cols) = (m.rows as usize, m.cols as usize); + let finite = |v: Vec2| v.x.is_finite() && v.y.is_finite(); + let mut pts = Vec::with_capacity(m.points.len()); + for (i, q) in m.points.iter().enumerate() { + if !finite(q.p.to_vec2()) || !q.handles.iter().all(|h| finite(*h)) { + return None; + } + let (r, c) = (i / (cols + 1), i % (cols + 1)); + let mut h = q.handles; + for (slot, out) in [(H_LEFT, c == 0), (H_RIGHT, c == cols), (H_UP, r == 0), (H_DOWN, r == rows)] { + if out && let Some(h) = h.get_mut(slot) { + *h = Vec2::ZERO; + } + } + pts.push((q.p, h)); + } + Some((m.rows, m.cols, pts)) +} + +/// Does the reader lay out grid `pts` (`rows`×`cols` patches) as it is written? +fn reads_as_written(rows: usize, cols: usize, pts: &[GridPoint]) -> bool { + let points = + pts.iter().map(|(p, handles)| MeshPoint { p: *p, color: vectorcraft_color::Color::BLACK, opacity: 1.0, handles: *handles }).collect(); + let mesh = GradientMesh { rows: rows as u32, cols: cols as u32, points }; + envelope_upright(&mesh).is_some_and(|(r, c, read)| (r as usize, c as usize) == (rows, cols) && read == pts) +} + +/// The grid a top object with outline `path` and corners `corners` is written with: its edge runs +/// through the outline's anchors clockwise from the top left corner, one grid edge to a segment, so +/// the top and bottom sides need as many segments as each other, as do the left and right sides; +/// the points inside blend the sides. `None` where that grid's edge, read back as the top object's +/// outline, doesn't give the same patch ([`Coons::from_top_object`]) at every place checked. +fn top_object_grid(path: &PathData, corners: Option<[u32; 4]>) -> Option<(usize, usize, Vec)> { + let coons = Coons::from_top_object(path, corners)?; + // The outline, as the patch takes it: the largest subpath. + let mut sp = path.subpaths.iter().filter(|s| s.anchors.len() >= 2).max_by(|a, b| a.area().abs().total_cmp(&b.area().abs()))?.clone(); + let count = sp.anchors.len(); + let empty = |i: usize| { + let c = sp.segment(i); + [c.p1, c.p2, c.p3].iter().all(|p| p.distance(c.p0) <= 1e-9) + }; + if !sp.closed || count < 4 || (0..count).any(empty) { + return None; + } + let fits = |c: &[usize; 4]| { + c.iter().all(|i| *i < count) && { + let gaps = (0..4).map(|k| (c[(k + 1) % 4] + count - c[k]) % count); + gaps.clone().all(|g| g > 0) && gaps.sum::() == count + } + }; + // Stored corners that fit keep the outline as drawn; otherwise it runs clockwise, and the + // corners are the anchors the patch's corners lie on. + let at = match corners.map(|c| c.map(|i| i as usize)).filter(fits) { + Some(c) => c, + None => { + if sp.signed_area() < 0.0 { + sp.reverse(); + } + let find = |q: Point| sp.anchors.iter().position(|a| a.p.distance(q) <= 1e-9); + let [tl, tr, br, bl] = coons.corners(); + let c = [find(tl)?, find(tr)?, find(br)?, find(bl)?]; + if !fits(&c) { + return None; + } + c + } + }; + let gap = |k: usize| (at[(k + 1) % 4] + count - at[k]) % count; + let (cols, rows) = (gap(0), gap(1)); + if gap(2) != cols || gap(3) != rows || cols > MAX_GRID || rows > MAX_GRID { + return None; + } + let width = cols + 1; + let mut pts: Vec = vec![(Point::ZERO, [Vec2::ZERO; 4]); (rows + 1) * width]; + // Where the `k`th anchor from the top left corner goes, and the slots of the handles of the + // segment from it to the next anchor: its own, and the next anchor's back. + let place = |k: usize| -> (usize, usize, usize, usize) { + if k < cols { + (0, k, H_RIGHT, H_LEFT) + } else if k < cols + rows { + (k - cols, cols, H_DOWN, H_UP) + } else if k < 2 * cols + rows { + (rows, cols - (k - cols - rows), H_LEFT, H_RIGHT) + } else { + (rows - (k - 2 * cols - rows), 0, H_UP, H_DOWN) + } + }; + for k in 0..count { + let i = (at[0] + k) % count; + let seg = sp.segment(i); + // A straight segment's patch spreads evenly along it, as a cubic's with its handles a third + // of the way does. + let (p1, p2) = if sp.segment_is_line(i) { (seg.p0.lerp(seg.p3, 1.0 / 3.0), seg.p0.lerp(seg.p3, 2.0 / 3.0)) } else { (seg.p1, seg.p2) }; + let (r, c, out, into) = place(k); + let (nr, nc, _, _) = place((k + 1) % count); + if let Some(q) = pts.get_mut(r * width + c) { + q.0 = seg.p0; + q.1[out] = p1 - seg.p0; + } + if let Some(q) = pts.get_mut(nr * width + nc) { + q.1[into] = p2 - seg.p3; + } + } + // The points inside, blended from the sides. + let edge = |r: usize, c: usize| pts.get(r * width + c).map_or(Point::ZERO, |q| q.0).to_vec2(); + let mut inside = vec![]; + for r in 1..rows { + for c in 1..cols { + let (u, v) = (c as f64 / cols as f64, r as f64 / rows as f64); + let p = (1.0 - v) * edge(0, c) + v * edge(rows, c) + (1.0 - u) * edge(r, 0) + u * edge(r, cols) + - ((1.0 - u) * (1.0 - v) * edge(0, 0) + u * (1.0 - v) * edge(0, cols) + (1.0 - u) * v * edge(rows, 0) + u * v * edge(rows, cols)); + inside.push((r * width + c, p.to_point())); + } + } + for (i, p) in inside { + if let Some(q) = pts.get_mut(i) { + q.0 = p; + } + } + if !pts.iter().all(|(p, h)| p.is_finite() && h.iter().all(|h| h.is_finite())) || !reads_as_written(rows, cols, &pts) { + return None; + } + // The top object the reader makes of the grid: its edge, with the corners of the grid. + let outline = envelope_outline(rows as u32, cols as u32, &pts)?; + let corners = [0, cols, cols + rows, 2 * cols + rows].map(|c| c as u32); + let read = Coons::from_top_object(&outline, Some(corners))?; + let [tl, tr, br, bl] = coons.corners(); + let reach = tl.distance(br).max(tr.distance(bl)).max(1.0) * TOP_OBJECT_TOLERANCE; + const STEPS: usize = 8; + let at = |i: usize| i as f64 / STEPS as f64; + let same = (0..=STEPS).all(|j| (0..=STEPS).all(|i| coons.eval(at(i), at(j)).distance(read.eval(at(i), at(j))) <= reach)); + same.then_some((rows, cols, pts)) +} + +impl Writer<'_> { + /// Envelope `n`, of transparency `xy`, as a live envelope (see the module's form), outside opacity + /// masks' art, pattern tiles, art cut to a clipping object and the layers of a large canvas. False, + /// writing nothing, where it is written as its art instead: where the reader would open it in + /// another shape, or some of it is left out for the object limit ([`Self::take_objects`]). + pub(super) fn envelope(&mut self, n: &Node, xy: Xy) -> bool { + let NodeKind::Envelope { content, kind, fidelity, editing, options, frame } = &n.kind else { return false }; + if self.hidden > 0 || self.clip.is_some() || self.nest >= MAX_NEST || !self.symbols_live || self.envelopes_left == 0 { + return false; + } + let Some(record) = record(n, content, kind, *fidelity, *editing, options, **frame) else { return false }; + let start = self.body.len(); + let (state, gs, charges, bound) = (self.state, self.gs, self.charges(), self.bound.len()); + self.nest += 1; + self.hidden += 1; + // The group before the dictionary: the grid, or the contents while they are edited. + let outer = std::mem::take(&mut self.body); + let opened = self.open_group("u"); + if opened { + if *editing { + self.contents(content); + } else { + self.grid(record.grid.as_ref()); + } + self.line("U"); + } + let before = std::mem::replace(&mut self.body, outer); + hide(&before, &mut self.body); + self.body.push_str("%_/ArtDictionary :\n"); + hide(&record.keys, &mut self.body); + self.body.push_str("%_X=\n"); + // The dictionary's art starts unlocked, shown and opaque, as an opacity mask's does. + let outer = std::mem::take(&mut self.body); + let at_block = self.state; + (self.state, self.gs) = (Some((false, false)), Some(Xy::OPAQUE)); + if *editing { + self.grid(record.grid.as_ref()); + } else if self.open_group("u") { + self.contents(content); + self.end_group("U", Xy::PLAIN); + } + let block = std::mem::replace(&mut self.body, outer); + hide(&block, &mut self.body); + (self.state, self.gs, self.block_end) = (at_block, None, usize::MAX); + let _ = writeln!(self.body, "%_X+\n%_ (AIDeformArtKey) ,\n%_{} /Int (AIDeformStyle) ,\n%_;\n%_\n%_9 () XW", record.style); + self.hidden -= 1; + self.nest -= 1; + // The distorted art, which takes the envelope's lock, visibility, transparency, name and + // opacity mask. + self.state(n.locked, !n.visible); + self.drawn_art(n, xy, None); + if !opened || self.left_out_since(charges) { + let lines = self.body.split_off(start); + self.give_back(charges, &lines); + self.bound.truncate(bound); + (self.state, self.gs, self.block_end) = (state, gs, usize::MAX); + return false; + } + self.deform = true; + self.envelopes_left -= 1; + true + } + + /// An envelope's contents. + fn contents(&mut self, content: &[Arc]) { + for c in content { + self.node(c); + } + } + + /// An envelope's grid, when it has one, as a gray gradient mesh (`/Mesh X!` … `/End X!`): its + /// size (`[cols rows] /Size`), then each patch's place (`[col row] /P`), its four corners + /// (`/N`: gray, opacity, the point, the handle towards the next corner and a weight, the handle + /// towards the previous one and a weight, in art space), from its top left one down, across and + /// up, and `/E`. One object. + fn grid(&mut self, grid: Option<&(usize, usize, Vec)>) { + let Some((rows, cols, pts)) = grid else { return }; + if !self.take_objects(1) { + return; + } + let (rows, cols, width) = (*rows, *cols, cols + 1); + let to_art = self.to_art; + let s = &mut self.body; + let _ = writeln!(s, "/Mesh X!\n2 /Version X#\n/Cartesian /Type X#\n[{cols} {rows}] /Size X#\n/Data X#\n/DeviceGray /CS X#"); + let num = |s: &mut String, v: f64| { + s.push(' '); + ps::push_num(s, v); + }; + for c in 0..cols { + for r in 0..rows { + let _ = writeln!(s, "[{c} {r}] /P X#"); + // Each corner with the slots of its handles towards the next corner and the previous one. + let corners = [((r, c), H_DOWN, H_RIGHT), ((r + 1, c), H_RIGHT, H_UP), ((r + 1, c + 1), H_UP, H_LEFT), ((r, c + 1), H_LEFT, H_DOWN)]; + for ((pr, pc), next, prev) in corners { + let (p, h) = pts.get(pr * width + pc).copied().unwrap_or((Point::ZERO, [Vec2::ZERO; 4])); + let at = |v: Vec2| to_art * (p + v); + s.push_str("[0 1"); + for q in [at(Vec2::ZERO), at(h[next])] { + num(s, q.x); + num(s, q.y); + } + s.push_str(" 1"); + let q = at(h[prev]); + num(s, q.x); + num(s, q.y); + s.push_str(" 1] /N X#\n"); + } + s.push_str("/E X#\n"); + } + } + s.push_str("/End X!\n"); + } +} diff --git a/crates/eps/src/ai_editing/writer/styles.rs b/crates/eps/src/ai_editing/writer/styles.rs index 29eb2bf910..fe3e68ce24 100644 --- a/crates/eps/src/ai_editing/writer/styles.rs +++ b/crates/eps/src/ai_editing/writer/styles.rs @@ -41,7 +41,8 @@ pub(in crate::ai_editing) fn style_links(doc: &Document) -> usize { /// The objects of `doc`'s layers that may be written with an art style ([`Writer::styled_object`]), /// by id: paths and compound paths with points and groups, with live effects, linked to a graphic -/// style or (paths and compound paths) with a brush on a stroke, without Opacity & Mask Define +/// style or (paths and compound paths) with a brush on a stroke, and embedded images with one Warp +/// ([`warped_image`]), without Opacity & Mask Define /// Knockout Shape (the reader takes an object's transparency /// from its look, which doesn't carry it). A group's members are paths, compound paths or such /// groups, none with effects or anything baking changes. @@ -86,10 +87,22 @@ fn candidate(n: &Node) -> bool { NodeKind::Path { path, guide: false, clipping: false, .. } => has_points(path), NodeKind::Compound { .. } => has_points(&compound_path(n)), NodeKind::Group { children, clip: false } => !n.is_compound_shape() && children.iter().all(|c| plain_member(c)), + NodeKind::Image(_) => warped_image(n), _ => false, } } +/// Is `n` an embedded image without an opacity mask whose appearance is one Warp, with no fills or +/// strokes that paint and no effects on them: an image the reader reads with its Warp live +/// ([`crate::import::read_art_style`]'s `image_warp`)? +fn warped_image(n: &Node) -> bool { + let NodeKind::Image(im) = &n.kind else { return false }; + im.link.is_none() + && n.extras().mask.is_none() + && matches!(n.appearance.effects.as_slice(), [e] if e.id.starts_with("warp.")) + && n.appearance.items.iter().all(|i| i.paint().is_none() && i.effects().is_empty()) +} + /// Does `n` have a stroke with a brush that paints, one that its art style holds ([`Writer::style_text`] /// leaves out what paints nothing)? fn brushed(n: &Node) -> bool { @@ -666,7 +679,7 @@ impl Writer<'_> { return Some(name); } let brushed = brushed(orig); - if (orig.appearance.effects.is_empty() && !brushed) || !own_style_holds(&orig.appearance) { + if (orig.appearance.effects.is_empty() && !brushed) || !(own_style_holds(&orig.appearance) || warped_image(orig)) { return None; } let graded = orig.appearance.items.iter().any(|i| matches!(i.paint(), Paint::Gradient(_))); @@ -704,7 +717,8 @@ impl Writer<'_> { /// glows or feathers, the object's transparency /// after the group's end, `0 0 Xd`, `6 () XW`); the object itself on `%_` lines (a path's or /// compound path's points painted with nothing, or with its gradient fill when its style has - /// one; a group with its members), its name and opacity mask; then `1 (name) XW`. + /// one; a group with its members; an image with its pixels), its name and opacity mask; then + /// `1 (name) XW`. /// The look's group and the object itself are counted first ([`Self::take_objects`]): without /// room for them, nothing is written, and the object counts neither as written with its graphic /// style nor as written with a brush on its stroke. @@ -712,7 +726,7 @@ impl Writer<'_> { let own = match &orig.kind { NodeKind::Path { path, .. } => super::object_count(path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()).count()), NodeKind::Compound { .. } => super::object_count(compound_path(orig).subpaths.iter().filter(|sp| !sp.anchors.is_empty()).count()), - NodeKind::Group { .. } => 1, + NodeKind::Group { .. } | NodeKind::Image(_) => 1, _ => 0, }; if !self.take_objects(1 + own) { @@ -752,13 +766,14 @@ impl Writer<'_> { let saved = std::mem::take(&mut self.body); self.hidden += 1; let fit = drawn_outline(n, orig).map(|p| p.bounding_box()); - // A path's objects were kept for it above; it counts them itself. + // A path's or an image's objects were kept for it above; it counts them itself. if !matches!(orig.kind, NodeKind::Group { .. }) { self.objects -= own; } match &orig.kind { NodeKind::Path { path, rule, .. } => self.styled_outline(orig, path, *rule, fit, xy), NodeKind::Compound { rule, .. } => self.styled_outline(orig, &compound_path(orig), *rule, fit, xy), + NodeKind::Image(im) => self.image(&self.doc.shown_image(orig, im), xy), NodeKind::Group { children, .. } => { self.line("u"); for c in children { @@ -847,7 +862,8 @@ fn object_rule(n: &Node) -> FillRule { /// Can appearance `ap` be written as a style of an object's own: fills and strokes that paint without /// transparency or effects of their own, and no Warp, Distort & Transform or Blur effect? Those -/// are written only in the Graphic Styles panel's styles. +/// are written only in the Graphic Styles panel's styles, apart from a Warp on an image +/// ([`warped_image`]). fn own_style_holds(ap: &Appearance) -> bool { let plain = |i: &AppearanceItem| i.opacity() >= 1.0 && i.blend() == BlendMode::Normal && i.effects().is_empty(); let panel_only = |e: &Effect| ["warp.", "distort.", "blur."].iter().any(|p| e.id.starts_with(p)); @@ -870,13 +886,16 @@ fn panel_reads(g: &GraphicStyle, text: &str) -> bool { /// Does the reader read object `n` written with style text `text` as it is: a path or compound /// path with a style it reads on any object, filled by the non-zero rule when the style fills it, /// or a group with no fills or strokes of its own, with effects that move the outline only where the -/// reader reads them ([`crate::import::style_moves_with`])? +/// reader reads them ([`crate::import::style_moves_with`]), or an image ([`warped_image`]) with a +/// style of one Warp? The reader takes such an image's Warp where it draws as its drawn look. fn object_reads(n: &Node, text: &str) -> bool { let section = known_style("x", text); let own = n.appearance.fill().map(|f| &f.paint).filter(|p| matches!(p, Paint::Gradient(_))); let Some(mut read) = crate::import::read_art_style(section.as_bytes(), "x", own) else { return false }; let group = matches!(n.kind, NodeKind::Group { .. }); - if !read.simple + let image = matches!(n.kind, NodeKind::Image(_)); + if (image && !(read.image_warp && warped_image(n))) + || (!image && !read.simple) || (group && !read.appearance.items.is_empty()) || (!group && read.pathfinder) || !crate::import::style_moves_with(section.as_bytes(), "x", n) diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index 2cc4bed521..bdb3b9cf50 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -82,12 +82,15 @@ use graphics::{GState, Out}; use interp::{Fault, Interp}; use obj::PsError; +#[cfg(test)] +pub(crate) use ai::ENVELOPE_DRAWN; pub use ai::NameEncoding; #[cfg(test)] pub(crate) use ai::objects_read; pub(crate) use ai::{ - BRUSH_MANAGER, BrushesRead, MAX_EDITING_OBJECTS, MAX_GRADIENT_STOPS, MAX_LISTED, MAX_LISTED_NAME, MAX_SYMBOLS, brush_plugin_name, brushes_kept, - read_art_style, read_brush_object, read_style_list, style_moves_with, symbol_art_member, warp_number, + BRUSH_MANAGER, BrushesRead, DEFORM_PLUGIN, EnvelopeGridPoint, MAX_CHECKED as ENVELOPE_CHECKS, MAX_EDITING_OBJECTS, MAX_GRADIENT_STOPS, + MAX_LISTED, MAX_LISTED_NAME, MAX_SYMBOLS, brush_plugin_name, brushes_kept, envelope_outline, envelope_upright, read_art_style, read_brush_object, + read_style_list, style_moves_with, symbol_art_member, warp_number, }; pub(crate) use ate::{MAX_BYTES as MAX_TEXT_DOCUMENT, MAX_FRAMES, MAX_SEGMENTS, MAX_STORY, MAX_VALUES as MAX_TEXT_VALUES, record_version}; pub use native::{AiLayers, ai_alone, ai_alone_on_page, ai_alone_with, ai_layers_alone, ai_opened_artboard, is_loss, layered_ai, layered_ai_from}; diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index 2d6c4a533d..a3de7560e3 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -36,9 +36,9 @@ use crate::ps; pub(crate) use brush::{BrushesRead, MANAGER_NAME as BRUSH_MANAGER, brushes_kept, plugin_name as brush_plugin_name, read_brush_object}; pub(crate) use envelope::DRAWN as ENVELOPE_DRAWN; -#[cfg(test)] pub(crate) use envelope::MAX_CHECKED; pub(crate) use envelope::TYPE_DRAWN as ENVELOPE_TYPE_DRAWN; +pub(crate) use envelope::{GridPoint as EnvelopeGridPoint, PLUGIN as DEFORM_PLUGIN, outline as envelope_outline, upright as envelope_upright}; pub(crate) use envelope::{WARPED_TYPE_DRAWN, WarpedType}; pub(crate) use frames::text_frames; pub use obj::{NameEncoding, Names}; diff --git a/crates/eps/src/import/ai/envelope.rs b/crates/eps/src/import/ai/envelope.rs index edb9bba3e3..741ebfabdf 100644 --- a/crates/eps/src/import/ai/envelope.rs +++ b/crates/eps/src/import/ai/envelope.rs @@ -41,7 +41,7 @@ use super::obj::Obj; use crate::import::native::compare::{MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, compare_scale, differ, differ_in_colour, differ_on_black}; /// The plugin that writes envelopes. -pub(super) const PLUGIN: &str = "Adobe Deform Plugin"; // brand-ok: the plugin name the files use +pub(crate) const PLUGIN: &str = "Adobe Deform Plugin"; // brand-ok: the plugin name the files use /// The note for an envelope that keeps its drawn art. pub(crate) const DRAWN: &str = "an envelope VectorCraft couldn't read as a live envelope comes in as its drawn art"; /// The note for an envelope of type, which keeps its drawn art with its type hidden (unless the @@ -366,12 +366,12 @@ fn only_mesh(n: &Node) -> Option<&GradientMesh> { } /// A grid point and its handles. -type GridPoint = (Point, [Vec2; 4]); +pub(crate) type GridPoint = (Point, [Vec2; 4]); /// The points of mesh `m` as a `rows`×`cols` grid with its first row at the top and its first /// column at the left (y down), as an envelope's mesh lays them out; `None` for a grid out of range /// or with points that aren't finite. -fn upright(m: &GradientMesh) -> Option<(u32, u32, Vec)> { +pub(crate) fn upright(m: &GradientMesh) -> Option<(u32, u32, Vec)> { let (mut rows, mut cols) = (m.rows, m.cols); if rows == 0 || cols == 0 || rows > MAX_GRID || cols > MAX_GRID { return None; @@ -451,7 +451,7 @@ fn upright(m: &GradientMesh) -> Option<(u32, u32, Vec)> { } /// The outline of an upright grid: its edge, clockwise from the top left corner. -fn outline(rows: u32, cols: u32, pts: &[GridPoint]) -> Option { +pub(crate) fn outline(rows: u32, cols: u32, pts: &[GridPoint]) -> Option { let at = |r: u32, c: u32| pts.get((r * (cols + 1) + c) as usize).copied(); // Each edge: from a point by one of its handles to the next point by one of its handles. type Edge = ((u32, u32), usize, (u32, u32), usize); diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 3721ce7960..4b2936f56e 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -483,6 +483,9 @@ struct Reader<'a> { /// a global process colour, so these make swatches only for names no colour operator defines. stop_spots: Vec, raster: Option, + /// The samples of the image being read are on `%_` lines (`%_%%BeginData`): it is the copy of + /// a styled object there, as the other objects on those lines are. + image_hidden: bool, /// The file `XG` names for the image after it (`XF`), until an image is read. image_link: Option, /// The placed file being read (`%AI5_BeginPlace` … `~`). @@ -736,6 +739,7 @@ impl<'a> Reader<'a> { spots: Vec::new(), stop_spots: Vec::new(), raster: None, + image_hidden: false, image_link: None, place: None, foreign_data: None, @@ -846,7 +850,7 @@ impl<'a> Reader<'a> { self.op(w, hidden)?; } Tok::Comment(c) => self.comment(c, hidden)?, - Tok::Data(d) => self.image(d)?, + Tok::Data(d) => self.image(d, hidden)?, Tok::Preview(d) => { if let Some(p) = self.place.as_mut() { p.preview = preview_png(d); diff --git a/crates/eps/src/import/ai/read/art.rs b/crates/eps/src/import/ai/read/art.rs index 3d859bf74e..7e0f91e993 100644 --- a/crates/eps/src/import/ai/read/art.rs +++ b/crates/eps/src/import/ai/read/art.rs @@ -370,15 +370,18 @@ impl<'a> Reader<'a> { // ---- images ---------------------------------------------------------------------------- - /// The samples after `XI`, its operands on the stack. - pub(super) fn image(&mut self, data: &[u8]) -> Result<(), String> { + /// The samples after `XI`, its operands on the stack; `hidden` when they are on `%_` lines. + pub(super) fn image(&mut self, data: &[u8], hidden: bool) -> Result<(), String> { let vals = self.operands(); // Operands that came before an `XI` on their own line. let vals = match self.raster.as_mut().and_then(|r| r.operands.take()) { Some(before) if !vals.iter().any(|v| matches!(v, V::Arr(_))) => before, _ => vals, }; - self.image_from(vals, data, false) + self.image_hidden = hidden; + let read = self.image_from(vals, data, false); + self.image_hidden = false; + read } /// The matrix and the numbers of an image's operands (`[a b c d tx ty] llx lly urx ury w h bits @@ -713,7 +716,8 @@ impl<'a> Reader<'a> { /// Add the image `blob` (`w` × `h` pixels), which the matrix `m` maps into art space, with /// `alpha` (its alpha channel, one byte a pixel) as its opacity mask when it hides part of the - /// image, and `colorize` as the color that colorizes it. + /// image, and `colorize` as the color that colorizes it. It is on `%_` lines when its samples + /// are ([`Self::image`]). fn add_raster(&mut self, blob: ImageBlob, alpha: Option<&[u8]>, m: &[f64], (w, h): (u32, u32), colorize: Option) -> Result<(), String> { // The matrix is an art-space matrix (y up) applied to the pixels with their rows running // downwards, (u, -v): pixels → (u, -v) → art space. Flipping the matrix's result instead @@ -735,7 +739,8 @@ impl<'a> Reader<'a> { let key = blob.content_key(); self.doc.images.entry(key.clone()).or_insert(blob); let im = ImageObject { key, width: w, height: h, xf, link: None, placement: Default::default(), pixels: None }; - self.add_image_colorized(im, mask, colorize, false) + // An image on `%_` lines is the copy of a styled object, as the other objects there are. + self.add_image_colorized(im, mask, colorize, self.image_hidden) } /// An image that isn't read is left out, with `warning`; in a symbol's art, the symbol isn't diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 9f6a1dd6af..f79e7b9108 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -748,6 +748,7 @@ impl<'a> Reader<'a> { } let space = self.space(); self.note_brushes_kept(); + let page = self.page_in_doc(); let Some(f) = self.frames.last_mut() else { return }; let n = f.children.len(); let (Some(object), Some(look)) = (n.checked_sub(1).and_then(|i| f.children.get(i)), n.checked_sub(2).and_then(|i| f.children.get(i))) else { @@ -780,7 +781,7 @@ impl<'a> Reader<'a> { look }; // A style read here: the object, painted as it says. - if let Some(mut appearance) = self.styles.get(&style).and_then(|st| { + let appearance = self.styles.get(&style).and_then(|st| { styled( object, look, @@ -796,13 +797,32 @@ impl<'a> Reader<'a> { space, }, ) - }) { - // Strokes and effects at the document's scale, as the art (a Large Canvas copy's is scaled up). - let k = space.determinant().abs().sqrt(); - if k.is_finite() && k > 0.0 && (k - 1.0).abs() > 1e-9 { - appearance.scale_strokes(k); - appearance.scale_effects(k, vectorcraft_effects::scale_effect); + .map(|mut appearance| { + // Strokes and effects at the document's scale, as the art (a Large Canvas copy's is scaled up). + let k = space.determinant().abs().sqrt(); + if k.is_finite() && k > 0.0 && (k - 1.0).abs() > 1e-9 { + appearance.scale_strokes(k); + appearance.scale_effects(k, vectorcraft_effects::scale_effect); + } + appearance + }) + }); + // An image with a Warp is the object only where its live warp draws as its drawn look, and + // while the import has a check left for it; otherwise its drawn look stays. + let appearance = match appearance { + Some(ap) if matches!(object.kind, NodeKind::Image(_)) && ap.effects.iter().any(|e| e.id.starts_with("warp.")) => { + let alike = self.envelope_checks > 0 && { + self.envelope_checks -= 1; + let layer = self.doc.alloc_id(); + let shared = crate::import::ai::envelope::Shared { patterns: &self.doc.patterns, images: &self.doc.images }; + let shown = !hidden && object.visible && look.visible; + image_warp_alike(object, &ap, look, &self.hidden_ids, hidden, layer, &shared, page.filter(|_| shown), &mut self.envelope_spent) + }; + alike.then_some(ap) } + other => other, + }; + if let Some(appearance) = appearance { let Some(mut object) = f.children.pop() else { return }; let Some(look) = f.children.pop() else { return }; let left_out = look.visual_bounds().filter(|_| !hidden && object.visible && look.visible); @@ -1116,6 +1136,41 @@ fn moves_with(object: &Node, st: &crate::import::ai::style::ArtStyle) -> bool { }) } +/// Is `object` an image without an opacity mask, and `st` one Warp on it with nothing else that +/// paints ([`crate::import::ai::style::ArtStyle::image_warp`])? Such an image is read with its Warp +/// live where that draws as its drawn look ([`image_warp_alike`]). +fn image_warps(object: &Node, st: &crate::import::ai::style::ArtStyle) -> bool { + matches!(object.kind, NodeKind::Image(_)) && object.extras().mask.is_none() && st.image_warp +} + +/// Does image `object` with `appearance` (its style's Warp) draw as `look`, its drawn look, compared +/// over all that the warp draws ([`crate::import::ai::envelope::warped_alike`]) on `layer`, a layer +/// id no other node has? Both are drawn shown, opaque and in the Normal mode. Unless the look is on +/// `%_` lines itself (`hidden`), the copies in it that are on `%_` lines (`hidden_ids`) are left out. +#[allow(clippy::too_many_arguments)] +fn image_warp_alike( + object: &Node, + appearance: &Appearance, + look: &Node, + hidden_ids: &HashSet, + hidden: bool, + layer: NodeId, + shared: &crate::import::ai::envelope::Shared<'_>, + page: Option, + spent: &mut crate::import::ai::envelope::Spent, +) -> bool { + let mut live = object.clone(); + live.appearance = appearance.clone().into(); + let mut plain = look.clone(); + if !hidden { + strip(&mut plain, hidden_ids); + } + for n in [&mut live, &mut plain] { + (n.visible, n.opacity, n.blend) = (true, 1.0, BlendMode::Normal); + } + crate::import::ai::envelope::warped_alike(&live, &plain, layer, shared, page, spent) +} + /// What [`placed_paints`] keys a pattern's name with, apart from the gradients' names. const PATTERN_KEY: &str = "\u{1}pattern "; @@ -1128,11 +1183,13 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p let slot = slot_of(object.name.as_deref()).is_some(); // Several fills and strokes, on a path or a compound path. let stacked = !slot && !st.simple && st.stacked && matches!(object.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }); + // One Warp on an image, checked against its drawn look by the caller ([`image_warp_alike`]). + let image_warp = !st.simple && image_warps(object, st); // A symbol instance draws its symbol's art: it keeps its drawn look. if !st.plain || matches!(object.kind, NodeKind::SymbolInstance { .. }) // A look with no outline in it to keep takes a variable-width stroke as the object's own. - || (!slot && !st.simple && !stacked && (!st.uneven || draws(look, &HashSet::new()))) + || (!slot && !st.simple && !stacked && !image_warp && (!st.uneven || draws(look, &HashSet::new()))) || (object.is_container() && !slot && !matches!(object.kind, NodeKind::Compound { .. }) && !st.items.is_empty()) || (st.pathfinder && (slot || !st.items.is_empty() || object.is_compound_shape() || !matches!(object.kind, NodeKind::Group { clip: false, .. }))) @@ -1266,6 +1323,9 @@ pub(crate) struct StyleRead { pub appearance: Appearance, /// An object other than type is read with it ([`crate::import::ai::style::ArtStyle::simple`]). pub simple: bool, + /// An image without an opacity mask is read with it where its live warp draws as its drawn + /// look ([`crate::import::ai::style::ArtStyle::image_warp`]). + pub image_warp: bool, /// It has Effect › Pathfinder effects, which only a group with no fills or strokes is read with. pub pathfinder: bool, /// The opacity, blending mode, isolation and knockout its blend filter gives. @@ -1310,7 +1370,7 @@ pub(crate) fn read_art_style(section: &[u8], name: &str, own_gradient: Option<&P s.brush = Some(brush); } } - Some(StyleRead { appearance, simple: st.simple, pathfinder: st.pathfinder, transparency: st.transparency }) + Some(StyleRead { appearance, simple: st.simple, image_warp: st.image_warp, pathfinder: st.pathfinder, transparency: st.transparency }) } /// Is art style `name` of `section` read on `object` as far as an effect that moves the outline @@ -1519,6 +1579,79 @@ mod tests { assert!(styled(&Node::new(NodeId(4), NodeKind::Image(Box::new(image))), &look, st, &paints).is_none()); } + /// The style `Fx`: `effects` (each a filter's name and its dictionary's keys) on the whole + /// object, over a fill and a stroke that `paints` turns on (`0 1`: the fill paints blue). + fn effects_style(effects: &[(&str, &str)], paints: &str) -> crate::import::ai::style::ArtStyle { + let filters: String = effects + .iter() + .map(|(name, keys)| { + format!("/BasicFilter :\n({name}) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n{keys}; /Dict ;\n /Part ,\n") + }) + .collect(); + let text = format!( + "%AI9_BeginArtStyles\n/KnownStyle :\n(Fx) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + {filters}/CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/StrokeStyle : 0 1 0 0 0 Xy\n0 0 Xd\n/Def ;\n (StrokeStyle) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n0 0 0 0 0 0 1 Xa\n{paints} Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ + ;\n /Part ,\n;\n%AI9_EndArtStyles\n" + ); + crate::import::ai::style::art_styles(text.as_bytes()).remove("Fx").unwrap_or_default() + } + + /// An image takes a style of one Warp, under fills and strokes that paint nothing, and no + /// other style with a geometry effect: those keep its drawn look. A path, and an image with an + /// opacity mask, keep their drawn look with the Warp too. + #[test] + fn an_image_takes_a_style_of_one_warp_alone() { + // GUARDS: an image with a Warp in its art style came in as its drawn look. + let warp = ("Adobe Deform", "1 /Int (DeformStyle) ,\n0.4 /Real (DeformValue) ,\n"); // brand-ok: the filter's name in the files + let (gradients, patterns, names, v7_patterns, bending) = + (HashMap::new(), HashMap::new(), ShownNames::default(), HashSet::new(), HashSet::new()); + let paints = StylePaints { + gradients: &gradients, + patterns: &patterns, + names: &names, + v7_patterns: &v7_patterns, + brushes: &[], + kept: &[], + bending: &bending, + space: Affine::IDENTITY, + }; + let look = Node::group(NodeId(1), vec![square(2, Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)))]); + let image = + ImageObject { key: "a".into(), width: 1, height: 1, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; + let image = Node::new(NodeId(4), NodeKind::Image(Box::new(image))); + let st = effects_style(&[warp], "0 0"); + assert!(st.image_warp && !st.simple, "{st:?}"); + let ap = styled(&image, &look, &st, &paints).expect("an image takes one Warp"); + let ids: Vec<&str> = ap.effects.iter().map(|e| e.id.as_str()).collect(); + assert_eq!(ids, ["warp.arc"]); + assert!(ap.items.iter().all(|i| i.paint().is_none()), "{ap:?}"); + // Not on a path, nor on an image with an opacity mask. + assert!(styled(&square(3, Paint::None), &look, &st, &paints).is_none()); + let mut masked = image.clone(); + masked.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(Node::group(NodeId(7), vec![]), true))); + assert!(styled(&masked, &look, &st, &paints).is_none()); + // A Warp over a fill that paints, a Warp with another effect, and the other geometry effects. + let still = ("Adobe Punk and Bloat", "0 /Real (d_factor) ,\n"); + let others: [(&[(&str, &str)], &str); 8] = [ + (&[warp], "0 1"), + (&[warp, still], "0 0"), + (&[still, warp], "0 0"), + (&[("Adobe Twirl", "45 /Real (angle) ,\n")], "0 0"), + (&[("Adobe Free Distort", "")], "0 0"), + (&[("Adobe Punk and Bloat", "-50 /Real (d_factor) ,\n")], "0 0"), + (&[("Adobe Zigzag", "3 /Real (amount) ,\n1 /Real (absoluteness) ,\n")], "0 0"), + (&[("Adobe Transform", "5 /Real (moveH_Pts) ,\n0.5 /Real (rotate_Radians) ,\n0 /Bool (transformPatterns) ,\n")], "0 0"), + ]; + for (effects, painted) in others { + let st = effects_style(effects, painted); + assert!(!st.image_warp, "{effects:?} {painted}"); + assert!(styled(&image, &look, &st, &paints).is_none(), "{effects:?} {painted}"); + } + } + #[test] fn data_stops_at_its_end_or_a_marker_of_the_section() { let section = Some(("BeginTextDocument", "EndTextDocument")); diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs index 482c172386..d27a297925 100644 --- a/crates/eps/src/import/ai/style.rs +++ b/crates/eps/src/import/ai/style.rs @@ -193,6 +193,10 @@ pub(super) struct ArtStyle { /// the effects any object takes that don't move the outline: what a path or compound path is /// read with when each gradient is placed as its drawn look has it (`read::ops`' `styled`). pub stacked: bool, + /// It is one Warp on the whole object, under fills and strokes that paint nothing and have no + /// effects of their own: what an image is read with when its live warp draws as its drawn look + /// (`read::ops`' `styled`). + pub image_warp: bool, /// Its fills and strokes, bottom first. pub items: Vec, /// Each item's own visibility, transparency and effects, in the order of [`Self::items`]. @@ -1778,6 +1782,10 @@ fn style(filters: &[Filter]) -> ArtStyle { && st.items.iter().all(|i| matches!(i, StyleItem::Fill(_) | StyleItem::Gradient { .. } | StyleItem::Stroke { brush: None, .. })) && st.looks.iter().all(|l| l.effects.is_empty()) && st.effects.iter().all(any_object_takes); + st.image_warp = st.plain + && matches!(st.effects.as_slice(), [e] if e.id.starts_with("warp.")) + && st.items.iter().all(|i| matches!(i, StyleItem::Fill(p) | StyleItem::Stroke { paint: p, .. } if p.is_none())) + && st.looks.iter().all(|l| l.effects.is_empty()); st } diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 3c0ac39a05..9b86f38350 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -7730,6 +7730,55 @@ fn a_top_object_envelope_opens_live_with_its_outline() { assert!(r.warnings.is_empty(), "{:?}", r.warnings); } +/// A top object whose saved grid has three patches across, its top edge one curve split into +/// thirds, maps its contents along that one curve. In this synthetic file the drawn art is drawn by +/// VectorCraft's own map of the unsplit curve, so the envelope opens live only when the split side +/// maps the same way, and the contents' first quarter ends a quarter of the way along the curve. +#[test] +fn a_top_object_whose_top_is_one_curve_split_in_thirds_opens_live() { + use kurbo::{CubicBez, ParamCurve}; + use vectorcraft_doc::live::EnvelopeKind; + // In the document: the top runs from (40, 20) to (160, 20), its parameter fast at the start. + let top = CubicBez::new((40.0, 20.0), (112.0, -16.0), (154.0, 2.0), (160.0, 20.0)); + let thirds = [top.subsegment(0.0..1.0 / 3.0), top.subsegment(1.0 / 3.0..2.0 / 3.0), top.subsegment(2.0 / 3.0..1.0)]; + // Art space has y up: row 1 is the top. The bottom row and the columns are straight. + let up = |p: Point| (p.x, 100.0 - p.y); + let at = move |(i, j): (usize, usize)| { + if j == 1 { up(if i == 0 { top.p0 } else { thirds[i - 1].p3 }) } else { (40.0 + 40.0 * i as f64, 20.0) } + }; + let handle = move |p: (usize, usize), q: (usize, usize)| match (p, q) { + ((i, 1), (k, 1)) if k == i + 1 => up(thirds[i].p1), + ((i, 1), (k, 1)) if k + 1 == i => up(thirds[k].p2), + _ => { + let ((x, y), (u, v)) = (at(p), at(q)); + (x + (u - x) / 3.0, y + (v - y) / 3.0) + } + }; + let shape = mesh_text(3, 1, &at, &handle, None); + // The contents: two red bars at the box's left and right ends, drawn by the unsplit curve. + let mut bp = kurbo::BezPath::new(); + bp.move_to(top.p0); + bp.curve_to(top.p1, top.p2, top.p3); + bp.line_to((160.0, 80.0)); + bp.line_to((40.0, 80.0)); + bp.close_path(); + let one_curve = EnvelopeKind::TopObject { path: vectorcraft_geom::PathData::from_bezpath(&bp), corners: Some([0, 1, 2, 3]) }; + let src = Rect::new(40.0, 20.0, 160.0, 80.0); + let bars = [Rect::new(40.0, 20.0, 70.0, 80.0), Rect::new(130.0, 20.0, 160.0, 80.0)]; + let content: String = bars.iter().map(|b| format!("{RED}{}f\n", rect_path(b.x0, b.y0, b.x1, b.y1))).collect(); + let drawn: String = bars.iter().map(|b| drawn_box(&one_curve, src, *b)).collect(); + let r = read_ok(&layer(&envelope_of(&shape, ENVELOPE_KEYS, &content, 3, &drawn))); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let (_, kind, ..) = live_envelope(&a[0]); + let EnvelopeKind::TopObject { path, .. } = kind else { panic!("{kind:?}") }; + assert_eq!(path.anchor_count(), 8, "{path:?}"); + let map = vectorcraft_doc::live::envelope_mapper(kind, src); + let (p, want) = (map(Point::new(70.0, 20.0)), top.eval(0.25)); + assert!((p - want).hypot() < 0.02, "{p:?}, want {want:?}"); +} + /// Envelope Options come from the options word, Fidelity from its own key. #[test] fn an_envelope_reads_its_options_and_fidelity() { diff --git a/crates/eps/src/scene.rs b/crates/eps/src/scene.rs index e8ffa4b278..0ec561dd31 100644 --- a/crates/eps/src/scene.rs +++ b/crates/eps/src/scene.rs @@ -55,8 +55,99 @@ const MAX_DEVICE_N: usize = 32; const MISSING_PATTERN: &str = "missing patterns are written as mid-grey"; const TOO_LARGE: &str = "the artwork is too large for EPS: what follows 256 MB of PostScript was left out"; /// The most PostScript the page body may grow to: symbols and patterns that hold one another -/// expand into every instance, so nesting depth alone doesn't bound the output. +/// expand into every instance, so nesting depth alone doesn't bound the output. An image placed +/// more than once counts its data once. const MAX_BODY: usize = 256 << 20; +/// Most compressed bytes in one string of an image's samples at Level 2 (under PostScript's +/// 65,535-byte string limit). +const IMAGE_CHUNK: usize = 48 << 10; +/// The start of the procedure that reads an image's data from the lines after it. +const INLINE_SOURCE: &str = "{ /VCsrc currentfile /ASCII85Decode filter def\n"; + +/// An image as written: what sets up its color, its image dictionary and its compressed samples. +/// Placed once, it is written where it is drawn, its data following the operators that read it. +/// Placed more than once, its samples are written once in the setup as `VCim` (a reusable +/// stream at Level 3, an array of strings at Level 2) and each placement reads them from there. +struct ImageCode { + /// The color space or ink operators, each line ending in a line break. + prelude: String, + /// `<< /ImageType … /ImageMatrix […]` with its mask colors: the dictionary up to its data source. + dict: String, + /// The decoding filter of the samples: `/FlateDecode` or `/RunLengthDecode`. + filter: &'static str, + /// `image` or `imagemask`. + op: &'static str, + /// The compressed samples in ASCII85, as lines with the end marker. + ascii: String, + /// The compressed samples, kept at Level 2, where a reused image's samples are written as + /// strings of at most [`IMAGE_CHUNK`] bytes. + data: Vec, + /// How many placements in the page draw it. + uses: usize, + /// The length of [`ImageCode::push_inline`]'s text. + inline_len: usize, + /// The length of [`ImageCode::reference`]'s text. + ref_len: usize, +} + +impl ImageCode { + /// The operators and data that draw the image where it is placed. + fn push_inline(&self, s: &mut String) { + s.push_str(&self.prelude); + s.push_str(INLINE_SOURCE); + s.push_str(&self.dict); + s.push_str(&self.inline_read()); + s.push_str(&self.ascii); + } + + /// The end of the procedure [`ImageCode::push_inline`] writes. The procedure is read whole + /// before it runs: the image data follows it, and flushing the ASCII85 filter afterwards reads + /// past its end marker. + fn inline_read(&self) -> String { + format!("\n/DataSource VCsrc {} filter >> {}\nVCsrc flushfile }} exec\n", self.filter, self.op) + } + + /// The operators that draw the image `VCim` holds, for an image placed more than once. + fn reference(&self, i: usize, level: Level) -> String { + match level { + // The stream is read again from its start. + Level::Three => { + format!("{}VCim{i} resetfile\n{}\n/DataSource VCim{i} {} filter >> {}\n", self.prelude, self.dict, self.filter, self.op) + } + // A procedure gives the strings in turn, then an empty string: the end of the data. + Level::Two => format!( + "{}/VCi 0 def\n{}\n/DataSource {{VCi VCim{i} length lt {{VCim{i} VCi get /VCi VCi 1 add def}} {{()}} ifelse}} {} filter >> {}\n", + self.prelude, self.dict, self.filter, self.op + ), + } + } + + /// The setup's definition of `VCim`: the image's compressed samples, once. + fn resource(&self, i: usize, level: Level) -> String { + let mut s = String::with_capacity(self.ascii.len() + 200); + match level { + Level::Three => { + // The stream reads all of its data when it is made, so the data follows the + // procedure that makes it. + let intent = if self.op == "imagemask" { 1 } else { 0 }; + let _ = writeln!( + s, + "{{ /VCsrc currentfile /ASCII85Decode filter def\n/VCim{i} VCsrc << /Intent {intent} /AsyncRead false /CloseSource false >> /ReusableStreamDecode filter def\nVCsrc flushfile }} exec" + ); + s.push_str(&self.ascii); + } + Level::Two => { + let _ = writeln!(s, "/VCim{i} ["); + for chunk in self.data.chunks(IMAGE_CHUNK) { + s.push_str("<~"); + s.push_str(&ps::ascii85(chunk)); + } + s.push_str("] def\n"); + } + } + s + } +} /// What the walk wrote: definitions for the setup, the page, the spot colours it uses (name and /// CMYK equivalent) and the warnings. @@ -157,10 +248,18 @@ pub(crate) struct Scene<'a> { device_n: Vec, warnings: Vec, brushes: Option>, - /// Image keys → what draws them (`None`: left out). - images: HashMap>>, + /// Image keys → the index in `codes` of what draws them (`None`: left out). + images: HashMap>, /// The source key and solid paint together identify a colorized encoding. - colorized_images: HashMap<(String, String), Option>>, + colorized_images: HashMap<(String, String), Option>, + /// The encoded images. + codes: Vec, + /// Where in `body` each placement of an encoded image goes (in order) and the index of its code. + placements: Vec<(usize, usize)>, + /// What the placements in `placements` add to `body`'s length when the page is finished. + pending: usize, + /// The most the page body may grow to ([`MAX_BODY`]). + max_body: usize, /// Symbols and brush art being written inside one another. nest: u32, } @@ -181,10 +280,21 @@ impl<'a> Scene<'a> { brushes: None, images: HashMap::new(), colorized_images: HashMap::new(), + codes: vec![], + placements: vec![], + pending: 0, + max_body: MAX_BODY, nest: 0, } } + /// This scene with a page body of at most `max` bytes. + #[cfg(test)] + pub fn with_max_body(mut self, max: usize) -> Self { + self.max_body = max; + self + } + pub fn run(mut self) -> Page { let doc = self.doc; for l in &doc.layers { @@ -199,7 +309,27 @@ impl<'a> Scene<'a> { self.page() } - fn page(self) -> Page { + fn page(mut self) -> Page { + if !self.placements.is_empty() { + let level = self.o.level; + let mut body = String::with_capacity(self.body.len().saturating_add(self.pending)); + let mut at = 0; + for &(offset, i) in &self.placements { + body.push_str(self.body.get(at..offset).unwrap_or_default()); + at = offset; + let Some(code) = self.codes.get(i) else { continue }; + if code.uses > 1 { + body.push_str(&code.reference(i, level)); + } else { + code.push_inline(&mut body); + } + } + body.push_str(self.body.get(at..).unwrap_or_default()); + self.body = body; + for (i, code) in self.codes.iter().enumerate().filter(|(_, c)| c.uses > 1) { + self.setup.push_str(&code.resource(i, level)); + } + } let custom = self .spots .iter() @@ -337,7 +467,7 @@ impl<'a> Scene<'a> { if let NodeKind::Layer { template: true, .. } = n.kind { return; } - if self.body.len() >= MAX_BODY { + if self.size() >= self.max_body { self.warn(TOO_LARGE); return; } @@ -347,7 +477,7 @@ impl<'a> Scene<'a> { _ => {} } self.note_losses(n); - let was = self.body.len(); + let (was, placed) = (self.body.len(), self.placements.len()); match &n.kind { NodeKind::Layer { children, clip: false, .. } | NodeKind::Group { children, clip: false } => { children.iter().for_each(|c| self.node(c, false)); @@ -402,12 +532,29 @@ impl<'a> Scene<'a> { // Ruler guides draw on screen only. NodeKind::RulerGuide { .. } => {} } - if self.body.len() > MAX_BODY { + if self.size() > self.max_body { self.body.truncate(was); + self.unplace(placed); self.warn(TOO_LARGE); } } + /// How long the page body will be: what is written and what its image placements add. + fn size(&self) -> usize { + self.body.len().saturating_add(self.pending) + } + + /// Take back the image placements after the first `n`, last first. + fn unplace(&mut self, n: usize) { + while self.placements.len() > n { + let Some((_, i)) = self.placements.pop() else { break }; + let Some(code) = self.codes.get_mut(i) else { continue }; + code.uses = code.uses.saturating_sub(1); + let cost = if code.uses == 0 { code.inline_len } else { code.ref_len }; + self.pending = self.pending.saturating_sub(cost); + } + } + /// A clipping group: the art inside its first child's outline. The clipping path's fills /// paint behind the art (clipped) and its strokes over it (not clipped). fn clip_group(&mut self, children: &[Arc]) { @@ -1229,7 +1376,7 @@ impl<'a> Scene<'a> { }; let place = Affine::translate(area.origin().to_vec2()) * Affine::scale_non_uniform(area.width(), area.height()); if let Some(image) = image { - self.place_image(&image, place); + self.place_inline(&image, place); } } @@ -1241,18 +1388,29 @@ impl<'a> Scene<'a> { return; } let encoded = match self.images.get(key) { - Some(e) => e.clone(), + Some(e) => *e, None => { - let e = self.decode_image(blob).and_then(|img| self.encode_image(img.as_raw(), img.width(), img.height())).map(Arc::new); - self.images.insert(key.to_string(), e.clone()); + let e = self.decode_image(blob).and_then(|img| self.encode_image(img.as_raw(), img.width(), img.height())).map(|c| self.add_code(c)); + self.images.insert(key.to_string(), e); e } }; - if let Some(e) = encoded { - self.place_image(&e, place); + if let Some(i) = encoded { + self.place_image(i, place); } } + /// Keep `code` for the placements that draw it: its index in `codes`. + fn add_code(&mut self, mut code: ImageCode) -> usize { + let i = self.codes.len(); + if self.o.level == Level::Three { + code.data = vec![]; + } + code.ref_len = code.reference(i, self.o.level).len(); + self.codes.push(code); + i + } + /// Gray coverage in the selected process or Separation ink. Binary coverage is a stencil; /// continuous coverage leaves zero pixels untouched at Level 3 and writes them as paper at Level 2. fn colorized_image(&mut self, key: &str, blob: Option<&ImageBlob>, width: u32, height: u32, xf: Affine, paint: &Paint) { @@ -1262,19 +1420,19 @@ impl<'a> Scene<'a> { } let cache = (key.to_string(), format!("{paint:?}")); let encoded = match self.colorized_images.get(&cache) { - Some(e) => e.clone(), + Some(e) => *e, None => { - let e = self.encode_colorized(blob, paint).map(Arc::new); - self.colorized_images.insert(cache, e.clone()); + let e = self.encode_colorized(blob, paint).map(|c| self.add_code(c)); + self.colorized_images.insert(cache, e); e } }; - if let Some(e) = encoded { - self.place_image(&e, place); + if let Some(i) = encoded { + self.place_image(i, place); } } - fn encode_colorized(&mut self, blob: Option<&ImageBlob>, paint: &Paint) -> Option { + fn encode_colorized(&mut self, blob: Option<&ImageBlob>, paint: &Paint) -> Option { let Some((w, h, coverage)) = blob.and_then(ImageBlob::coverage) else { self.warn(UNDECODED); return None; @@ -1355,17 +1513,17 @@ impl<'a> Scene<'a> { ("/RunLengthDecode", rl) } }; - let mut out = String::new(); + let mut prelude = String::new(); if binary { // imagemask takes its current ink from the graphics state. - out.push_str(&self.ink_code(ink)); + prelude.push_str(&self.ink_code(ink)); } else { match ink { Ink::Spot { space, .. } => { - let _ = writeln!(out, "VCsp{space} setcolorspace"); + let _ = writeln!(prelude, "VCsp{space} setcolorspace"); } Ink::Process(space, ..) => { - let _ = writeln!(out, "{} setcolorspace", space.name()); + let _ = writeln!(prelude, "{} setcolorspace", space.name()); } } } @@ -1374,19 +1532,16 @@ impl<'a> Scene<'a> { Ink::Process(space, ..) => space.n(), }; let decode = if binary { "1 0".to_string() } else { "0 1 ".repeat(n).trim_end().to_string() }; - let _ = write!( - out, - "{{ /VCsrc currentfile /ASCII85Decode filter def\n<< /ImageType {} /Width {w} /Height {h} /BitsPerComponent {} /Decode [{decode}] /ImageMatrix [{w} 0 0 {h} 0 0]", + let mut dict = format!( + "<< /ImageType {} /Width {w} /Height {h} /BitsPerComponent {} /Decode [{decode}] /ImageMatrix [{w} 0 0 {h} 0 0]", if keyed { 4 } else { 1 }, if binary { 1 } else { 8 }, ); if keyed { let mask: Vec = key.iter().take(n).map(|v| format!("{v} {v}")).collect(); - let _ = write!(out, " /MaskColor [{}]", mask.join(" ")); + let _ = write!(dict, " /MaskColor [{}]", mask.join(" ")); } - let _ = writeln!(out, "\n/DataSource VCsrc {filter} filter >> {}\nVCsrc flushfile }} exec", if binary { "imagemask" } else { "image" }); - out.push_str(&ps::ascii85(&encoded)); - Some(out) + Some(image_code(prelude, dict, filter, if binary { "imagemask" } else { "image" }, encoded)) } /// Ink-setting operators in the cached stencil body, built with the same path as solid fills. @@ -1409,18 +1564,40 @@ impl<'a> Scene<'a> { Some(img.to_rgba8()) } - /// Draw an image of [`Self::encode_image`] on the unit square mapped by `place`. - fn place_image(&mut self, encoded: &str, place: Affine) { + /// Draw the image of `codes[i]` on the unit square mapped by `place`. Its operators go in when + /// the page is finished ([`Self::page`]), once it is known how many placements draw it. + fn place_image(&mut self, i: usize, place: Affine) { if !invertible(place) { return; } - if self.body.len().saturating_add(encoded.len()).saturating_add(64) > MAX_BODY { + let Some(code) = self.codes.get(i) else { return }; + let cost = if code.uses == 0 { code.inline_len } else { code.ref_len }; + if self.size().saturating_add(cost).saturating_add(64) > self.max_body { self.warn(TOO_LARGE); return; } self.line("q"); let _ = writeln!(self.body, "{} cm", ps::matrix(place)); - self.body.push_str(encoded); + self.placements.push((self.body.len(), i)); + self.pending = self.pending.saturating_add(cost); + if let Some(code) = self.codes.get_mut(i) { + code.uses += 1; + } + self.line("Q"); + } + + /// Draw `code`, an image drawn nowhere else, on the unit square mapped by `place`. + fn place_inline(&mut self, code: &ImageCode, place: Affine) { + if !invertible(place) { + return; + } + if self.size().saturating_add(code.inline_len).saturating_add(64) > self.max_body { + self.warn(TOO_LARGE); + return; + } + self.line("q"); + let _ = writeln!(self.body, "{} cm", ps::matrix(place)); + code.push_inline(&mut self.body); self.line("Q"); } @@ -1428,7 +1605,7 @@ impl<'a> Scene<'a> { /// them on the unit square: in the process colour space, transparent pixels masked out at /// Level 3 (a key colour no opaque pixel has), white at Level 2; partly transparent ones over /// white. `None` for an empty image. - fn encode_image(&mut self, rgba: &[u8], w: u32, h: u32) -> Option { + fn encode_image(&mut self, rgba: &[u8], w: u32, h: u32) -> Option { let space = if self.cmyk { Space::Cmyk } else { Space::Rgb }; let mut cache: HashMap<[u8; 3], [u8; 4]> = HashMap::new(); let cms = self.cms.clone(); @@ -1447,7 +1624,7 @@ impl<'a> Scene<'a> { /// Straight CMYK pixels with opacity (five bytes a pixel, `w` × `h`, rows from the top), drawn /// as [`Self::encode_image`] draws its pixels and keeping their ink amounts: partly /// transparent pixels lay down that share of each ink. - fn encode_inks(&mut self, cmyka: &[u8], w: u32, h: u32) -> Option { + fn encode_inks(&mut self, cmyka: &[u8], w: u32, h: u32) -> Option { self.encode_samples(cmyka.as_chunks::<5>().0, w, h, Space::Cmyk, |p: &[u8; 5], al| { [0, 1, 2, 3].map(|i| ((u32::from(p[i]) * al + 127) / 255) as u8) }) @@ -1463,7 +1640,7 @@ impl<'a> Scene<'a> { h: u32, space: Space, mut sample: impl FnMut(&[u8; N], u32) -> [u8; 4], - ) -> Option { + ) -> Option { if w == 0 || h == 0 { return None; } @@ -1503,27 +1680,29 @@ impl<'a> Scene<'a> { ("/RunLengthDecode", rl) } }; - let mut out = String::with_capacity(encoded.len() * 5 / 4 + 400); - let _ = writeln!(out, "{} setcolorspace", space.name()); + let prelude = format!("{} setcolorspace\n", space.name()); let decode = "0 1 ".repeat(n); - let _ = write!( - out, - "{{ /VCsrc currentfile /ASCII85Decode filter def\n<< /ImageType {} /Width {w} /Height {h} /BitsPerComponent 8 /Decode [{}] /ImageMatrix [{w} 0 0 {h} 0 0]", + let mut dict = format!( + "<< /ImageType {} /Width {w} /Height {h} /BitsPerComponent 8 /Decode [{}] /ImageMatrix [{w} 0 0 {h} 0 0]", if keyed { 4 } else { 1 }, decode.trim_end() ); if keyed { let mask: Vec = key.iter().take(n).map(|v| format!("{v} {v}")).collect(); - let _ = write!(out, " /MaskColor [{}]", mask.join(" ")); + let _ = write!(dict, " /MaskColor [{}]", mask.join(" ")); } - // The procedure is read whole before it runs: the image data follows it, and flushing the - // ASCII85 filter afterwards reads past its end marker. - let _ = writeln!(out, "\n/DataSource VCsrc {filter} filter >> image\nVCsrc flushfile }} exec"); - out.push_str(&ps::ascii85(&encoded)); - Some(out) + Some(image_code(prelude, dict, filter, "image", encoded)) } } +/// An image of `prelude`, `dict`, `filter` and `op` (see [`ImageCode`]) with compressed samples +/// `data`, not yet placed. +fn image_code(prelude: String, dict: String, filter: &'static str, op: &'static str, data: Vec) -> ImageCode { + let mut code = ImageCode { prelude, dict, filter, op, ascii: ps::ascii85(&data), data, uses: 0, inline_len: 0, ref_len: 0 }; + code.inline_len = code.prelude.len() + INLINE_SOURCE.len() + code.dict.len() + code.inline_read().len() + code.ascii.len(); + code +} + /// `a` to `b` at `t`. fn mix(a: &[f32], b: &[f32], t: f32) -> Vec { a.iter().zip(b).map(|(x, y)| x + (y - x) * t).collect() diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs index 13bdbb80e2..0d5649ead5 100644 --- a/crates/eps/src/tests.rs +++ b/crates/eps/src/tests.rs @@ -82,6 +82,17 @@ fn checked_page(ps: &str) -> String { } } '{' | '[' => stack.push(c), + // An ASCII85 string: its digits are data. + '<' if chars.peek() == Some(&'~') => { + let mut last = ' '; + loop { + let c = chars.next().expect("ASCII85 string closes"); + if last == '~' && c == '>' { + break; + } + last = c; + } + } '<' if chars.peek() == Some(&'<') => { chars.next(); stack.push('<'); @@ -679,15 +690,20 @@ fn png_doc() -> Document { for (x, _, p) in img.enumerate_pixels_mut() { *p = if x < 2 { image::Rgba([0, 200, 0, 255]) } else { image::Rgba([0, 0, 0, 0]) }; } + image_doc(&img, 10.0) +} + +/// A 200 × 200 pt document holding `img` as a PNG, its pixels `scale` points wide, at (10, 10). +fn image_doc(img: &image::RgbaImage, scale: f64) -> Document { let mut png = vec![]; img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); let mut d = Document::new(200.0, 200.0); d.images.insert("pic".into(), ImageBlob::new("image/png", png)); let im = ImageObject { key: "pic".into(), - width: 4, - height: 2, - xf: Affine::translate((10.0, 10.0)) * Affine::scale(10.0), + width: img.width(), + height: img.height(), + xf: Affine::translate((10.0, 10.0)) * Affine::scale(scale), link: None, placement: Default::default(), pixels: None, @@ -988,6 +1004,219 @@ fn uncolorized_image_stays_on_original_eps_path() { assert_eq!(page_of(&color, &opts(&color)), original); } +/// A copy of the first layer's object `i`, moved by `xf`, added on top. +fn place_again(d: &mut Document, i: usize, xf: Affine) { + let mut n = (*d.layers[0].children().unwrap()[i]).clone(); + n.id = d.alloc_id(); + if let NodeKind::Image(im) = &mut n.kind { + im.xf = xf * im.xf; + } + d.insert(d.default_layer(), usize::MAX, n).unwrap(); +} + +/// Pixels of noise, opaque. +fn noise(w: u32, h: u32) -> image::RgbaImage { + let mut seed = 1u32; + image::RgbaImage::from_fn(w, h, |_, _| { + let mut px = [255u8; 4]; + for v in &mut px[..3] { + seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345); + *v = (seed >> 16) as u8; + } + image::Rgba(px) + }) +} + +/// The pixels of each image an EPS file's page draws, read back from the page. +fn imported_images(bytes: &[u8]) -> Vec> { + fn walk(n: &Node, d: &Document, out: &mut Vec>) { + if let NodeKind::Image(im) = &n.kind { + out.push(image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8().into_raw()); + } + for c in n.children().into_iter().flatten() { + walk(c, d, out); + } + } + let r = import_with(bytes, false).unwrap(); + assert!(!r.preview, "{:?}", r.warnings); + let mut out = vec![]; + for l in &r.document.layers { + walk(l, &r.document, &mut out); + } + out +} + +/// The samples of an image placed more than once, from the setup that defines them: inflated at +/// Level 3, each string run-length decoded in turn at Level 2. +fn reused_samples(ps: &str, level: Level) -> Vec { + let setup = &ps[ps.find("%%BeginSetup").unwrap()..ps.find("%%EndSetup").unwrap()]; + match level { + Level::Three => ps::inflate(&image_data(setup), 1 << 28).unwrap(), + Level::Two => { + let mut data = vec![]; + for s in setup.split("<~").skip(1) { + let chunk = ps::ascii85_decode(&s[..s.find("~>").unwrap() + 2]).unwrap(); + assert!(chunk.len() <= 65_535, "a string holds at most 65,535 bytes: {}", chunk.len()); + data.extend(chunk); + } + unpack(&data) + } + } +} + +/// The samples of a single image written where it is drawn. +fn inline_samples(ps: &str, level: Level) -> Vec { + match level { + Level::Three => ps::inflate(&image_data(ps), 1 << 28).unwrap(), + Level::Two => unpack(&image_data(ps)), + } +} + +/// How many placements draw the image the setup defines as `VCim`. +fn reuses(ps: &str, i: usize, level: Level) -> usize { + match level { + Level::Three => ps.matches(&format!("VCim{i} resetfile\n")).count(), + Level::Two => ps.matches(&format!("{{VCi VCim{i} length lt")).count(), + } +} + +#[test] +fn an_image_placed_twice_writes_its_samples_once_at_both_levels() { + let single = png_doc(); + let mut d = single.clone(); + place_again(&mut d, 0, Affine::translate((60.0, 80.0)) * Affine::rotate(0.5)); + for level in Level::ALL { + let one = export(&single, &EpsOptions { level, ..opts(&single) }, None, None).unwrap(); + let one_ps = text(&one); + assert!(!one_ps.contains("VCim"), "an image placed once is written where it is drawn: {one_ps}"); + let out = export(&d, &EpsOptions { level, ..opts(&d) }, None, None).unwrap(); + let ps = text(&out); + checked_page(&ps); + assert_eq!(reuses(&ps, 0, level), 2, "{ps}"); + assert!(!ps.contains("VCim1"), "{ps}"); + let body = &ps[ps.find("%%EndSetup").unwrap()..]; + assert!(!body.contains("currentfile") && !body.contains("~>"), "no samples in the page: {ps}"); + match level { + Level::Three => { + assert_eq!(ps.matches("/ReusableStreamDecode filter def").count(), 1, "{ps}"); + assert!(ps.contains("/Intent 0 /AsyncRead false /CloseSource false"), "{ps}"); + assert!(body.contains("/DataSource VCim0 /FlateDecode filter >> image\n"), "{ps}"); + } + Level::Two => { + assert!(ps.contains("/VCim0 [\n<~") && !ps.contains("ReusableStreamDecode"), "{ps}"); + assert!(body.contains("/VCi 0 def\n") && body.contains("/RunLengthDecode filter >> image\n"), "{ps}"); + } + } + assert_eq!(reused_samples(&ps, level), inline_samples(&one_ps, level)); + assert_eq!(out.warnings, one.warnings); + // Read back, each placement draws the image the single placement draws. + let once = imported_images(&one.bytes); + assert_eq!(once.len(), 1); + assert_eq!(imported_images(&out.bytes), vec![once[0].clone(); 2], "{level:?}"); + } +} + +/// An image in an envelope is drawn as clipped pieces, all from one copy of its samples, which the +/// image placed beside the envelope also draws. +#[test] +fn an_envelopes_image_pieces_draw_one_copy_of_its_samples() { + let mut d = png_doc(); + let mut content = (*d.layers[0].children().unwrap()[0]).clone(); + content.id = d.alloc_id(); + let kind = vectorcraft_doc::EnvelopeKind::Warp { style: "arc".into(), bend: 50.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }; + let envelope = Node::new( + d.alloc_id(), + NodeKind::Envelope { + content: vec![Arc::new(content)], + kind: Box::new(kind), + fidelity: 50.0, + editing: false, + options: Default::default(), + frame: Box::new(Affine::IDENTITY), + }, + ); + d.insert(d.default_layer(), usize::MAX, envelope).unwrap(); + for level in Level::ALL { + let out = export(&d, &EpsOptions { level, ..opts(&d) }, None, None).unwrap(); + let ps = text(&out); + checked_page(&ps); + // The plain image and 200 pieces: 10 × 10 cells of two triangles. + assert_eq!(reuses(&ps, 0, level), 201, "{ps}"); + assert!(!ps.contains("VCim1"), "{ps}"); + assert_eq!(ps.matches(if level == Level::Three { "/ReusableStreamDecode" } else { "<~" }).count(), 1, "{ps}"); + assert!(!out.warnings.iter().any(|w| w.contains("too large")), "{:?}", out.warnings); + } +} + +#[test] +fn each_ink_of_a_colorized_image_placed_twice_is_written_once() { + let first = Paint::Solid { color: Color::rgb8(255, 0, 0), swatch: Some("Ink".into()), tint: 1.0 }; + let mut d = colorized_doc(vec![0, 255, 0], Some(first)); + let mut n = (*d.layers[0].children().unwrap()[0]).clone(); + n.id = d.alloc_id(); + n.extras_mut().colorize = Some(Box::new(Paint::Solid { color: Color::rgb8(255, 128, 128), swatch: Some("Ink".into()), tint: 0.5 })); + d.insert(d.default_layer(), usize::MAX, n).unwrap(); + place_again(&mut d, 0, Affine::translate((0.0, 50.0))); + place_again(&mut d, 1, Affine::translate((0.0, 100.0))); + for level in Level::ALL { + let ps = page_of(&d, &EpsOptions { level, ..opts(&d) }); + assert_eq!((reuses(&ps, 0, level), reuses(&ps, 1, level)), (2, 2), "{ps}"); + assert_eq!(ps.matches("VCsp0 setcolorspace 1 setcolor\n").count(), 2, "{ps}"); + assert_eq!(ps.matches("VCsp0 setcolorspace 0.5 setcolor\n").count(), 2, "{ps}"); + assert_eq!(ps.matches("imagemask").count(), 4, "{ps}"); + if level == Level::Three { + assert_eq!(ps.matches("/Intent 1 ").count(), 2, "image masks: {ps}"); + } + } +} + +/// Samples longer than PostScript's longest string: one stream at Level 3, several strings at +/// Level 2, each placement reading all of them. +#[test] +fn samples_longer_than_a_string_are_reused_at_both_levels() { + let single = image_doc(&noise(160, 160), 1.0); + let mut d = single.clone(); + place_again(&mut d, 0, Affine::translate((20.0, 0.0))); + for level in Level::ALL { + let one = export(&single, &EpsOptions { level, ..opts(&single) }, None, None).unwrap(); + let out = export(&d, &EpsOptions { level, ..opts(&d) }, None, None).unwrap(); + let ps = text(&out); + checked_page(&ps); + assert_eq!(reuses(&ps, 0, level), 2); + if level == Level::Two { + assert_eq!(ps.matches("<~").count(), 2, "160 × 160 × 3 run-length bytes take two strings"); + } + let samples = reused_samples(&ps, level); + assert_eq!(samples.len(), 160 * 160 * 3); + assert_eq!(samples, inline_samples(&text(&one), level)); + let once = imported_images(&one.bytes); + assert_eq!(imported_images(&out.bytes), vec![once[0].clone(); 2], "{level:?}"); + } +} + +/// The limit on the page body counts the samples of an image placed many times once. Art taken +/// back for passing the limit takes its image placements with it. +#[test] +fn the_page_limit_counts_a_repeated_images_samples_once() { + let single = image_doc(&noise(40, 40), 1.0); + let o = opts(&single); + let inline = crate::scene::Scene::new(&single, &o).run().body.len(); + let mut d = single.clone(); + for k in 1..20 { + place_again(&mut d, 0, Affine::translate((f64::from(k), 0.0))); + } + let page = crate::scene::Scene::new(&d, &o).with_max_body(inline * 3).run(); + assert!(page.warnings.is_empty(), "{:?}", page.warnings); + assert_eq!(reuses(&page.body, 0, Level::Three), 20); + assert!(page.setup.contains("/VCim0 VCsrc")); + // Past the limit, the placements that don't fit are left out with a warning. + let page = crate::scene::Scene::new(&d, &o).with_max_body(inline + 1000).run(); + assert!(page.warnings.iter().any(|w| w.contains("too large")), "{:?}", page.warnings); + let placed = reuses(&page.body, 0, Level::Three); + assert!((2..20).contains(&placed), "{placed}"); + assert!(page.body.len() + page.setup.len() <= inline + 1000 + 400, "{}", page.body.len()); +} + #[test] fn run_length_and_ascii85_round_trip() { let cycle: Vec = (0..=255u8).cycle().take(1000).collect(); diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index 59a8f30660..ac7dc63add 100644 --- a/crates/geom/src/path.rs +++ b/crates/geom/src/path.rs @@ -165,6 +165,26 @@ impl Anchor { pub fn reversed(&self) -> Self { Self { p: self.p, h_in: self.h_out, h_out: self.h_in, kind: self.kind } } + /// Make the anchor smooth between the points `prev` and `next` (its own point for a missing + /// one): handles in line with them, each a third of the way to that side's point. A smooth + /// anchor with both handles keeps them. False, with no change, when the two points give no + /// direction. [`SubPath::smooth_anchor`] calls it with the anchor's neighbors. + pub fn smooth_between(&mut self, prev: Option, next: Option) -> bool { + if self.kind == AnchorKind::Smooth && self.has_in() && self.has_out() { + return true; + } + let (pp, nn) = (prev.unwrap_or(self.p), next.unwrap_or(self.p)); + let dir = nn - pp; + let l = dir.hypot(); + if l <= 1e-9 { + return false; + } + let u = dir / l; + self.h_in = self.p - u * (self.p.distance(pp) / 3.0); + self.h_out = self.p + u * (self.p.distance(nn) / 3.0); + self.kind = AnchorKind::Smooth; + true + } /// Remove both handles (convert to a sharp corner). pub fn retract(&mut self) { self.h_in = self.p; @@ -398,21 +418,7 @@ impl SubPath { }; let at = |j: Option| j.and_then(|j| self.anchors.get(j)).map(|a| a.p); let (prev, next) = (at(prev), at(next)); - let Some(a) = self.anchors.get_mut(i) else { return false }; - if a.kind == AnchorKind::Smooth && a.has_in() && a.has_out() { - return true; - } - let (pp, nn) = (prev.unwrap_or(a.p), next.unwrap_or(a.p)); - let dir = nn - pp; - let l = dir.hypot(); - if l <= 1e-9 { - return false; - } - let u = dir / l; - a.h_in = a.p - u * (a.p.distance(pp) / 3.0); - a.h_out = a.p + u * (a.p.distance(nn) / 3.0); - a.kind = AnchorKind::Smooth; - true + self.anchors.get_mut(i).is_some_and(|a| a.smooth_between(prev, next)) } /// Cut at the anchors `at`: each becomes the end of one open piece and the start of the next, /// its handle off each piece retracted (the shape doesn't change). A closed subpath opens at @@ -688,7 +694,8 @@ fn box_gap(c: &CubicBez, p: Point) -> Option { const MEASURE_LIMIT: f64 = 1e9; /// The length of `seg` to `accuracy`; 0 for a segment whose control points are not finite or past -/// [`MEASURE_LIMIT`]. +/// [`MEASURE_LIMIT`], and 0 when the measurement is not finite (kurbo gives NaN for a quadratic +/// segment whose three points coincide). pub fn measured_arclen(seg: &PathSeg, accuracy: f64) -> f64 { let ok = |p: Point| p.x.is_finite() && p.y.is_finite() && p.x.abs() <= MEASURE_LIMIT && p.y.abs() <= MEASURE_LIMIT; let fits = match seg { @@ -696,7 +703,11 @@ pub fn measured_arclen(seg: &PathSeg, accuracy: f64) -> f64 { PathSeg::Quad(q) => ok(q.p0) && ok(q.p1) && ok(q.p2), PathSeg::Cubic(c) => ok(c.p0) && ok(c.p1) && ok(c.p2) && ok(c.p3), }; - if fits { kurbo::ParamCurveArclen::arclen(seg, accuracy) } else { 0.0 } + if !fits { + return 0.0; + } + let len = kurbo::ParamCurveArclen::arclen(seg, accuracy); + if len.is_finite() { len } else { 0.0 } } /// The largest x or y, in size, of a segment's control points for which [`segment_bounds`] @@ -1056,6 +1067,19 @@ mod tests { assert!((square().length() - 40.0).abs() < 1e-6); } + /// A quadratic segment whose three points coincide measures 0, not NaN; quadratic segments + /// with only two points together, and an ordinary one, keep kurbo's length. + #[test] + fn measured_arclen_of_a_quad_whose_points_coincide_is_zero() { + let quad = |a: (f64, f64), b: (f64, f64), c: (f64, f64)| PathSeg::Quad(kurbo::QuadBez::new(a, b, c)); + assert_eq!(measured_arclen(&quad((5.0, 5.0), (5.0, 5.0), (5.0, 5.0)), 1e-6), 0.0); + assert_eq!(measured_arclen(&quad((0.0, 0.0), (0.0, 0.0), (0.0, 0.0)), 1e-3), 0.0); + assert!((measured_arclen(&quad((0.0, 0.0), (0.0, 0.0), (10.0, 0.0)), 1e-6) - 10.0).abs() < 1e-6); + assert!((measured_arclen(&quad((0.0, 0.0), (10.0, 0.0), (0.0, 0.0)), 1e-6) - 10.0).abs() < 1e-6); + let ordinary = quad((0.0, 0.0), (10.0, 0.0), (10.0, 10.0)); + assert_eq!(measured_arclen(&ordinary, 1e-6), kurbo::ParamCurveArclen::arclen(&ordinary, 1e-6)); + } + #[test] fn serde_roundtrip() { let p = square(); diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index fbb5e4fc90..fb980843e8 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -74,6 +74,21 @@ pub enum HostError { /// A function the host gives a script, with its arguments converted. pub type HostFunction = Rc) -> Result>; +/// The place in the script's code that reads a [`HostItem::SiteGetter`] property: the source tag +/// of that code, as [`crate::Realm::error_tag`] gives one, and the line and column there, counted +/// from 1. A function an earlier script defined keeps its script's tag; code that `eval` or +/// `Function` compiled has [`crate::UNKNOWN_SOURCE`]. A read with none of the script's code +/// running has [`crate::UNKNOWN_SOURCE`] and line and column 0. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CallSite { + pub source: u32, + pub line: u32, + pub column: u32, +} + +/// A getter the host gives a script that is told where the code reading it is. +pub type SiteFunction = Rc Result>; + /// How one argument of a [`HostItem::Converted`] function is read. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Arg { @@ -96,6 +111,8 @@ pub(crate) enum ArgRead { Text, /// One by one as the list says; those past its end are not read. Each(Rc<[Arg]>), + /// None: the function is given the [`CallSite`] of the code that calls it, as three numbers. + Site, } /// A member of an object the host adds to the global environment. @@ -114,6 +131,9 @@ pub enum HostItem { /// A property whose value the function gives each time it is read, frozen as /// [`HostItem::Value`] gives its value. FrozenGetter(HostFunction), + /// A property whose value the function gives each time it is read, given the [`CallSite`] of + /// the code that reads it. + SiteGetter(SiteFunction), /// A property whose value `get` gives each time it is read, and that `set` is given each value /// assigned to it, as its one argument; an error from `set` is thrown to the script. Property { @@ -357,7 +377,10 @@ impl Interp { /// Calls host function `f`: reads its arguments as `how` says, runs it, and gives its result to /// the script. pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc, args: &[Value], how: &ArgRead) -> JsResult { - let data = self.read_args(name, args, how)?; + let data = match how { + ArgRead::Site => site_data(self.call_site()), + _ => self.read_args(name, args, how)?, + }; // Only the script's own code, in a run that can pause, can wait for a result. let can_wait = self.in_slice && self.reentry == 0; self.can_wait.set(can_wait); @@ -375,6 +398,18 @@ impl Interp { } } + /// Where the innermost frame of the script's code is: its source's tag and the line and column + /// of the instruction it is running. + fn call_site(&self) -> CallSite { + match self.script_frames().last() { + Some((code, pc, _)) => { + let (line, column) = code.line_column(pc.saturating_sub(1)); + CallSite { source: code.source.tag, line, column } + } + None => CallSite { source: crate::UNKNOWN_SOURCE, line: 0, column: 0 }, + } + } + /// Calls evaluator `f` ([`HostItem::Evaluator`]): reads its arguments, runs it, and runs the /// source it gives as global code, as an indirect `eval` does, giving that code's completion /// value. A result that is not a string is given to the script as it is. `end` is called once @@ -442,7 +477,7 @@ impl Interp { for (i, a) in args.iter().enumerate() { reading.path.push(Step::Index(u32::try_from(i).unwrap_or(u32::MAX))); let d = match how { - ArgRead::Data | ArgRead::Frozen => self.read_data(a, &mut reading), + ArgRead::Data | ArgRead::Frozen | ArgRead::Site => self.read_data(a, &mut reading), ArgRead::Text => self.read_text(a, &mut reading), ArgRead::Each(list) => match list.get(i) { Some(Arg::TextOrUndefined) if matches!(a, Value::Undefined) => Ok(Data::Undefined), @@ -531,6 +566,10 @@ impl Interp { HostItem::Value(d) => Prop::Data { value: self.write_data(d, 0, true)?, flags: ENUMERABLE }, HostItem::Getter(f) => Prop::Accessor { get: Some(self.host_function(f, &full, ArgRead::Data)), set: None, flags: ENUMERABLE }, HostItem::FrozenGetter(f) => Prop::Accessor { get: Some(self.host_function(f, &full, ArgRead::Frozen)), set: None, flags: ENUMERABLE }, + HostItem::SiteGetter(f) => { + let get: HostFunction = Rc::new(move |data| f(read_site(&data))); + Prop::Accessor { get: Some(self.host_function(get, &full, ArgRead::Site)), set: None, flags: ENUMERABLE } + } HostItem::Property { get, set } => Prop::Accessor { get: Some(self.host_function(get, &full, ArgRead::Data)), set: Some(self.host_function(set, &full, ArgRead::Data)), @@ -577,3 +616,18 @@ enum Slot { Index(usize), Name(String), } + +/// `site` as the three numbers [`ArgRead::Site`] gives its function. +fn site_data(site: CallSite) -> Vec { + vec![Data::Number(f64::from(site.source)), Data::Number(f64::from(site.line)), Data::Number(f64::from(site.column))] +} + +/// The [`CallSite`] that [`site_data`] gave as `data`. +fn read_site(data: &[Data]) -> CallSite { + let at = |i: usize, missing: u32| match data.get(i) { + // Each number is a `u32` that `site_data` gave, so the conversion is exact. + Some(Data::Number(n)) => *n as u32, + _ => missing, + }; + CallSite { source: at(0, crate::UNKNOWN_SOURCE), line: at(1, 0), column: at(2, 0) } +} diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index de252c6c64..700efddfb2 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -271,6 +271,41 @@ fn a_frozen_getter_gives_a_frozen_value_each_time() { assert_eq!(r.run(source).unwrap(), JsValue::String("true,true,true,1,false,false".into())); } +/// A site getter is told the source tag, line and column of the code that reads it: a function an +/// earlier script or an evaluator's source defined keeps that source's tag, and code that `eval` +/// compiled has none. +#[test] +fn a_site_getter_is_told_where_the_code_that_reads_it_is() { + let mut r = realm(10_000_000); + let seen: Rc>> = Rc::default(); + let log = seen.clone(); + let site: SiteFunction = Rc::new(move |s| { + log.borrow_mut().push(s); + Ok(Data::Number(f64::from(s.line))) + }); + let source: HostFunction = Rc::new(|_| Ok(Data::String("\n\nfunction inEval() { return host.site; }".into()))); + let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) }; + r.define_host_object("host", vec![("site".into(), HostItem::SiteGetter(site)), ("load".into(), load)]).unwrap(); + r.run("function early() {\n return host.site;\n}\nhost.load();").unwrap(); + let first = r.script_tag(); + assert_eq!(r.run("\n\n\n\nhost.site + early() + inEval() + eval('host.site')").unwrap(), JsValue::Number(5.0 + 2.0 + 3.0 + 1.0)); + let second = r.script_tag(); + let sites = seen.borrow().clone(); + assert_eq!( + sites, + vec![ + CallSite { source: second, line: 5, column: 1 }, + CallSite { source: first, line: 2, column: 11 }, + CallSite { source: first + 1, line: 3, column: 28 }, + CallSite { source: UNKNOWN_SOURCE, line: 1, column: 1 }, + ] + ); + seen.borrow_mut().clear(); + // A getter a built-in calls is at the place of the code that called the built-in. + assert_eq!(r.run("\nObject.getOwnPropertyDescriptor(host, 'site').get.call(host)").unwrap(), JsValue::Number(2.0)); + assert_eq!(seen.borrow().first().map(|s| s.source), Some(r.script_tag())); +} + #[test] fn a_text_function_takes_each_argument_as_string_gives_it() { let mut r = realm(1_000_000); diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index cad290f1af..2e61f2e1bb 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -80,7 +80,7 @@ pub use ast::{ }; pub use builtins::extensions::Localization; pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; -pub use host::{Arg, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem}; +pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction}; pub use lexer::{Goal, Lexer}; pub use number::to_string as number_to_string; pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind, UNKNOWN_SOURCE}; diff --git a/crates/js/src/xml.rs b/crates/js/src/xml.rs index 8d83162a50..f49c94eb46 100644 --- a/crates/js/src/xml.rs +++ b/crates/js/src/xml.rs @@ -7,6 +7,7 @@ //! each new node, name, reference or output unit is charged to the heap before it is made. use std::collections::{HashMap, HashSet}; +use std::hash::Hash; use std::rc::Rc; use crate::LimitKind; @@ -18,7 +19,7 @@ use crate::heap::{ XmlListData, XmlName, XmlNode, XmlNs, key, string_bytes, }; use crate::interp::{Abrupt, ErrorType, HeldBytes, Interp, JsResult}; -use crate::string_builtins::{UNITS_PER_FUEL, flat_charged}; +use crate::string_builtins::{UNITS_PER_FUEL, flat_charged, push_held, reserve_units}; use crate::value::{Str, Value, index_key}; fn parser_units(s: &str) -> Vec { @@ -295,26 +296,40 @@ fn name_bytes(n: &XmlName) -> usize { string_bytes(n.local.len()) + n.uri.as_ref().map_or(0, |u| string_bytes(u.len())) + n.prefix.as_ref().map_or(0, |p| string_bytes(p.len())) } -/// The namespace `stack` declares for `uri`, nearest first, skipping prefixes redeclared nearer. -/// `prefer` picks that prefix when several match; `need_prefix` rejects the default namespace. -fn ns_lookup(stack: &[XmlNs], uri: &Key, prefer: Option<&Key>, need_prefix: bool) -> Option { - let mut seen: HashSet<&[u16]> = HashSet::new(); - let mut best = None; - for ns in stack.iter().rev() { - let Some(p) = &ns.prefix else { continue }; - if !seen.insert(p) { - continue; - } - if ns.uri == *uri && !(need_prefix && p.is_empty()) { - if prefer == Some(p) { - return Some(ns.clone()); - } - if best.is_none() { - best = Some(ns.clone()); - } - } +/// Inserts `item` into `set`, first holding an upper estimate of the bytes of the set's new table +/// when it must grow. Returns whether `item` was new. +fn insert_held(interp: &mut Interp, held: &mut HeldBytes, set: &mut HashSet, item: T) -> JsResult { + if set.len() == set.capacity() && !set.contains(&item) { + let more = set.capacity().max(4); + held.add(interp, more.saturating_mul(size_of::() + 1).saturating_mul(16) / 7)?; + set.reserve(more); } - best + Ok(set.insert(item)) +} + +/// Makes room in `list` for `more` items, first holding the bytes of its new capacity when it must +/// grow. The capacity at least doubles, as a push's would. +fn reserve_held(interp: &mut Interp, held: &mut HeldBytes, list: &mut Vec, more: usize) -> JsResult<()> { + if list.capacity() - list.len() < more { + let cap = list.len().saturating_add(more).max(list.capacity().saturating_mul(2)); + held.add(interp, (cap - list.capacity()).saturating_mul(size_of::()))?; + list.reserve_exact(cap - list.len()); + } + Ok(()) +} + +/// The number `n` of a prefix written `ns` in decimal without leading zeros, as +/// [`Interp::fresh_prefix`] makes them. +fn prefix_number(prefix: &[u16]) -> Option { + let digits = prefix.strip_prefix(&[u16::from(b'n'), u16::from(b's')])?; + let (&first, _) = digits.split_first()?; + if digits.len() > 9 || (first == u16::from(b'0') && digits.len() > 1) { + return None; + } + digits.iter().try_fold(0usize, |n, &c| { + let d = c.checked_sub(u16::from(b'0')).filter(|d| *d < 10)?; + Some(n * 10 + usize::from(d)) + }) } fn prefix_in_scope<'a>(stack: &'a [XmlNs], prefix: &[u16]) -> Option<&'a XmlNs> { @@ -345,18 +360,6 @@ fn units_are(units: &[u16], text: &str) -> bool { units.iter().copied().eq(text.encode_utf16()) } -/// A prefix no entry of `stack` uses. -fn fresh_prefix(stack: &[XmlNs]) -> Key { - let mut n = 0u32; - loop { - let candidate = key(&format!("ns{n}")); - if prefix_in_scope(stack, &candidate).is_none() { - return candidate; - } - n += 1; - } -} - /// One open element while serializing. struct OutFrame { node: ObjId, @@ -579,13 +582,16 @@ impl Interp { // ---- names ---- - fn name_from_string(&mut self, s: &[u16]) -> JsResult { + /// The name `s` gives: an attribute name after `@`, which is copied after its units are + /// reserved, and otherwise an element name that shares `s`. + fn name_from_string(&mut self, s: &Key) -> JsResult { if let Some((&0x40, rest)) = s.split_first() { let uri = if rest == STAR { None } else { Some(Rc::from(Vec::new())) }; + reserve_units(self, rest.len())?; return Ok(NameRef { uri, local: Rc::from(rest), attribute: true }); } - let uri = if s == STAR { None } else { Some(self.xml_default_uri()?) }; - Ok(NameRef { uri, local: Rc::from(s), attribute: false }) + let uri = if **s == *STAR { None } else { Some(self.xml_default_uri()?) }; + Ok(NameRef { uri, local: s.clone(), attribute: false }) } /// ToXMLName, with a canonical array index read as a position (ECMA-357 section 10.6). @@ -593,7 +599,7 @@ impl Interp { match k { Value::Number(n) if *n >= 0.0 && n.fract() == 0.0 && *n < 4_294_967_295.0 => Ok(Access::Index(*n as u32)), Value::String(s) => { - let flat = s.flat(); + let flat = flat_charged(self, s)?; if let Some(i) = canonical_index(&flat) { return Ok(Access::Index(i)); } @@ -603,7 +609,8 @@ impl Interp { if let Some(Class::QName { name, attribute, .. }) = self.heap.object(*o).map(|ob| &ob.class) { return Ok(Access::Name(NameRef { uri: name.uri.clone(), local: name.local.clone(), attribute: *attribute })); } - let s = self.to_str(k)?.flat(); + let s = self.to_str(k)?; + let s = flat_charged(self, &s)?; if let Some(i) = canonical_index(&s) { return Ok(Access::Index(i)); } @@ -787,31 +794,33 @@ impl Interp { if n.attribute { let count = self.xml_node(x)?.attrs.len(); self.xml_take_fuel(count)?; - let attrs = std::mem::take(&mut self.xml_node_mut(x)?.attrs); - let mut kept = Vec::with_capacity(attrs.len()); - for a in attrs { + let mut kept = 0; + for k in 0..count { + let Some(a) = self.xml_node(x)?.attrs.get(k).copied() else { break }; let hit = self.xml_node(a)?.name.as_ref().is_some_and(|q| n.matches(q)); if hit { self.xml_node_mut(a)?.parent = None; } else { - kept.push(a); + self.xml_node_mut(x)?.attrs.swap(kept, k); + kept += 1; } } - self.xml_node_mut(x)?.attrs = kept; + self.xml_node_mut(x)?.attrs.truncate(kept); return Ok(()); } let count = self.children_len(x)?; self.xml_take_fuel(count)?; - let children = std::mem::take(&mut self.xml_node_mut(x)?.children); - let mut kept = Vec::with_capacity(children.len()); - for c in children { + let mut kept = 0; + for k in 0..count { + let Some(c) = self.child_at(x, k)? else { break }; if n.matches_child(self.xml_node(c)?) { self.xml_node_mut(c)?.parent = None; } else { - kept.push(c); + self.xml_node_mut(x)?.children.swap(kept, k); + kept += 1; } } - self.xml_node_mut(x)?.children = kept; + self.xml_node_mut(x)?.children.truncate(kept); Ok(()) } @@ -939,7 +948,7 @@ impl Interp { self.use_fuel()?; cur = self.xml_node(a)?.parent; } - let height = self.node_height(v)?; + let height = self.rooted(&[Value::Object(x), Value::Object(v)], |i| i.node_height(v))?; if depth.saturating_add(height) > self.options.max_depth { return Err(Abrupt::Limit(LimitKind::Heap)); } @@ -971,7 +980,9 @@ impl Interp { /// The levels of the tree at `root`, counting it. fn node_height(&mut self, root: ObjId) -> JsResult { - let mut stack = vec![(root, 0usize)]; + let mut held = HeldBytes::new(self); + let mut stack = Vec::new(); + push_held(self, &mut held, &mut stack, (root, 0usize))?; let mut height = 1; while let Some(&(node, next)) = stack.last() { self.use_fuel()?; @@ -980,7 +991,7 @@ impl Interp { if let Some(top) = stack.last_mut() { top.1 += 1; } - stack.push((c, 0)); + push_held(self, &mut held, &mut stack, (c, 0))?; height = height.max(stack.len()); } None => { @@ -1049,19 +1060,22 @@ impl Interp { } /// Takes the fuel and heap to put every item of `l` under `x` and returns the nodes to place, - /// from [`Self::child_for_item`]. The tree does not change here, so a limit leaves it as it - /// was. - fn reserve_list_insert(&mut self, x: ObjId, l: ObjId) -> JsResult> { + /// from [`Self::child_for_item`], with the hold on the list of them, which the caller keeps + /// until they are placed. The tree does not change here, so a limit leaves it as it was. + fn reserve_list_insert(&mut self, x: ObjId, l: ObjId) -> JsResult<(Vec, HeldBytes)> { + let count = self.list_len(l)?; + let roots = [Value::Object(x), Value::Object(l)]; + let mut held = HeldBytes::new(self); + self.rooted(&roots, |i| held.add(i, size_of::().saturating_mul(count)))?; let mut items = self.xml_list(l)?.items.clone(); let bytes = XML_REF_BYTES.saturating_mul(items.len()); - let roots = [Value::Object(x), Value::Object(l)]; self.rooted(&roots, |i| i.xml_charge(bytes))?; let len = self.children_len(x)?; for (j, item) in items.iter_mut().enumerate() { *item = self.child_for_item(*item, &roots)?; self.place_fuel(len + j, *item)?; } - Ok(items) + Ok((items, held)) } /// Puts `items` at `at` in order, after [`Self::reserve_list_insert`]. @@ -1100,7 +1114,7 @@ impl Interp { self.insert_node(x, at, *v)?; } Content::List(l) => { - let items = self.reserve_list_insert(x, *l)?; + let (items, _held) = self.reserve_list_insert(x, *l)?; self.place_children(x, at, &items)?; } } @@ -1152,7 +1166,7 @@ impl Interp { } Content::List(l) => { self.check_attach(x, c)?; - let items = self.reserve_list_insert(x, *l)?; + let (items, _held) = self.reserve_list_insert(x, *l)?; let len = self.children_len(x)?; self.xml_text_fuel(len)?; if at < len { @@ -1229,7 +1243,8 @@ impl Interp { s.push_units(self, &[SPACE])?; } let Some(item) = self.list_at(*l, i)? else { break }; - let text = self.node_to_str(item)?.flat(); + let text = self.node_to_str(item)?; + let text = flat_charged(self, &text)?; s.push_units(self, &text)?; } let Value::String(s) = s.finish(self) else { return Err(Abrupt::Internal("not a string".into())) }; @@ -1240,9 +1255,9 @@ impl Interp { let mut found = None; let count = self.xml_node(x)?.attrs.len(); self.xml_take_fuel(count)?; - let attrs = std::mem::take(&mut self.xml_node_mut(x)?.attrs); - let mut kept = Vec::with_capacity(attrs.len()); - for a in attrs { + let mut kept = 0; + for k in 0..count { + let Some(a) = self.xml_node(x)?.attrs.get(k).copied() else { break }; let hit = self.xml_node(a)?.name.as_ref().is_some_and(|q| n.matches(q)); if hit && found.is_some() { self.xml_node_mut(a)?.parent = None; @@ -1250,10 +1265,11 @@ impl Interp { if hit { found = Some(a); } - kept.push(a); + self.xml_node_mut(x)?.attrs.swap(kept, k); + kept += 1; } } - self.xml_node_mut(x)?.attrs = kept; + self.xml_node_mut(x)?.attrs.truncate(kept); if let Some(a) = found { self.xml_node_mut(a)?.value = value; return Ok(()); @@ -1280,11 +1296,13 @@ impl Interp { } let len = self.children_len(x)?; self.xml_take_fuel(len)?; + self.xml_keep(x); + let mut held = HeldBytes::new(self); let mut matches = Vec::new(); for k in 0..len { let Some(child) = self.child_at(x, k)? else { break }; if n.matches_child(self.xml_node(child)?) { - matches.push(child); + push_held(self, &mut held, &mut matches, child)?; } } match c { @@ -1378,6 +1396,8 @@ impl Interp { /// The steps of [`Self::resolve_value`], setting `created` to the first element they add. fn resolve_value_adding(&mut self, x: ObjId, created: &mut Option) -> JsResult> { + self.xml_keep(x); + let mut held = HeldBytes::new(self); let mut chain = Vec::new(); let mut cur = x; let base = loop { @@ -1391,7 +1411,7 @@ impl Interp { if *name.local == *STAR { return Ok(None); } - chain.push(l); + push_held(self, &mut held, &mut chain, l)?; cur = target; }; let mut base = base; @@ -1615,6 +1635,9 @@ impl Interp { Some(parent) => self.index_in_parent(parent, item)?.map(|q| (parent, q)), None => None, }; + let count = self.list_len(c)?; + let mut held = HeldBytes::new(self); + self.rooted(&[Value::Object(x), Value::Object(c)], |i| held.add(i, size_of::().saturating_mul(count)))?; let mut items = self.xml_list(c)?.items.clone(); if place.is_some() { let roots = [Value::Object(x), Value::Object(c)]; @@ -1682,6 +1705,8 @@ impl Interp { // ---- copies ---- fn copy_shallow(&mut self, src: ObjId, parent: Option) -> JsResult { + let declared = self.xml_node(src)?.ns.len(); + self.xml_charge(XML_NS_BYTES.saturating_mul(declared))?; let node = self.xml_node(src)?; let copy = XmlNode { kind: node.kind, @@ -1692,11 +1717,11 @@ impl Interp { children: Vec::new(), ns: node.ns.clone(), }; - let attrs = node.attrs.clone(); - self.xml_charge(XML_NS_BYTES.saturating_mul(copy.ns.len()))?; let c = self.new_xml_node(copy)?; self.xml_keep(c); - for a in attrs { + let mut k = 0; + while let Some(a) = self.xml_node(src)?.attrs.get(k).copied() { + k += 1; self.use_fuel()?; let n = self.xml_node(a)?; let attr = XmlNode { @@ -1721,7 +1746,9 @@ impl Interp { let top = i.copy_shallow(root, None)?; i.xml_keep(top); let mark = i.temp_roots.len(); - let mut stack = vec![(root, top, 0usize)]; + let mut held = HeldBytes::new(i); + let mut stack = Vec::new(); + push_held(i, &mut held, &mut stack, (root, top, 0usize))?; while let Some(&(src, dst, next)) = stack.last() { i.use_fuel()?; i.temp_roots.truncate(mark); @@ -1733,7 +1760,7 @@ impl Interp { let c = i.copy_shallow(child, Some(dst))?; i.xml_charge_link(c)?; i.xml_node_mut(dst)?.children.push(c); - stack.push((child, c, 0)); + push_held(i, &mut held, &mut stack, (child, c, 0))?; } None => { stack.pop(); @@ -1778,9 +1805,18 @@ impl Interp { // ---- comparison ---- + /// The namespace, local name and value of the attribute `id`, flattening a value that is a + /// rope with [`flat_charged`]. + fn attr_key(&mut self, id: ObjId) -> JsResult<(Option, Key, Key)> { + let n = self.xml_node(id)?; + let name = n.name.as_ref().ok_or_else(|| Abrupt::Internal("attribute without a name".into()))?; + let (uri, local, value) = (name.uri.clone(), name.local.clone(), n.value.clone()); + Ok((uri, local, flat_charged(self, &value)?)) + } + fn same_shallow(&mut self, a: ObjId, b: ObjId) -> JsResult { let (x, y) = (self.xml_node(a)?, self.xml_node(b)?); - if x.kind != y.kind || x.attrs.len() != y.attrs.len() || x.children.len() != y.children.len() || x.value.flat() != y.value.flat() { + if x.kind != y.kind || x.attrs.len() != y.attrs.len() || x.children.len() != y.children.len() || x.value.len() != y.value.len() { return Ok(false); } match (&x.name, &y.name) { @@ -1788,26 +1824,25 @@ impl Interp { (Some(p), Some(q)) if p.local == q.local && p.uri == q.uri => {} _ => return Ok(false), } - if x.attrs.is_empty() { + let (xv, yv) = (x.value.clone(), y.value.clone()); + if flat_charged(self, &xv)? != flat_charged(self, &yv)? { + return Ok(false); + } + let count = self.xml_node(a)?.attrs.len(); + if count == 0 { return Ok(true); } - let count = x.attrs.len(); self.xml_take_fuel(count)?; let mut held = HeldBytes::new(self); held.add(self, ATTR_COUNT_BYTES.saturating_mul(count))?; - let (x, y) = (self.xml_node(a)?, self.xml_node(b)?); - let (xa, ya) = (x.attrs.clone(), y.attrs.clone()); let mut counts: HashMap<(Option, Key, Key), usize> = HashMap::new(); - let attr_key = |i: &Self, id: ObjId| -> JsResult<(Option, Key, Key)> { - let n = i.xml_node(id)?; - let name = n.name.as_ref().ok_or_else(|| Abrupt::Internal("attribute without a name".into()))?; - Ok((name.uri.clone(), name.local.clone(), n.value.flat())) - }; - for a in xa { - *counts.entry(attr_key(self, a)?).or_default() += 1; + for k in 0..count { + let Some(id) = self.xml_node(a)?.attrs.get(k).copied() else { break }; + *counts.entry(self.attr_key(id)?).or_default() += 1; } - for b in ya { - match counts.get_mut(&attr_key(self, b)?) { + for k in 0..count { + let Some(id) = self.xml_node(b)?.attrs.get(k).copied() else { break }; + match counts.get_mut(&self.attr_key(id)?) { Some(n) if *n > 0 => *n -= 1, _ => return Ok(false), } @@ -1884,7 +1919,8 @@ impl Interp { let (xk, yk) = (self.xml_kind(x)?, self.xml_kind(y)?); let textual = |k| matches!(k, XmlKind::Text | XmlKind::Attribute); if (textual(xk) && self.node_simple(y)?) || (textual(yk) && self.node_simple(x)?) { - return Ok(Some(self.node_to_str(x)?.flat() == self.node_to_str(y)?.flat())); + let (s, other) = (self.node_to_str(x)?, self.node_to_str(y)?); + return Ok(Some(flat_charged(self, &s)? == flat_charged(self, &other)?)); } return self.node_equals(x, y).map(Some); } @@ -1900,9 +1936,9 @@ impl Interp { if let Xv::Node(n) = self.classify(x) && self.node_simple(n)? { - let s = self.node_to_str(n)?.flat(); - let other = self.to_str(y)?.flat(); - return Ok(Some(s == other)); + let s = self.node_to_str(n)?; + let other = self.to_str(y)?; + return Ok(Some(flat_charged(self, &s)? == flat_charged(self, &other)?)); } } Ok(None) @@ -1951,7 +1987,9 @@ impl Interp { /// The nodes under `x` matching `n`, in document order ([[Descendants]], section 9.1.1.8). pub(crate) fn node_descendants(&mut self, x: ObjId, n: &NameRef, out: ObjId) -> JsResult<()> { - let mut stack = vec![(x, 0usize)]; + let mut held = HeldBytes::new(self); + let mut stack = Vec::new(); + push_held(self, &mut held, &mut stack, (x, 0usize))?; if n.attribute { self.collect_matching(x, n, out)?; } @@ -1969,14 +2007,16 @@ impl Interp { } else if n.matches_child(self.xml_node(child)?) { self.list_push(out, child)?; } - stack.push((child, 0)); + push_held(self, &mut held, &mut stack, (child, 0))?; } Ok(()) } /// Merges adjacent text and removes empty text under `root` (ECMA-357 section 13.4.4.26). pub(crate) fn node_normalize(&mut self, root: ObjId) -> JsResult<()> { - let mut stack = vec![(root, 0usize)]; + let mut held = HeldBytes::new(self); + let mut stack = Vec::new(); + push_held(self, &mut held, &mut stack, (root, 0usize))?; while let Some(&(x, mut i)) = stack.last() { self.use_fuel()?; let Some(child) = self.child_at(x, i)? else { @@ -2010,7 +2050,7 @@ impl Interp { frame.1 = i + 1; } if kind == XmlKind::Element { - stack.push((child, 0)); + push_held(self, &mut held, &mut stack, (child, 0))?; } } Ok(()) @@ -2032,7 +2072,8 @@ impl Interp { let Some(c) = self.child_at(x, i)? else { break }; let node = self.xml_node(c)?; if !matches!(node.kind, XmlKind::Comment | XmlKind::Pi) { - let text = node.value.flat(); + let text = node.value.clone(); + let text = flat_charged(self, &text)?; out.push_units(self, &text)?; } } @@ -2069,7 +2110,8 @@ impl Interp { self.use_fuel()?; let Some(item) = self.list_at(l, i)? else { break }; if !matches!(self.xml_kind(item)?, XmlKind::Comment | XmlKind::Pi) { - let text = self.node_to_str(item)?.flat(); + let text = self.node_to_str(item)?; + let text = flat_charged(self, &text)?; out.push_units(self, &text)?; } } @@ -2107,6 +2149,46 @@ impl Interp { out.push_units(self, text.get(from..).unwrap_or_default()) } + /// The namespace `stack` declares for `uri`, nearest first, skipping prefixes redeclared nearer. + /// `prefer` picks that prefix when several match; `need_prefix` rejects the default namespace. + /// The set of prefixes it has passed is held against the heap limit. + fn ns_lookup(&mut self, stack: &[XmlNs], uri: &Key, prefer: Option<&Key>, need_prefix: bool) -> JsResult> { + let mut held = HeldBytes::new(self); + let mut seen: HashSet<&[u16]> = HashSet::new(); + let mut best = None; + for ns in stack.iter().rev() { + let Some(p) = &ns.prefix else { continue }; + if !insert_held(self, &mut held, &mut seen, &p[..])? { + continue; + } + if ns.uri == *uri && !(need_prefix && p.is_empty()) { + if prefer == Some(p) { + return Ok(Some(ns.clone())); + } + if best.is_none() { + best = Some(ns.clone()); + } + } + } + Ok(best) + } + + /// The first of `ns0`, `ns1`, ... that no entry of `stack` uses. One of the first + /// `stack.len() + 1` is free, so one pass over `stack` marks the used ones. + fn fresh_prefix(&mut self, stack: &[XmlNs]) -> JsResult { + self.xml_take_fuel(stack.len() + 1)?; + let mut held = HeldBytes::new(self); + held.add(self, stack.len() + 1)?; + let mut used = vec![false; stack.len() + 1]; + for ns in stack { + if let Some(slot) = ns.prefix.as_deref().and_then(prefix_number).and_then(|n| used.get_mut(n)) { + *slot = true; + } + } + let n = used.iter().position(|u| !u).unwrap_or(stack.len()); + Ok(key(&format!("ns{n}"))) + } + /// Picks the prefix of a name in `scope`, adding a declaration to `scope` when none is there. fn out_prefix(&mut self, name: &XmlName, scope: &mut Vec, attribute: bool) -> JsResult { self.xml_take_fuel(scope.len() + 1)?; @@ -2122,13 +2204,13 @@ impl Interp { if *uri == *key(XML_URI) { return Ok(key("xml")); } - if let Some(ns) = ns_lookup(scope, &uri, name.prefix.as_ref(), attribute) { + if let Some(ns) = self.ns_lookup(scope, &uri, name.prefix.as_ref(), attribute)? { return Ok(ns.prefix.unwrap_or(empty)); } let prefix = match &name.prefix { Some(p) if !(attribute && p.is_empty()) && prefix_in_scope(scope, p).is_none() => p.clone(), _ if !attribute && prefix_in_scope(scope, &empty).is_none() => empty, - _ => fresh_prefix(scope), + _ => self.fresh_prefix(scope)?, }; self.xml_charge(XML_NS_BYTES)?; scope.push(XmlNs { prefix: Some(prefix.clone()), uri }); @@ -2143,8 +2225,7 @@ impl Interp { out.push_units(self, local) } - /// Writes `x`; an element with children is left open on `stack`. - #[allow(clippy::too_many_arguments)] + /// Writes `x`, and returns the frame of an element with children, which is left open. fn write_enter( &mut self, out: &mut Builder, @@ -2153,11 +2234,11 @@ impl Interp { settings: &Settings, pretty: bool, scope: &mut Vec, - stack: &mut Vec, - ) -> JsResult<()> { + ) -> JsResult> { self.use_fuel()?; let node = self.xml_node(x)?; - let (kind, value) = (node.kind, node.value.flat()); + let (kind, value) = (node.kind, node.value.clone()); + let value = flat_charged(self, &value)?; self.xml_text_fuel(value.len())?; if pretty { out.push_repeated(self, &[SPACE], indent)?; @@ -2165,13 +2246,18 @@ impl Interp { match kind { XmlKind::Text => { let trimmed: &[u16] = if pretty { trim_xml_space(&value) } else { &value }; - return self.write_escaped(out, trimmed, false); + self.write_escaped(out, trimmed, false)?; + return Ok(None); + } + XmlKind::Attribute => { + self.write_escaped(out, &value, true)?; + return Ok(None); } - XmlKind::Attribute => return self.write_escaped(out, &value, true), XmlKind::Comment => { out.push_str(self, ""); + out.push_str(self, "-->")?; + return Ok(None); } XmlKind::Pi => { let target = self.xml_node(x)?.name.as_ref().map(|n| n.local.clone()).unwrap_or_else(|| Rc::from(Vec::new())); @@ -2179,47 +2265,46 @@ impl Interp { out.push_units(self, &target)?; out.push_units(self, &[SPACE])?; out.push_units(self, &value)?; - return out.push_str(self, "?>"); + out.push_str(self, "?>")?; + return Ok(None); } XmlKind::Element => {} } let ns_mark = scope.len(); let node = self.xml_node(x)?; - let declared = node.ns.clone(); - let attrs = node.attrs.clone(); + let declared = node.ns.len(); let name = node.name.clone().ok_or_else(|| Abrupt::Internal("element without a name".into()))?; - self.xml_take_fuel(declared.len().saturating_mul(scope.len() + 1))?; - let mut unnamed = Vec::new(); - for ns in declared { - if ns.prefix.is_none() { - unnamed.push(ns); - } else if !scope.iter().any(|a| a.uri == ns.uri && a.prefix == ns.prefix) { - self.xml_charge(XML_NS_BYTES)?; - scope.push(ns); - } - } - for ns in unnamed { - if !scope.iter().any(|a| a.uri == ns.uri) { - let prefix = fresh_prefix(scope); - self.xml_charge(XML_NS_BYTES)?; - scope.push(XmlNs { prefix: Some(prefix), uri: ns.uri }); + self.xml_take_fuel(declared.saturating_mul(scope.len() + 1))?; + for unnamed in [false, true] { + let mut k = 0; + while let Some(ns) = self.xml_node(x)?.ns.get(k).cloned() { + k += 1; + if ns.prefix.is_none() != unnamed { + continue; + } + if !unnamed && !scope.iter().any(|a| a.uri == ns.uri && a.prefix == ns.prefix) { + self.xml_charge(XML_NS_BYTES)?; + scope.push(ns); + } else if unnamed && !scope.iter().any(|a| a.uri == ns.uri) { + let prefix = self.fresh_prefix(scope)?; + self.xml_charge(XML_NS_BYTES)?; + scope.push(XmlNs { prefix: Some(prefix), uri: ns.uri }); + } } } let prefix = self.out_prefix(&name, scope, false)?; - let mut attr_prefixes = Vec::new(); - for &a in &attrs { - self.use_fuel()?; - let an = self.xml_node(a)?.name.clone().ok_or_else(|| Abrupt::Internal("attribute without a name".into()))?; - attr_prefixes.push(self.out_prefix(&an, scope, true)?); - } out.push_units(self, &[LT])?; self.write_name(out, &prefix, &name.local)?; - for (&a, attr_prefix) in attrs.iter().zip(&attr_prefixes) { - let an = self.xml_node(a)?; - let local = an.name.as_ref().map(|q| q.local.clone()).unwrap_or_else(|| Rc::from(Vec::new())); - let value = an.value.flat(); + let mut k = 0; + while let Some(a) = self.xml_node(x)?.attrs.get(k).copied() { + k += 1; + self.use_fuel()?; + let an = self.xml_node(a)?.name.clone().ok_or_else(|| Abrupt::Internal("attribute without a name".into()))?; + let attr_prefix = self.out_prefix(&an, scope, true)?; + let value = self.xml_node(a)?.value.clone(); + let value = flat_charged(self, &value)?; out.push_units(self, &[SPACE])?; - self.write_name(out, attr_prefix, &local)?; + self.write_name(out, &attr_prefix, &an.local)?; out.push_units(self, &[EQ, DQUOTE])?; self.write_escaped(out, &value, true)?; out.push_units(self, &[DQUOTE])?; @@ -2239,7 +2324,8 @@ impl Interp { let count = self.children_len(x)?; if count == 0 { scope.truncate(ns_mark); - return out.push_str(self, "/>"); + out.push_str(self, "/>")?; + return Ok(None); } out.push_units(self, &[GT])?; let first_is_text = match self.child_at(x, 0)? { @@ -2248,14 +2334,17 @@ impl Interp { }; let pretty_children = pretty && (count > 1 || !first_is_text); let child_indent = if pretty_children { indent.saturating_add(u64::from(settings.indent)) } else { 0 }; - stack.push(OutFrame { node: x, next: 0, indent, child_indent, pretty_children, ns_mark, prefix, local: name.local }); - Ok(()) + Ok(Some(OutFrame { node: x, next: 0, indent, child_indent, pretty_children, ns_mark, prefix, local: name.local })) } + /// Writes the tree at `root`. Its open elements are held against the heap limit. fn write_node(&mut self, out: &mut Builder, root: ObjId, indent: u64, settings: &Settings, pretty: bool) -> JsResult<()> { let mut scope: Vec = Vec::new(); + let mut held = HeldBytes::new(self); let mut stack: Vec = Vec::new(); - self.write_enter(out, root, indent, settings, pretty, &mut scope, &mut stack)?; + if let Some(frame) = self.write_enter(out, root, indent, settings, pretty, &mut scope)? { + push_held(self, &mut held, &mut stack, frame)?; + } while let Some(frame) = stack.last_mut() { let (node, next, child_indent, pretty_children) = (frame.node, frame.next, frame.child_indent, frame.pretty_children); frame.next += 1; @@ -2264,7 +2353,9 @@ impl Interp { if pretty_children { out.push_units(self, &[LF])?; } - self.write_enter(out, child, child_indent, settings, pretty && pretty_children, &mut scope, &mut stack)?; + if let Some(frame) = self.write_enter(out, child, child_indent, settings, pretty && pretty_children, &mut scope)? { + push_held(self, &mut held, &mut stack, frame)?; + } } None => { let Some(frame) = stack.pop() else { break }; @@ -2311,8 +2402,11 @@ impl Interp { self.throw(ErrorType::Syntax, message) } - fn decode_into(&mut self, src: &[u16], from: usize, to: usize, out: &mut Vec, attribute: bool) -> JsResult<()> { + /// Decodes `src[from..to]` onto `out`, holding the room it takes in `out` with `held` first. The + /// decoded text is never longer than the source. + fn decode_into(&mut self, src: &[u16], from: usize, to: usize, out: &mut Vec, attribute: bool, held: &mut HeldBytes) -> JsResult<()> { self.xml_text_fuel(to.saturating_sub(from))?; + reserve_held(self, held, out, to.saturating_sub(from))?; let mut pos = from; while pos < to { let Some(&c) = src.get(pos) else { break }; @@ -2427,7 +2521,16 @@ impl Interp { Ok(()) } - fn flush_text(&mut self, text: &mut Vec, ignore_whitespace: bool, open: &[ObjId], roots: &mut Vec) -> JsResult<()> { + /// Makes a text node of `text`, unless it is empty or ignored white space. Taking the buffer + /// releases `text_held`, its hold. + fn flush_text( + &mut self, + text: &mut Vec, + text_held: &mut HeldBytes, + ignore_whitespace: bool, + open: &[ObjId], + roots: &mut Vec, + ) -> JsResult<()> { if text.is_empty() { return Ok(()); } @@ -2435,16 +2538,22 @@ impl Interp { text.clear(); return Ok(()); } - let t = self.new_text_node(Str::from_units(std::mem::take(text)), None)?; + let value = Str::from_units(std::mem::take(text)); + *text_held = HeldBytes::new(self); + let t = self.new_text_node(value, None)?; self.place_parsed(t, open, roots) } + /// Parses the open tag at `src[pos]` and returns the offset after it. An element left open is + /// pushed onto `open` and its name onto `names`, both held with `stack_held`. The attributes, + /// sets and copies it works with are held until it returns. fn parse_open_tag( &mut self, src: &[u16], pos: usize, open: &mut Vec, names: &mut Vec<(usize, usize)>, + stack_held: &mut HeldBytes, roots: &mut Vec, ) -> JsResult { if open.len() >= self.options.max_depth { @@ -2455,6 +2564,7 @@ impl Interp { let raw_name = src.get(name_start..name_end).unwrap_or_default(); let (elem_prefix, elem_local) = self.split_name(raw_name)?; let mut at = name_end; + let mut held = HeldBytes::new(self); let mut raw_attrs: Vec<(usize, usize, Vec)> = Vec::new(); let closes = loop { let before = at; @@ -2492,27 +2602,31 @@ impl Interp { return Err(self.syntax("'<' cannot appear in an attribute value")); } let mut value = Vec::new(); - self.decode_into(src, value_start, value_end, &mut value, true)?; - raw_attrs.push((at, end, value)); + self.decode_into(src, value_start, value_end, &mut value, true, &mut held)?; + push_held(self, &mut held, &mut raw_attrs, (at, end, value))?; at = value_end + 1; } } }; self.xml_charge(XML_NS_BYTES.saturating_mul(raw_attrs.len()))?; - let mut ns: Vec = Vec::new(); - let mut seen_decl: HashSet> = HashSet::new(); + let xmlns = key("xmlns"); + let declares = |raw: &[u16]| raw == &xmlns[..] || raw.strip_prefix(&xmlns[..]).is_some_and(|rest| rest.first() == Some(&COLON)); + let decls = raw_attrs.iter().filter(|(start, end, _)| declares(src.get(*start..*end).unwrap_or_default())).count(); + let mut ns: Vec = Vec::with_capacity(decls); + let mut seen_decl: HashSet<&[u16]> = HashSet::new(); for (start, end, value) in &raw_attrs { let raw = src.get(*start..*end).unwrap_or_default(); - if raw == key("xmlns").as_ref() { + if raw == &xmlns[..] { if !ns_binding_allowed(&[], value) { return Err(self.syntax(RESERVED_NS_BINDING)); } - if !seen_decl.insert(Vec::new()) { + if !insert_held(self, &mut held, &mut seen_decl, &[] as &[u16])? { return Err(self.syntax("a namespace is declared twice")); } + self.xml_charge(string_bytes(0).saturating_add(string_bytes(value.len())))?; ns.push(XmlNs { prefix: Some(Rc::from(Vec::new())), uri: Rc::from(value.as_slice()) }); } else if let (Some(p), local) = self.split_name(raw)? - && p == key("xmlns").as_ref() + && p == &xmlns[..] { if value.is_empty() { return Err(self.syntax("a namespace prefix cannot be declared with an empty URI")); @@ -2520,9 +2634,10 @@ impl Interp { if !ns_binding_allowed(local, value) { return Err(self.syntax(RESERVED_NS_BINDING)); } - if !seen_decl.insert(local.to_vec()) { + if !insert_held(self, &mut held, &mut seen_decl, local)? { return Err(self.syntax("a namespace is declared twice")); } + self.xml_charge(string_bytes(local.len()).saturating_add(string_bytes(value.len())))?; ns.push(XmlNs { prefix: Some(Rc::from(local)), uri: Rc::from(value.as_slice()) }); } } @@ -2547,7 +2662,8 @@ impl Interp { ns, })?; self.place_parsed(element, open, roots)?; - let mut unique: HashSet<(Key, Vec)> = HashSet::new(); + let mut unique: HashSet<(Key, &[u16])> = HashSet::new(); + let mut own: Option> = None; for (start, end, value) in raw_attrs { self.use_fuel()?; let raw = src.get(start..end).unwrap_or_default(); @@ -2557,15 +2673,19 @@ impl Interp { } let (auri, stored_prefix): (Key, Key) = match prefix { Some(p) => { - let own = self.xml_node(element)?.ns.clone(); - match self.resolve_prefix(p, &own, open)? { + if own.is_none() { + let count = self.xml_node(element)?.ns.len(); + held.add(self, size_of::().saturating_mul(count))?; + own = Some(self.xml_node(element)?.ns.clone()); + } + match self.resolve_prefix(p, own.as_deref().unwrap_or_default(), open)? { Some(u) => (u, Rc::from(p)), None => return Err(self.syntax("an XML name uses an undeclared namespace prefix")), } } None => (Rc::from(Vec::new()), Rc::from(Vec::new())), }; - if !unique.insert((auri.clone(), local.to_vec())) { + if !insert_held(self, &mut held, &mut unique, (auri.clone(), local))? { return Err(self.type_error("an XML element has two attributes with the same name")); } let a = self.new_xml_node(XmlNode { @@ -2581,8 +2701,8 @@ impl Interp { self.xml_node_mut(element)?.attrs.push(a); } if !closes { - open.push(element); - names.push((name_start, name_end)); + push_held(self, stack_held, open, element)?; + push_held(self, stack_held, names, (name_start, name_end))?; } Ok(at) } @@ -2605,10 +2725,14 @@ impl Interp { } /// Parses XML text into nodes, kept reachable through the temporary roots until the caller's - /// scope ends. + /// scope ends. The open elements and their names, the text being gathered and each tag's + /// attributes are held as they grow. The allowance held from the source's length covers the + /// copy a value's units take as it becomes a string, before the node that holds it is charged. pub(crate) fn xml_parse(&mut self, source: &[u16]) -> JsResult> { let mut held = HeldBytes::new(self); held.add(self, string_bytes(source.len()).saturating_mul(2))?; + let mut stack_held = HeldBytes::new(self); + let mut text_held = HeldBytes::new(self); let settings = self.xml_settings()?; let mut src = source; let offset_start = skip_xml_space(src, 0); @@ -2638,7 +2762,7 @@ impl Interp { self.xml_text_fuel(end - pos)?; return Err(self.syntax("']]>' cannot appear in XML text")); } - self.decode_into(src, pos, end, &mut text, false)?; + self.decode_into(src, pos, end, &mut text, false, &mut text_held)?; pos = end; continue; } @@ -2650,11 +2774,13 @@ impl Interp { }; self.xml_text_fuel(end - pos)?; self.check_units(src, pos + 9, end)?; - text.extend_from_slice(src.get(pos + 9..end).unwrap_or_default()); + let section = src.get(pos + 9..end).unwrap_or_default(); + reserve_held(self, &mut text_held, &mut text, section.len())?; + text.extend_from_slice(section); pos = end + 3; continue; } - self.flush_text(&mut text, settings.ignore_whitespace, &open, &mut roots)?; + self.flush_text(&mut text, &mut text_held, settings.ignore_whitespace, &open, &mut roots)?; if rest.starts_with(&parser_units("