diff --git a/crates/color/src/recolor.rs b/crates/color/src/recolor.rs index 5117f16a36..93c0ad0f37 100644 --- a/crates/color/src/recolor.rs +++ b/crates/color/src/recolor.rs @@ -485,6 +485,88 @@ pub fn cluster(colors: &[Color], weights: &[f32], n: usize) -> Vec> { rows } +/// The distinct colors [`theme_palette`] clusters, at most. +const THEME_CANDIDATES: usize = 4096; + +/// The color palette of the weighted colors `samples` (color, weight), for Recolor Artwork's Color +/// Theme Picker: at most `n` colors. The same color given twice counts once with both weights, +/// and past [`THEME_CANDIDATES`] distinct colors, colors close in Lab merge into the heaviest of +/// them first. +/// The colors are grouped as [`cluster`] groups them, each group shows its heaviest color (a color +/// of `samples`, in its own model; on a tie the one given first), and the heaviest group comes +/// first (on a tie the group whose first color was given first). Samples without a positive, +/// finite weight are left out, so no samples give no colors. +pub fn theme_palette(samples: &[(Color, f32)], n: usize) -> Vec { + let mut index: std::collections::HashMap = std::collections::HashMap::new(); + let mut colors: Vec = vec![]; + let mut weights: Vec = vec![]; + for (c, w) in samples { + if !(w.is_finite() && *w > 0.0) { + continue; + } + let i = *index.entry(ColorKey::of(c)).or_insert_with(|| { + colors.push(*c); + weights.push(0.0); + colors.len() - 1 + }); + weights[i] += w; + } + if colors.is_empty() || n == 0 { + return vec![]; + } + // At most THEME_CANDIDATES colors are clustered: past that, colors in the same cube of Lab + // space merge into the heaviest of them, the cubes doubling in size until few enough remain. + if colors.len() > THEME_CANDIDATES { + let labs: Vec<[f32; 3]> = colors + .iter() + .map(|c| { + let l = c.to_lab(); + [l.l, l.a, l.b] + }) + .collect(); + let mut side = 2.0f32; + loop { + let mut cube: std::collections::HashMap<[i32; 3], usize> = std::collections::HashMap::new(); + let (mut top, mut sum): (Vec, Vec) = (vec![], vec![]); + for (i, lab) in labs.iter().enumerate() { + let k = lab.map(|v| (v / side).floor() as i32); + match cube.get(&k) { + Some(&j) => { + sum[j] += weights[i]; + if weights[i] > weights[top[j]] { + top[j] = i; + } + } + None => { + cube.insert(k, top.len()); + top.push(i); + sum.push(weights[i]); + } + } + } + if top.len() <= THEME_CANDIDATES { + colors = top.iter().map(|&i| colors[i]).collect(); + weights = sum; + break; + } + side *= 2.0; + } + } + let mut groups: Vec<(f32, usize, Color)> = cluster(&colors, &weights, n) + .into_iter() + .filter_map(|g| { + let total: f32 = g.iter().map(|&i| weights[i]).sum(); + let top = g.iter().copied().fold(None::, |best, i| match best { + Some(b) if weights[b] >= weights[i] => Some(b), + _ => Some(i), + })?; + Some((total, *g.first()?, colors[top])) + }) + .collect(); + groups.sort_by(|a, b| b.0.total_cmp(&a.0).then(a.1.cmp(&b.1))); + groups.into_iter().map(|g| g.2).collect() +} + /// 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)>); @@ -691,6 +773,39 @@ mod tests { assert!(cluster(&[], &[], 3).is_empty()); } + /// The Color Theme Picker's palette: similar colors merge, each group shows its heaviest + /// color in its own model, and the heaviest group comes first. + #[test] + fn theme_palette_takes_the_heaviest_color_of_each_group_heaviest_first() { + let red = Color::rgb(1.0, 0.0, 0.0); + let pink = Color::rgb(1.0, 0.2, 0.2); + let blue = Color::cmyk(1.0, 0.8, 0.0, 0.0); + let navy = Color::cmyk(1.0, 0.9, 0.0, 0.3); + let samples = [(pink, 1.0), (blue, 2.0), (red, 3.0), (navy, 2.5), (red, 0.5)]; + // Blue and navy weigh 4.5, and so do red (3 + 0.5, its two samples add up) and pink. + assert_eq!(theme_palette(&samples, 2), vec![red, navy], "a tie: the group given first"); + let samples = [(pink, 1.0), (blue, 2.0), (red, 3.0), (navy, 1.0)]; + assert_eq!(theme_palette(&samples, 2), vec![red, blue], "heaviest group first, its heaviest color"); + assert_eq!(theme_palette(&samples, 9).len(), 4, "never more colors than given"); + assert_eq!(theme_palette(&samples, 1), vec![red]); + assert!(theme_palette(&samples, 0).is_empty()); + assert!(theme_palette(&[(red, 0.0), (blue, f32::NAN), (pink, -1.0)], 3).is_empty(), "no weight, no colors"); + assert!(theme_palette(&[], 3).is_empty()); + } + + /// Past 4,096 distinct colors, close colors merge before clustering: the palette still keeps + /// a heavy color apart from thousands of light ones. + #[test] + fn theme_palette_merges_close_colors_past_its_candidate_limit() { + let mut samples: Vec<(Color, f32)> = (0..20_000).map(|i| (Color::rgb(0.0, 0.0, 0.3 + 0.7 * i as f32 / 20_000.0), 0.001)).collect(); + samples.extend((0..20_000).map(|i| (Color::rgb(1.0, 0.8 * i as f32 / 20_000.0, 0.0), 0.0001))); + samples.push((Color::rgb(0.0, 1.0, 0.0), 50.0)); + let p = theme_palette(&samples, 3); + assert_eq!(p.len(), 3); + assert_eq!(p[0], Color::rgb(0.0, 1.0, 0.0), "the heavy green first, exactly as given"); + assert!(p[1].to_hsb()[0] > 180.0 && p[2].to_hsb()[0] < 90.0, "then the blues, then the reds and oranges: {p:?}"); + } + #[test] fn hue_shift_with_own_model_puts_every_colour_of_the_row_in_the_new_model() { let to = Color::cmyk(0.0, 1.0, 1.0, 0.0); diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 6eae9c1488..fd907a26cc 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -569,7 +569,7 @@ fn clip_contains(clip: &Node, p: Point) -> bool { /// The regions `clip` clips to ([`Node::clip_shapes`]), text counted by its frame as in /// [`clip_contains`]. -fn clip_regions(clip: &Node) -> Vec<(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)> { +pub fn clip_regions(clip: &Node) -> Vec<(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)> { let frame = |n: &Node| { let b = n.geometric_bounds()?; Some(Node::path(n.id, vectorcraft_geom::shapes::rectangle(b), Default::default())) @@ -640,7 +640,7 @@ fn source_of(n: &Node, scope: Option) -> bool { /// Do clicks and marquees skip the child `i` of `parent` with `scope` isolated? For a Shaper /// Group that is its original shapes (its first child), or, in Construction mode, when they are /// isolated, the art the group shows. -fn shaper_hides(parent: &Node, i: usize, scope: Option) -> bool { +pub fn shaper_hides(parent: &Node, i: usize, scope: Option) -> bool { parent.extras().shaper.is_some() && (i == 0) != source_of(parent, scope) } @@ -1356,7 +1356,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh /// The part of a marquee `r` in which it can touch the children of `parent`. For a clip group or a /// layer with a clipping mask, this is what [`marquee_in_clip`] returns for its clipping path (None /// when the marquee misses it); otherwise it is all of `r`. -fn marquee_in(parent: &Node, r: Rect) -> Option { +pub fn marquee_in(parent: &Node, r: Rect) -> Option { match parent.children().and_then(|c| c.first()) { Some(clip) if parent.clips() => marquee_in_clip(clip, r), _ => Some(r), diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 2ed800ceec..2a970f2686 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -51,7 +51,7 @@ pub mod overprint; pub mod pattern; pub mod perspective; mod pixels; -pub use pixels::{GraySource, MAX_RASTER_ALLOC}; +pub use pixels::{GraySource, MAX_RASTER_ALLOC, PixelPick}; pub mod placed_document; pub mod plugin_data; pub mod profiles; diff --git a/crates/doc/src/pixels.rs b/crates/doc/src/pixels.rs index 30d8a7a63b..7edf64eb5e 100644 --- a/crates/doc/src/pixels.rs +++ b/crates/doc/src/pixels.rs @@ -11,6 +11,10 @@ use crate::ImageBlob; /// address and aborts when an allocation fails, so it keeps the decoder's own 512 MB. pub const MAX_RASTER_ALLOC: u64 = if cfg!(target_arch = "wasm32") { 512 << 20 } else { 2 << 30 }; +/// A box of an image to sample, in 0 to 1 units of its width and height (`None`: all of it), and +/// the pixel centres to take from it ([`ImageBlob::sample_pixels`]). +pub type PixelPick<'a> = (Option<[f64; 4]>, &'a dyn Fn(f64, f64) -> bool); + /// The pixels of encoded image `bytes` as RGBA; `None` when they can't be decoded, would take /// more than `max` bytes as RGBA, or need more than `max` bytes to decode. The size is read from /// the header first: the decoder's limit is on the file's samples, and a gray image is a quarter @@ -61,6 +65,49 @@ impl ImageBlob { Some(Self::png(png)) } + /// For each of `picks`, at most `budget` of the image's pixels (at least one), spread evenly + /// in rows and columns over the pick's box (`[u0, v0, u1, v1]`, where 0 to 1 spans the + /// image's width and height from the top left; clipped to the image; `None`: the whole image), + /// as straight RGBA. Only pixels whose centres the pick's function takes (in the same 0 to 1 + /// units) are given. The image is decoded once for all the picks. `None` when it can't be + /// decoded within [`MAX_RASTER_ALLOC`]. + pub fn sample_pixels(&self, picks: &[PixelPick<'_>], budget: usize) -> Option>> { + let img = rgba_within(&self.bytes, MAX_RASTER_ALLOC)?; + let (w, h) = img.dimensions(); + let (fw, fh) = (f64::from(w), f64::from(h)); + let span = |a: f64, b: f64, n: f64| { + let (a, b) = (a.min(b), a.max(b)); + ((a * n).floor().clamp(0.0, n) as u32, (b * n).ceil().clamp(0.0, n) as u32) + }; + let sample = |area: Option<[f64; 4]>, keep: &dyn Fn(f64, f64) -> bool| { + let [u0, v0, u1, v1] = area.unwrap_or([0.0, 0.0, 1.0, 1.0]); + let (x0, x1) = span(u0, u1, fw); + let (y0, y1) = span(v0, v1, fh); + if x0 >= x1 || y0 >= y1 { + return vec![]; + } + // Rows and columns in proportion to the box, at most `budget` cells in all. + let (bw, bh, budget) = (f64::from(x1 - x0), f64::from(y1 - y0), budget.max(1) as f64); + let (sx, sy) = if bw * bh <= budget { + (1, 1) + } else { + let rows = (budget * bh / bw).sqrt().floor().clamp(1.0, bh.min(budget)); + let cols = (budget / rows).floor().clamp(1.0, bw); + ((bw / cols).ceil() as usize, (bh / rows).ceil() as usize) + }; + let mut out = vec![]; + for y in (y0..y1).step_by(sy) { + for x in (x0..x1).step_by(sx) { + if keep((f64::from(x) + 0.5) / fw, (f64::from(y) + 0.5) / fh) { + out.push(img.get_pixel(x, y).0); + } + } + } + out + }; + Some(picks.iter().map(|(area, keep)| sample(*area, *keep)).collect()) + } + /// The image as a grayscale PNG: `f` gives each pixel's gray level from its (straight) RGB, and /// the PNG has an alpha channel only when some pixel isn't opaque. `f` runs once per distinct /// color. `None` when the image can't be decoded, or when its file stores grayscale already @@ -276,6 +323,31 @@ mod tests { image::load_from_memory(&b.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect() } + /// Sampling reads the pixels of a box of the image, spread to about the budget, and only those + /// whose centres `keep` takes. + #[test] + fn sampled_pixels_stay_in_their_box_and_budget() { + // 4 × 2: a red left half and a blue right half. + let (r, b) = ([255, 0, 0, 255], [0, 0, 255, 255]); + let img = blob(&[r, r, b, b, r, r, b, b], 4, 2); + let any = |_: f64, _: f64| true; + let one = |b: &ImageBlob, area: Option<[f64; 4]>, budget: usize| b.sample_pixels(&[(area, &any)], budget).unwrap().remove(0); + assert_eq!(one(&img, None, 100).len(), 8, "the budget covers every pixel"); + assert_eq!(one(&img, Some([0.5, 0.0, 1.0, 1.0]), 100), vec![b; 4], "the right half"); + assert_eq!(one(&img, Some([1.0, 1.0, 0.5, 0.0]), 100), vec![b; 4], "a box given backwards"); + assert!(one(&img, Some([2.0, 0.0, 3.0, 1.0]), 100).is_empty(), "outside the image"); + assert_eq!(one(&img, None, 2).len(), 2, "every second pixel of every second row"); + assert_eq!(one(&img, None, 0), vec![r], "a budget of 0 counts as 1"); + let left = |u: f64, _: f64| u < 0.5; + let both = img.sample_pixels(&[(None, &left), (Some([0.5, 0.0, 1.0, 1.0]), &any)], 100).unwrap(); + assert_eq!(both, vec![vec![r; 4], vec![b; 4]], "several picks, each with the centres its function takes"); + // A narrow image keeps to the budget too. + let tall = blob(&vec![r; 5000], 1, 5000); + let n = one(&tall, None, 100).len(); + assert!((50..=100).contains(&n), "{n} pixels"); + assert!(ImageBlob::png(b"not a png".to_vec()).sample_pixels(&[(None, &any)], 100).is_none()); + } + /// A GIF whose `w` × `h` screen holds one opaque red pixel at the top left. The file holds no /// other pixels, and the decoder makes them transparent. fn gif_with_one_red_pixel(w: u16, h: u16) -> Vec { diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index da845ba739..d69da9bae2 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -17,7 +17,7 @@ mod wrap; pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape}; use char_style::yes; -pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, ScriptMetrics}; +pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, MAX_AKI, ScriptMetrics}; pub use composite::{ COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CharClass, CompositeFont, CompositePart, CompositeParts, diff --git a/crates/doc/src/text/char_style.rs b/crates/doc/src/text/char_style.rs index fcaa78e494..a880a2a2bc 100644 --- a/crates/doc/src/text/char_style.rs +++ b/crates/doc/src/text/char_style.rs @@ -34,6 +34,16 @@ pub struct CharStyle { /// before it whose [`Self::kerning`] could space it. Elsewhere it has no effect. #[serde(default, rename = "kerningBefore", skip_serializing_if = "crate::skip::is_default")] pub kerning_before: f64, + /// Insert Aki Left (Character panel, East Asian options): space added before the character in + /// reading order, in 1/1000 em as [`Self::tracking`], 0 to 1000. Before is on the left in + /// left-to-right type, on the right in right-to-left type and above in vertical type. A + /// cluster takes the value of its first character, and full justification leaves it as it is. + /// + #[serde(default, rename = "akiLeft", skip_serializing_if = "crate::skip::is_default")] + pub aki_left: f64, + /// Insert Aki Right: space added after the character in reading order, as [`Self::aki_left`]. + #[serde(default, rename = "akiRight", skip_serializing_if = "crate::skip::is_default")] + pub aki_right: f64, /// Use glyph shapes for automatic pair spacing; false uses font metrics. #[serde(default, rename = "opticalKerning", skip_serializing_if = "crate::skip::is_default")] pub optical_kerning: bool, @@ -404,6 +414,9 @@ fn hundred() -> f64 { 100.0 } +/// The largest Insert Aki Left or Right ([`CharStyle::aki_left`]), in 1/1000 em: one em. +pub const MAX_AKI: f64 = 1000.0; + pub(super) fn yes() -> bool { true } @@ -420,6 +433,8 @@ impl Default for CharStyle { tracking: 0.0, kerning: None, kerning_before: 0.0, + aki_left: 0.0, + aki_right: 0.0, optical_kerning: false, baseline_shift: 0.0, h_scale: 100.0, @@ -468,7 +483,8 @@ impl CharStyle { /// becomes Auto, and a value past [`crate::MAX_COORD`] (a baseline shift past it either way) /// becomes the nearer end. A leading of 0, which legacy `.ai` import stores, stays, and a /// baseline shift that is not a number becomes 0. The Tate-chu-yoko Up/Down and Left/Right - /// offsets are kept as the baseline shift is. + /// offsets are kept as the baseline shift is. Insert Aki Left and Right are kept from 0 to + /// [`MAX_AKI`], and one that is not a number becomes 0. pub fn keep_dimensions_in_range(&mut self) { let default = Self::default(); let within = |v: f64, or: f64| if v > 0.0 { v.min(crate::MAX_COORD) } else { or }; @@ -480,6 +496,9 @@ impl CharStyle { self.baseline_shift = shift(self.baseline_shift); self.tcy_up_down = shift(self.tcy_up_down); self.tcy_left_right = shift(self.tcy_left_right); + let aki = |v: f64| if v.is_nan() { 0.0 } else { v.clamp(0.0, MAX_AKI) }; + self.aki_left = aki(self.aki_left); + self.aki_right = aki(self.aki_right); } /// Do the characters draw a stroke (a paint and a positive weight)? pub fn has_stroke(&self) -> bool { diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index d46b45b1f7..68f41abd5b 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -490,6 +490,8 @@ impl crate::Document { st.baseline_shift = num("baseline_shift").unwrap_or(st.baseline_shift); st.tcy_up_down = num("tcyUpDown").unwrap_or(st.tcy_up_down); st.tcy_left_right = num("tcyLeftRight").unwrap_or(st.tcy_left_right); + st.aki_left = num("akiLeft").unwrap_or(st.aki_left); + st.aki_right = num("akiRight").unwrap_or(st.aki_right); st.keep_dimensions_in_range(); let kept = [ ("size", Some(st.size)), @@ -498,6 +500,8 @@ impl crate::Document { ("baseline_shift", Some(st.baseline_shift)), ("tcyUpDown", Some(st.tcy_up_down)), ("tcyLeftRight", Some(st.tcy_left_right)), + ("akiLeft", Some(st.aki_left)), + ("akiRight", Some(st.aki_right)), ("leading", st.leading), ]; for (k, v) in kept { diff --git a/crates/doc/src/text/tabs_lists.rs b/crates/doc/src/text/tabs_lists.rs index e213c252bb..4fcaa8d078 100644 --- a/crates/doc/src/text/tabs_lists.rs +++ b/crates/doc/src/text/tabs_lists.rs @@ -357,7 +357,7 @@ impl ParaList { /// The style the marker is set in: `first` (the style of the paragraph's first character) /// without its baseline shift, rotation, superscript or subscript, tracking, manual kerning, - /// tate-chu-yoko, underline and strikethrough. + /// Insert Aki, tate-chu-yoko, underline and strikethrough. pub fn marker_style(first: &CharStyle) -> CharStyle { CharStyle { baseline_shift: 0.0, @@ -366,6 +366,8 @@ impl ParaList { tracking: 0.0, kerning: None, kerning_before: 0.0, + aki_left: 0.0, + aki_right: 0.0, optical_kerning: first.optical_kerning, tate_chu_yoko: false, underline: false, diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index 3b3781f87c..0f474d2ed8 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -92,6 +92,43 @@ fn font_height_reference_is_saved_only_when_not_the_em_box() { assert_eq!(serde_json::from_value::(old).unwrap().font_height_reference, FontHeightReference::EmBox); } +/// Insert Aki Left and Right are 0 by default and saved only when not 0, each side on its own; +/// styles written before them read as 0, and a value out of range from a file is kept from 0 to one +/// em. +#[test] +fn insert_aki_is_saved_only_when_set() { + let st = CharStyle::default(); + assert_eq!((st.aki_left, st.aki_right), (0.0, 0.0)); + let saved = serde_json::to_value(&st).unwrap(); + assert!(saved.get("akiLeft").is_none() && saved.get("akiRight").is_none()); + for set in [ + CharStyle { aki_left: 250.0, ..CharStyle::default() }, + CharStyle { aki_right: 500.0, ..CharStyle::default() }, + CharStyle { aki_left: 125.5, aki_right: 1000.0, ..CharStyle::default() }, + ] { + let saved = serde_json::to_value(&set).unwrap(); + assert_eq!(saved.get("akiLeft").and_then(serde_json::Value::as_f64).unwrap_or(0.0), set.aki_left); + assert_eq!(saved.get("akiRight").and_then(serde_json::Value::as_f64).unwrap_or(0.0), set.aki_right); + assert_eq!(saved.get("akiLeft").is_some(), set.aki_left != 0.0); + assert_eq!(serde_json::from_value::(saved).unwrap(), set); + } + let old = serde_json::to_value(&st).unwrap(); + let read = serde_json::from_value::(old).unwrap(); + assert_eq!((read.aki_left, read.aki_right), (0.0, 0.0)); + let mut damaged = CharStyle { aki_left: -20.0, aki_right: 4000.0, ..CharStyle::default() }; + damaged.keep_dimensions_in_range(); + assert_eq!((damaged.aki_left, damaged.aki_right), (0.0, MAX_AKI)); + let mut damaged = CharStyle { aki_left: f64::NAN, aki_right: f64::INFINITY, ..CharStyle::default() }; + damaged.keep_dimensions_in_range(); + assert_eq!((damaged.aki_left, damaged.aki_right), (0.0, MAX_AKI)); + // A character style from a file is kept in range the same way. + let mut d = crate::Document::new(100.0, 100.0); + let attrs = serde_json::json!({"akiLeft": 5000, "akiRight": -1}); + d.char_styles.push(TextStyleDef { name: "Spaced".into(), attrs: attrs.as_object().cloned().unwrap_or_default() }); + d.keep_type_values_in_range(); + assert_eq!((d.char_styles[0].attrs["akiLeft"].as_f64(), d.char_styles[0].attrs["akiRight"].as_f64()), (Some(MAX_AKI), Some(0.0))); +} + /// Each Indic numeral system draws 0–9 (and the Arabic-Indic sets) as the ten digits of its /// script's block; every system saves under its id, which reads back, and other names are refused. #[test] diff --git a/crates/effects/Cargo.toml b/crates/effects/Cargo.toml index 4078312855..d5821607ec 100644 --- a/crates/effects/Cargo.toml +++ b/crates/effects/Cargo.toml @@ -26,3 +26,5 @@ serde_json = { workspace = true } [dev-dependencies] vectorcraft-color = { workspace = true } +# A face built in code from the bundled Source Sans 3 (no font file is committed). +vectorcraft-text = { workspace = true, features = ["test-fonts"] } diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index 0f61fda674..959bd5e857 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -689,7 +689,7 @@ pub fn member_shapes(doc: Option<&Document>, n: &Node) -> Vec<(PathData, FillRul } /// A path node of `id` on `path` (filled under `rule`) painted by `ap`. -fn shape_node(id: NodeId, path: PathData, rule: FillRule, ap: Appearance) -> Node { +pub(crate) fn shape_node(id: NodeId, path: PathData, rule: FillRule, ap: Appearance) -> Node { let mut n = Node::path(id, path, ap); if let NodeKind::Path { rule: r, .. } = &mut n.kind { *r = rule; diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index 0006e5362f..eb227300e0 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -594,7 +594,7 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { if is_container(n) { return group_art(n, expand); } - let (path, _) = profile(n)?; + let (path, rule) = profile(n)?; let ctx = GeomContext::of(n); let mut children = vec![]; let mut copies = 0; @@ -620,15 +620,17 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let path = geometry(&path, &n.appearance.effects, &ctx); remaining = crate::without_geometry(&remaining); // The object's Transform effects, applied to the path above, transform the items' raster - // effects too. - let mut items: Vec = n.appearance.items.iter().filter(|i| crate::paints(i)).cloned().collect(); + // effects too. Each copy keeps its item beside it, which plug-in effects are told they sit + // on. + let originals: Vec<&AppearanceItem> = n.appearance.items.iter().filter(|i| crate::paints(i)).collect(); + let mut items: Vec = originals.iter().map(|i| (*i).clone()).collect(); crate::raster::follow_paints(&mut items, &n.appearance.effects); // Every item's shadow goes behind every item's art. let mut shadows = vec![]; - for item in &items { + for (original, item) in originals.into_iter().zip(&items) { if let Some(index) = item.effects().iter().position(|e| e.visible && is_revolve(&e.id)) { let fx = item.effects().get(index)?; - let p = geometry(&path, item.effects().get(..index)?, &ctx.item(item)); + let p = geometry(&path, item.effects().get(..index)?, &ctx.item(original)); let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); let mut art = object_surface(n, &p, fx, item, expand, &mut copies)?; art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect(); @@ -640,7 +642,8 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { } children.push(Arc::new(art)); } else { - children.push(Arc::new(Node::path(n.id, path.clone(), Appearance { items: vec![item.clone()], ..Default::default() }))); + let flat = Appearance { items: vec![item.clone()], ..Default::default() }; + children.push(Arc::new(crate::group::shape_node(n.id, path.clone(), rule, flat))); } } children.splice(0..0, shadows); @@ -1022,6 +1025,52 @@ mod tests { assert!(surface.children().unwrap().iter().all(|c| c.opacity == 1.0 && !has_revolve(c))); } #[test] + fn a_fill_without_the_revolve_keeps_the_even_odd_hole() { + use vectorcraft_geom::FillRule; + use vectorcraft_geom::hit::fill_contains; + // Two nested squares drawn in the same direction: only the even-odd rule leaves a hole. + let [outer, inner] = [(100.0, 200.0), (130.0, 170.0)].map(|(lo, hi)| { + let mut b = BezPath::new(); + b.move_to((lo, lo)); + b.line_to((hi, lo)); + b.line_to((hi, hi)); + b.line_to((lo, hi)); + b.close_path(); + PathData::from_bezpath(&b) + }); + let flat = AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::rgb(0.1, 0.3, 0.9)))); + for id in [REVOLVE, CLASSIC_REVOLVE] { + let mut top = AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::rgb(0.8, 0.2, 0.1)))); + top.effects_mut().push(crate::new_effect(id, &json!({})).unwrap()); + let appearance = Appearance { items: vec![flat.clone(), top], ..Default::default() }; + let members = vec![ + Arc::new(Node::path(NodeId(2), outer.clone(), Appearance::default())), + Arc::new(Node::path(NodeId(3), inner.clone(), Appearance::default())), + ]; + let mut compound = Node::new(NodeId(1), NodeKind::Compound { children: members, rule: FillRule::EvenOdd }); + compound.appearance = appearance.clone().into(); + let both = PathData::new(outer.subpaths.iter().chain(&inner.subpaths).cloned().collect()); + let path = crate::group::shape_node(NodeId(1), both, FillRule::EvenOdd, appearance); + for (n, shape) in [(compound, "compound path"), (path, "path")] { + for (art, how) in [(revolve_art(&n), "live"), (expand_revolve_art(&n), "expanded")] { + let what = format!("{id} on the top fill of a {shape}, {how}"); + let art = art.unwrap_or_else(|| panic!("{what}")); + let children = art.children().unwrap(); + let plain: Vec = (0..children.len()) + .filter(|&i| children[i].appearance.items == [flat.clone()] && children[i].path_data().is_some()) + .collect(); + let [index] = plain[..] else { panic!("{what}: one flat child, got {plain:?}") }; + let NodeKind::Path { path, rule, .. } = &children[index].kind else { panic!("{what}: a path") }; + assert_eq!(*rule, FillRule::EvenOdd, "{what}"); + let bez = path.to_bezpath(); + assert!(fill_contains(&bez, *rule, Point::new(110.0, 150.0)), "{what}: the ring is filled"); + assert!(!fill_contains(&bez, *rule, Point::new(150.0, 150.0)), "{what}: the hole stays open"); + assert!(index + 1 < children.len(), "{what}: the revolved art is drawn above"); + } + } + } + } + #[test] fn export_bakes_faces_with_unique_ids_and_no_revolve_effects() { let mut d = Document::new(300.0, 300.0); let mut n = profile_node(); diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index e4fb218604..93679ca71d 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -1197,7 +1197,8 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option { shadows.extend(shadow.into_iter().map(with_later)); children.extend(surfaces.into_iter().map(with_later)); } else { - children.push(Arc::new(Node::path(n.id, path.clone(), Appearance { items: vec![item.clone()], ..Default::default() }))); + let flat = Appearance { items: vec![item.clone()], ..Default::default() }; + children.push(Arc::new(crate::group::shape_node(n.id, path.clone(), rule, flat))); } } children.splice(0..0, shadows); diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index 1efe826c75..5041f01bb2 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -457,6 +457,68 @@ fn transparency_stays_on_the_whole_surface_and_items_take_their_own_effect() { assert!(matches!(surfaces[1].kind, NodeKind::Path { .. })); } +/// Two nested squares drawn in the same direction, so only the even-odd rule leaves a hole. +fn nested_squares() -> [PathData; 2] { + [(100.0, 200.0), (130.0, 170.0)].map(|(lo, hi)| { + let mut b = BezPath::new(); + b.move_to((lo, lo)); + b.line_to((hi, lo)); + b.line_to((hi, hi)); + b.line_to((lo, hi)); + b.close_path(); + PathData::from_bezpath(&b) + }) +} + +/// The nested squares as an even-odd compound path and as one even-odd path, painted by `items`. +fn even_odd_shapes(items: Vec) -> [Node; 2] { + let [outer, inner] = nested_squares(); + let appearance = Appearance { items, ..Default::default() }; + let children = vec![ + Arc::new(Node::path(NodeId(2), outer.clone(), Appearance::default())), + Arc::new(Node::path(NodeId(3), inner.clone(), Appearance::default())), + ]; + let mut compound = Node::new(NodeId(1), NodeKind::Compound { children, rule: FillRule::EvenOdd }); + compound.appearance = appearance.clone().into(); + let both = PathData::new(outer.subpaths.into_iter().chain(inner.subpaths).collect()); + [compound, crate::group::shape_node(NodeId(1), both, FillRule::EvenOdd, appearance)] +} + +/// Check that `art` draws `item` as one flat child: an even-odd path with a hole in the middle, +/// below the 3D art after it. +fn assert_flat_item_keeps_the_hole(art: &Node, item: &AppearanceItem, what: &str) { + use vectorcraft_geom::hit::fill_contains; + let children = art.children().unwrap(); + let flat: Vec = + (0..children.len()).filter(|&i| children[i].appearance.items == [item.clone()] && children[i].path_data().is_some()).collect(); + let [index] = flat[..] else { panic!("{what}: one flat child, got {flat:?}") }; + let NodeKind::Path { path, rule, .. } = &children[index].kind else { panic!("{what}: a path") }; + assert_eq!(*rule, FillRule::EvenOdd, "{what}"); + let bez = path.to_bezpath(); + assert!(fill_contains(&bez, *rule, Point::new(110.0, 150.0)), "{what}: the ring is filled"); + assert!(!fill_contains(&bez, *rule, Point::new(150.0, 150.0)), "{what}: the hole stays open"); + assert!(index + 1 < children.len(), "{what}: the 3D art is drawn above"); +} + +#[test] +fn a_fill_or_stroke_without_the_effect_keeps_the_even_odd_hole() { + let red = AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(RED))); + let blue = AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(BLUE))); + let stroke = AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), 4.0)); + for id in SOLIDS { + // The top fill and then the top stroke take the effect; the fill below stays flat. + for (top, on) in [(&red, "fill"), (&stroke, "stroke")] { + let mut lifted = top.clone(); + lifted.effects_mut().push(fx(id, json!({}))); + for (n, shape) in even_odd_shapes(vec![blue.clone(), lifted]).into_iter().zip(["compound path", "path"]) { + let what = format!("{id} on the top {on} of a {shape}"); + let art = solid_art(&n).unwrap_or_else(|| panic!("{what}")); + assert_flat_item_keeps_the_hole(&art, &blue, &what); + } + } + } +} + #[test] fn export_and_expand_bake_faces_with_their_own_ids() { for id in SOLIDS { diff --git a/crates/effects/tests/envelope_ink.rs b/crates/effects/tests/envelope_ink.rs index a95906cc1b..45ac0fb64d 100644 --- a/crates/effects/tests/envelope_ink.rs +++ b/crates/effects/tests/envelope_ink.rs @@ -6,20 +6,38 @@ use std::sync::Arc; use vectorcraft_doc::{CharStyle, Node, NodeId, NodeKind, TextObject}; -use vectorcraft_geom::{Point, Rect}; +use vectorcraft_geom::{Point, Rect, Shape}; +use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font}; /// The largest distance between the edges of `a` and `b`. fn off(a: Rect, b: Rect) -> f64 { [a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().fold(0.0f64, |m, v| m.max(v.abs())) } +/// "Type" at 48 pt in a face the test adds, so its glyphs draw on a machine without craft-fonts or +/// system fonts. +fn type_in_test_face() -> TextObject { + assert!(vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap()) > 0, "the test face loads"); + TextObject::point(Point::new(10.0, 60.0), "Type", CharStyle { font_family: HEIGHT_FAMILY.into(), size: 48.0, ..Default::default() }) +} + +/// The box of the outlines `t`'s glyphs draw, in document space, measured glyph by glyph. +fn outline_box(t: &TextObject) -> Rect { + let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + let outlines: Vec = laid.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| (t.xf * &g.outline).bounding_box()).collect(); + assert_eq!(outlines.len(), 4, "every glyph of \"Type\" draws an outline"); + outlines.into_iter().reduce(|a, b| a.union(b)).unwrap() +} + #[test] fn live_evaluation_measures_type_in_envelopes_by_its_glyphs() { - let t = TextObject::point(Point::new(10.0, 60.0), "Type", CharStyle { size: 48.0, ..Default::default() }); + let t = type_in_test_face(); let n = Arc::new(Node::new(NodeId(1), NodeKind::Text(Box::new(t.clone())))); let laid = n.geometric_bounds().unwrap(); - let ink = t.xf.transform_rect_bbox(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).ink_bounds().unwrap()); + let ink = outline_box(&t); assert!(laid.height() - ink.height() > 1.0, "the laid-out box {laid:?} reaches past the glyphs {ink:?}"); + let measured = vectorcraft_text::envelope_ink(&t, t.xf, None).unwrap(); + assert!(off(measured, ink) < 1e-6, "the envelope measure gives the glyphs' box: {measured:?} vs {ink:?}"); let before = vectorcraft_doc::live::envelope_content_bounds(std::slice::from_ref(&n)).unwrap(); assert!(off(before, laid) < 1e-6, "with nothing registered, type keeps its laid-out box: {before:?} vs {laid:?}"); diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 66eb2104d1..eab57e2a91 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -426,8 +426,13 @@ pub(crate) fn bad(cmd: &str, msg: impl Into) -> EngineError { pub(crate) fn f64_or(p: &Value, key: &str, default: f64) -> f64 { p.get(key).and_then(Value::as_f64).unwrap_or(default) } +/// The number `p` gives for `key`. A missing key or null is "missing number `{key}`"; any other +/// value, such as `"40"`, is "`{key}` must be a number, not {v}", as [`number_or`] words it. pub(crate) fn f64_req(p: &Value, key: &str, cmd: &str) -> Result { - p.get(key).and_then(Value::as_f64).ok_or_else(|| bad(cmd, format!("missing number `{key}`"))) + match p.get(key) { + None | Some(Value::Null) => Err(bad(cmd, format!("missing number `{key}`"))), + Some(v) => v.as_f64().ok_or_else(|| bad(cmd, format!("`{key}` must be a number, not {v}"))), + } } /// The number `p` gives for `key`, or `default` when `p` leaves it out or gives null. Any other /// value, such as `"40"`, is an error: "`{key}` must be a number, not {v}". diff --git a/crates/engine/src/cmd/addons/cleanup/text.rs b/crates/engine/src/cmd/addons/cleanup/text.rs index 10fd432dfc..7d7dcbb197 100644 --- a/crates/engine/src/cmd/addons/cleanup/text.rs +++ b/crates/engine/src/cmd/addons/cleanup/text.rs @@ -12,7 +12,7 @@ use vectorcraft_doc::{CharStyle, Document, Justify, Node, NodeId, NodeKind, Para use vectorcraft_geom::{Affine, Point, Vec2}; use vectorcraft_text::{FontDb, FontMatch, TextLayout, edit}; -use crate::cmd::fonts::{edit_symbol_texts, symbol_texts}; +use crate::cmd::fonts::{art_texts_of, edit_art_texts_of}; use crate::cmd::textedit::{editing_range, editing_story}; use crate::cmd::typecmd::refresh_bounds; use crate::cmd::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param}; @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Replace Missing Fonts…", ["Object", "Plug-ins", "Artwork Cleanup"], None, - "{font?: family (default: the default type font, Source Sans 3; any of its names)} set every character of the document's type (the type in the art of its symbols included) whose font family isn't available in `font`, in the style it has closest to the one each had, as one undo step → {runs (style runs changed), font}", + "{font?: family (default: the default type font, Source Sans 3; any of its names)} set every character of the document's type (the type in its opacity masks and in the art of its symbols and patterns included, hidden or locked type and disabled masks too) whose font family isn't available in `font`, in the style it has closest to the one each had, as one undo step → {runs (style runs changed), font}", has_doc, replace_fonts ), @@ -982,8 +982,9 @@ fn replace_fonts(s: &mut Session, p: &Value) -> Result { } }); } - // The type in the symbols' art too, which exports name when its font is missing. - if ids.is_empty() && !symbol_texts(d, None).into_iter().any(|(t, _)| lacks(t)) { + // The type in opacity masks and in the art of symbols and patterns too, hidden or locked type + // included, which exports name when its font is missing. + if ids.is_empty() && !art_texts_of(d).into_iter().any(|(_, t, _)| lacks(t)) { return Err(EngineError::Other("No fonts are missing".into())); } let runs = s.edit("Replace Missing Fonts", |d, _| { @@ -1008,7 +1009,7 @@ fn replace_fonts(s: &mut Session, p: &Value) -> Result { replace(t); } } - edit_symbol_texts(d, None, &|t, _| lacks(t), &mut replace); + edit_art_texts_of(d, &lacks, &mut replace); Ok(runs) })?; Ok(json!({ "runs": runs, "font": family })) diff --git a/crates/engine/src/cmd/addons/cleanup/text/tests.rs b/crates/engine/src/cmd/addons/cleanup/text/tests.rs index 0af24be36a..3769cf3b42 100644 --- a/crates/engine/src/cmd/addons/cleanup/text/tests.rs +++ b/crates/engine/src/cmd/addons/cleanup/text/tests.rs @@ -415,3 +415,53 @@ fn replace_missing_fonts_reaches_the_type_in_symbols() { s.execute("symbol.exitEditing", &json!({})).unwrap(); assert_eq!(crate::cmd::fonts::substitution_warning(&s.doc().unwrap().doc), None); } + +/// Replace Missing Fonts reaches the type in opacity masks (of a hidden object, disabled, in a +/// symbol's art) and in a pattern swatch nothing paints with, and the export warning, the missing +/// fonts list and Find Font name that type's font until it is replaced. +#[test] +fn replace_missing_fonts_reaches_the_type_in_masks_and_patterns() { + let mut s = session(); + let mask = |s: &mut Session, owner: NodeId, art: NodeId| { + s.edit("Mask", |d, _| { + let art = d.remove(art)?; + d.node_mut(owner).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true))); + Ok(()) + }) + .unwrap(); + }; + let lost = |s: &mut Session| text(s, json!({"x": 40, "y": 60, "text": "Lost", "size": 20, "font": "No Such Font Family"})); + let rect = + |s: &mut Session| NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap()); + let (hidden, disabled, in_symbol) = (rect(&mut s), rect(&mut s), rect(&mut s)); + for owner in [hidden, disabled, in_symbol] { + let t = lost(&mut s); + mask(&mut s, owner, t); + } + s.execute("select.set", &json!({"ids": [hidden.0]})).unwrap(); + s.execute("object.hide", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [disabled.0]})).unwrap(); + s.execute("transparency.disableOpacityMask", &json!({})).unwrap(); + s.execute("symbol.new", &json!({"name": "Mark", "ids": [in_symbol.0]})).unwrap(); + let t = lost(&mut s); + s.execute("object.pattern.make", &json!({"ids": [t.0], "name": "Unused", "edit": false})).unwrap(); + select(&mut s, &[t]); + s.execute("edit.clear", &json!({})).unwrap(); + let mut on_layers = 0; + s.doc().unwrap().doc.walk(|n| on_layers += usize::from(matches!(n.kind, NodeKind::Text(_)))); + assert_eq!(on_layers, 0, "the type is only in masks, a symbol and a pattern"); + let missing = |s: &Session| crate::cmd::fontfiles::missing_fonts(&s.doc().unwrap().doc).into_iter().map(|f| f.family).collect::>(); + assert_eq!(missing(&s), ["No Such Font Family"]); + assert!(crate::cmd::fonts::substitution_warning(&s.doc().unwrap().doc).is_some_and(|w| w.contains("No Such Font Family"))); + let listed = s.execute("text.fonts", &json!({})).unwrap(); + assert_eq!((listed[0]["family"].as_str(), listed[0]["objects"].as_u64()), (Some("No Such Font Family"), Some(4)), "{listed}"); + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let before = steps(&s); + let r = s.execute("addon.cleanup.replaceFonts", &json!({})).unwrap(); + assert_eq!(r["runs"].as_u64(), Some(4), "{r}"); + assert_eq!(steps(&s), before + 1); + assert!(missing(&s).is_empty()); + assert_eq!(crate::cmd::fonts::substitution_warning(&s.doc().unwrap().doc), None); + assert_eq!(other(s.execute("addon.cleanup.replaceFonts", &json!({}))), "No fonts are missing"); + assert_eq!(steps(&s), before + 1); +} diff --git a/crates/engine/src/cmd/addons/cutting/weed.rs b/crates/engine/src/cmd/addons/cutting/weed.rs index a05770a024..8a6375a595 100644 --- a/crates/engine/src/cmd/addons/cutting/weed.rs +++ b/crates/engine/src/cmd/addons/cutting/weed.rs @@ -40,7 +40,7 @@ pub fn specs() -> Vec { "Weed Box and Lines…", ["Object", "Plug-ins", "Cutting Tools"], None, - "{margin?: pt 0..100000 (9: from the art to the weed box), box?: true (false: the weeding lines only), direction?: \"horizontal\" | \"vertical\" | \"both\" (\"both\"), count?: whole number 0..1000 of lines each way (1), spacing?: pt (instead of count: as few lines as keep them at most this far apart), gap?: pt 0..100000 (0: the lines stop at the art's outlines), weight?: pt 0.01..1000 (0.3), swatch?: a color swatch the lines are stroked in (\"[Registration]\")} add a weed box around the selected art and weeding lines across it that divide it evenly, each running from one side of the box to the other and left out over the art and within `gap` of its outlines, so the waste lifts off in pieces. The art is measured by the outlines a cutter cuts: closed paths enclose their area by their fill rule and open paths are lines, compound paths by all their subpaths, type by its glyph outlines, a clip group by what shows inside its clipping path, images by their frames, placed files by the art they show (by their boxes when the file can't be read), symbol instances by their art and live objects by the art they draw; strokes, effects and hidden objects are left out. One group named Weeding, stroked with no fill, on top of the current layer (outside the clip groups around a group edited in isolation), selected, as one undo step → {id: the group, box: its weed box or null, lines (pieces of weeding line)}", + "{margin?: pt 0..100000 (9: from the art to the weed box), box?: true (false: the weeding lines only), direction?: \"horizontal\" | \"vertical\" | \"both\" (\"both\"), count?: whole number 0..1000 of lines each way (1), spacing?: pt more than 0 and at most 100000 (instead of count, never with it: as few lines as keep them at most this far apart, up to 1000 each way), gap?: pt 0..100000 (0: the lines stop at the art's outlines), weight?: pt 0.01..1000 (0.3), swatch?: a color swatch the lines are stroked in (\"[Registration]\")} add a weed box around the selected art and weeding lines across it that divide it evenly, each running from one side of the box to the other and left out over the art and within `gap` of its outlines, so the waste lifts off in pieces. The art is measured by the outlines a cutter cuts: closed paths enclose their area by their fill rule and open paths are lines, compound paths by all their subpaths, type by its glyph outlines, a clip group by what shows inside its clipping path, images by their frames, placed files by the art they show (by their boxes when the file can't be read), symbol instances by their art and live objects by the art they draw; strokes, effects and hidden objects are left out. One group named Weeding, stroked with no fill, on top of the current layer (outside the clip groups around a group edited in isolation), selected, as one undo step → {id: the group, box: its weed box or null, lines (pieces of weeding line)}", has_selection, weed )] diff --git a/crates/engine/src/cmd/addons/cutting/weed/geometry.rs b/crates/engine/src/cmd/addons/cutting/weed/geometry.rs index 4642031e71..0db89fb2ee 100644 --- a/crates/engine/src/cmd/addons/cutting/weed/geometry.rs +++ b/crates/engine/src/cmd/addons/cutting/weed/geometry.rs @@ -723,12 +723,13 @@ pub(super) fn lines(region: &Region, outline: &[Segment], frame: Rect, n: Counts continue; } // The lines (0-based) each outline segment comes within `gap` of: lines k (1-based) lie at - // v0 + k·step. + // v0 + k·step. The range is widened by a small tolerance so that a line whose position + // rounds just past a segment's end is still measured; `near` drops lines the segment misses. let reach = |&(a, b): &Segment| { let (va, vb) = (uv(a, vertical).1, uv(b, vertical).1); let (lo, hi) = (va.min(vb) - gap, va.max(vb) + gap); - let first = ((lo - v0) / step).ceil().max(1.0); - let last = ((hi - v0) / step).floor().min(count as f64); + let first = ((lo - v0) / step - 1e-9).ceil().max(1.0); + let last = ((hi - v0) / step + 1e-9).floor().min(count as f64); if step > 0.0 && first <= last { (first as usize - 1)..(last as usize) } else { 0..0 } }; // The outlines near each line, found once for all of them, by index into `outline`. diff --git a/crates/engine/src/cmd/addons/cutting/weed/tests.rs b/crates/engine/src/cmd/addons/cutting/weed/tests.rs index 1003ef1db3..69114f8991 100644 --- a/crates/engine/src/cmd/addons/cutting/weed/tests.rs +++ b/crates/engine/src/cmd/addons/cutting/weed/tests.rs @@ -541,6 +541,24 @@ fn indexed_crossings_find_the_same_stretches() { } } +/// An outline that lies on a weeding line stops it even when the line's position rounds just past +/// the outline's: the one line across 0.1 to 0.5 lies at 0.1 + 0.2, which is 0.30000000000000004, +/// and (0.30000000000000004 - 0.1) / 0.2 is 1.0000000000000002. +#[test] +fn an_outline_on_a_rounded_line_position_stops_the_line() { + let doc = vectorcraft_doc::Document::new(800.0, 600.0); + let c = 0.1 + 0.2; + let mut p = BezPath::new(); + p.move_to((20.0, c)); + p.line_to((80.0, c)); + let n = Node::path(NodeId(1), PathData::from_bezpath(&p), Appearance::default()); + let region = super::geometry::Reader::new(&doc).read(&[&n]).unwrap().unwrap(); + let outline = region.outline().unwrap(); + let counts = super::geometry::Counts { horizontal: 1, vertical: 0 }; + let pieces = super::geometry::lines(®ion, &outline, Rect::new(0.0, 0.1, 100.0, 0.5), counts, 0.0, 100).unwrap(); + assert_eq!(pieces, [(Point::new(0.0, c), Point::new(20.0, c)), (Point::new(80.0, c), Point::new(100.0, c))]); +} + #[test] fn art_nested_too_deep_is_refused() { // A rectangle inside `levels` groups, each holding the next. A document keeps none this deep, diff --git a/crates/engine/src/cmd/artboardalign.rs b/crates/engine/src/cmd/artboardalign.rs index 9832133729..541ec94a4e 100644 --- a/crates/engine/src/cmd/artboardalign.rs +++ b/crates/engine/src/cmd/artboardalign.rs @@ -17,7 +17,7 @@ pub fn specs() -> Vec { "Align", [], None, - "{index? | indices?: [n…], selectedArtboards?: [n…] (as artboard.duplicate; default: the artboards the Artboard tool has selected, else its active one), horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\" (one of the two is needed), to?: \"selection\"|\"artboard\" (default \"selection\": the bounds of the artboards together; \"artboard\": artboard `artboard`, which stays where it is), artboard?: n (0-based; the artboard to align to with to: \"artboard\"; default: the Artboard tool's active one; it need not be one of the artboards aligned), activeArtboard?: n (the journal records that default here, for a replay; `artboard` goes ahead of it), moveArt?: bool (the art fully inside each artboard moves with it; default: the Artboard tool's Move Artwork with Artboard option), patterns?: bool, lockedAndHidden?: bool (as artboard.move)} (Align panel › Align Objects with the Artboard tool chosen) each artboard moves until its edge or center is on that edge or center of what it aligns to, with its guides, in one undo step; a locked artboard stays where it is and still counts in the bounds, and the call fails with `the artboard is locked` when every artboard it names is locked; when no artboard moves, no undo step is recorded → {moved: [index…]}", + "{index? | indices?: [n…], selectedArtboards?: [n…] (as artboard.duplicate; default: the artboards the Artboard tool has selected, else its active one), horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\" (one of the two is needed), to?: \"selection\"|\"artboard\" (default \"selection\": the bounds of the artboards together; \"artboard\": artboard `artboard`, which stays where it is), artboard?: n (0-based; the artboard to align to with to: \"artboard\"; default: the Artboard tool's active one; it need not be one of the artboards aligned), activeArtboard?: n (the journal records that default here, for a replay; `artboard` goes ahead of it), moveArt?: bool (the art fully inside each artboard moves with it, art inside two of them with the first by index, which may stay; default: the Artboard tool's Move Artwork with Artboard option), patterns?: bool, lockedAndHidden?: bool (as artboard.move)} (Align panel › Align Objects with the Artboard tool chosen) each artboard moves until its edge or center is on that edge or center of what it aligns to, with its guides, in one undo step; a locked artboard stays where it is and still counts in the bounds, and the call fails with `the artboard is locked` when every artboard it names is locked; when no artboard moves, no undo step is recorded → {moved: [index…]}", has_doc, align ), @@ -114,18 +114,27 @@ fn kept(b: &Boards, items: &[(usize, Rect)], gap: Option) -> Result Result { let d = &s.doc()?.doc; - let moves: Vec<(usize, Vec2)> = + let mut moves: Vec<(usize, Vec2)> = moves.iter().copied().filter(|(i, dv)| (dv.x.abs() > 1e-9 || dv.y.abs() > 1e-9) && d.artboards.get(*i).is_some_and(|a| !a.locked)).collect(); + // In artboard order, as the other artboard edits take them, whatever order the Distribute + // commands spaced them in. + moves.sort_by_key(|(i, _)| *i); let moved: Vec = moves.iter().map(|(i, _)| *i).collect(); if moves.is_empty() { return Ok(json!({ "moved": moved })); } - let arts = artboards_art(s, &moved, b.move_art, b.locked_art, true)?; + // The art of every artboard named, those that stay included, so that art on overlapping + // artboards goes with the first by index; then that of the artboards that move. + let named: Vec = b.items.iter().map(|(i, _)| *i).collect(); + let arts: Vec<(usize, Vec)> = + artboards_art(s, &named, b.move_art, b.locked_art, true)?.into_iter().filter(|(i, _)| moved.contains(i)).collect(); let ids: Vec = arts.iter().flat_map(|(_, a)| a.iter().copied()).collect(); let sc = Scaling { patterns: super::object::transform_patterns(s, p, &ids)?, ..Scaling::default() }; s.edit(label, |d, _| { diff --git a/crates/engine/src/cmd/artboardalign/tests.rs b/crates/engine/src/cmd/artboardalign/tests.rs index 94733b099e..526a50db31 100644 --- a/crates/engine/src/cmd/artboardalign/tests.rs +++ b/crates/engine/src/cmd/artboardalign/tests.rs @@ -265,6 +265,39 @@ fn bad_params_are_errors() { assert_eq!((undo_steps(&s), corners(&s)), (steps, before)); } +/// Art inside two overlapping artboards moves with the one first in artboard order, as with the +/// other artboard edits, even when Distribute spaces the other one first: artboard 2 at x 140 is +/// left of artboard 1 at x 200, and the square inside both goes with artboard 1. +#[test] +fn art_on_overlapping_artboards_moves_with_the_first_by_index() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("artboard.new", &json!({"x": 200, "y": 0, "width": 100, "height": 100})).unwrap(); + s.execute("artboard.new", &json!({"x": 140, "y": 0, "width": 100, "height": 100})).unwrap(); + let sq = s.execute("shape.rectangle", &json!({"x": 210, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let p = json!({"indices": ALL, "to": "artboard", "artboard": 0, "spacing": 10}); + assert_eq!(s.execute("artboard.distributeSpacing", &p).unwrap(), json!({"moved": [1, 2]})); + assert_eq!(corners(&s), [(0.0, 0.0), (220.0, 0.0), (110.0, 0.0)]); + assert_eq!(corner(&s, sq), (230.0, 10.0), "with artboard 1, 20 pt to the right"); +} + +/// Art inside an artboard that stays and a later one that moves stays with the first: artboard 2 +/// overlaps artboard 0, and aligning it to artboard 0 leaves the square inside both in place. +#[test] +fn art_shared_with_an_artboard_that_stays_stays() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("artboard.new", &json!({"x": 200, "y": 0, "width": 100, "height": 100})).unwrap(); + s.execute("artboard.new", &json!({"x": 60, "y": 0, "width": 100, "height": 100})).unwrap(); + let sq = s.execute("shape.rectangle", &json!({"x": 70, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let p = json!({"indices": [0, 2], "horizontal": "left", "to": "artboard", "artboard": 0}); + assert_eq!(s.execute("artboard.align", &p).unwrap(), json!({"moved": [2]})); + assert_eq!(corners(&s)[2], (0.0, 0.0)); + assert_eq!(corner(&s, sq), (70.0, 10.0), "with artboard 0, which stays"); +} + /// An artboard's own guides move with it. #[test] fn an_artboards_guides_move_with_it() { diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index 243c69f671..291c221756 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -712,15 +712,6 @@ fn same_brush(r: &Relink, ours: &Brush, theirs: &Brush) -> bool { relinked(&Relink::default(), ours) == relinked(r, theirs) } -/// Does brush `b`'s art show symbols or patterns? -fn shows_definitions(b: &Brush) -> bool { - let mut found = false; - for a in b.art() { - node_refs(a, &mut |r| found |= matches!(r, Ref::Name(Res::Symbol | Res::Pattern, _))); - } - found -} - /// A symbol's Symbol Options, which its document keeps by symbol name: copied with the symbol and /// given to it under the name pasting adds it as. #[derive(Clone, Debug, PartialEq)] @@ -754,7 +745,7 @@ impl SymbolOptions { } /// A character or paragraph style, symbol (with the Symbol Options copied with it), pattern or -/// brush (placed with the others only when they are placed in use order) to place +/// brush to place /// ([`Clipboard::import_used`]). #[derive(Clone, Copy)] enum Def<'c> { @@ -1070,49 +1061,40 @@ impl Clipboard { } /// Add the resources the objects use to `d` (inside the paste's undo step) and work out how - /// pasted copies relink to them. An error, with `d` unchanged, when a pasted SVG filter finds no - /// free name ([`Self::filter_links`]). + /// pasted copies relink to them. Each style, symbol, pattern and brush is placed after those it + /// uses, as [`import_text_styles`] places them, so that a style that paints with a pattern added + /// under a free name ("Dots 2") is compared and added with that name. An error, with `d` + /// unchanged, when a pasted SVG filter finds no free name ([`Self::filter_links`]). pub(crate) fn import_into(&self, d: &mut Document, choices: &SwatchChoices, same_doc: bool) -> Result { - self.import_used(d, &self.used(), choices, same_doc, false) + self.import_used(d, &self.used(), choices, same_doc) } - /// [`Self::import_into`] for the resources `used` names. The character and paragraph styles - /// come before the symbols and patterns, whose art may set type in them; with `in_use_order`, - /// each style, symbol, pattern and brush comes after the styles, symbols, patterns and brushes it uses - /// ([`use_order`]), so that it is compared and relinked with their names here, and each loop - /// of definitions that use each other is matched on its own ([`loop_groups`]). - fn import_used(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool, in_use_order: bool) -> Result { + /// [`Self::import_into`] for the resources `used` names. Each style, symbol, pattern and brush + /// comes after the styles, symbols, patterns and brushes it uses ([`use_order`]), so that it is + /// compared and relinked with their names here, and each loop of definitions that use each + /// other is matched on its own ([`loop_groups`]). Pasted back into its own document + /// (`same_doc`), each definition of a loop is the document's of its name. + fn import_used(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool) -> Result { let mut out = Imported::default(); out.relink.filters = self.filter_links(d, same_doc)?; self.import_images(d, used, same_doc, &mut out); self.import_swatches(d, used, choices, same_doc, &mut out); - // Brushes whose art shows no symbols or patterns, before the symbols and patterns whose art - // they may brush; the others once those are in. With `in_use_order`, the brushes are - // placed in use order with the others. - let mut added_brushes: HashSet = - if in_use_order { HashSet::new() } else { self.import_brushes(d, used, same_doc, false, &mut out).into_iter().collect() }; let mut defs: Vec> = vec![]; for (r, list) in [(Res::CharStyle, &self.char_styles), (Res::ParaStyle, &self.para_styles)] { defs.extend(list.iter().filter(|s| used.has(r, &s.name)).map(|s| Def::Style(r, s))); } defs.extend(self.symbols.iter().filter(|s| used.has(Res::Symbol, &s.name)).map(|s| Def::Symbol(s, self.symbol_options.get(&s.name)))); defs.extend(self.patterns.iter().filter(|p| used.has(Res::Pattern, &p.name)).map(Def::Pattern)); - if in_use_order { - defs.extend(self.brushes.iter().filter(|b| used.has(Res::Brush, &b.name)).map(Def::Brush)); - } + defs.extend(self.brushes.iter().filter(|b| used.has(Res::Brush, &b.name)).map(Def::Brush)); // Groups to place in order; true for a loop of definitions that use each other. - let groups: Vec<(Vec>, bool)> = if in_use_order { - let (order, rest) = use_order(defs); - let loops = loop_groups(&rest).into_iter().map(|(at, looped)| (at.into_iter().filter_map(|i| rest.get(i).copied()).collect(), looped)); - std::iter::once((order, false)).chain(loops).collect() - } else { - vec![(defs, false)] - }; - // Styles (their colors relinked first), symbols and patterns (compared once relinked, - // symbols with their options too). The symbols and patterns added are relinked at the end, - // when every new name and graphic style id is known; with `in_use_order`, so are the - // styles added, which a loop of uses may place before a pattern they paint with. - let (mut added_symbols, mut added_patterns, mut added_styles) = (HashSet::new(), HashSet::new(), vec![]); + let (order, rest) = use_order(defs); + let loops = loop_groups(&rest).into_iter().map(|(at, looped)| (at.into_iter().filter_map(|i| rest.get(i).copied()).collect(), looped)); + let groups: Vec<(Vec>, bool)> = std::iter::once((order, false)).chain(loops).collect(); + // Styles (their colors relinked first), symbols, patterns and brushes (compared once + // relinked, symbols with their options too). The styles, symbols, patterns and brushes + // added are relinked at the end, when every new name and graphic style id is known: a loop + // of uses may place one before a definition it uses. + let (mut added_symbols, mut added_patterns, mut added_brushes, mut added_styles) = (HashSet::new(), HashSet::new(), HashSet::new(), vec![]); // Each definition, whether it is in a loop, and the loop it starts. let steps = groups .iter() @@ -1122,8 +1104,8 @@ impl Clipboard { let mut fresh = false; // The names in the document of the loop being placed, when it has them all at once. let mut matched: BTreeMap<(Res, String), String> = BTreeMap::new(); - // The document's brush library, read the first time a brush is placed in use order and - // stored again after each brush added; nothing else in the loop changes it. + // The document's brush library, read the first time a brush is placed and stored again + // after each brush added; nothing else in the loop changes it. let mut library: Option> = None; for (def, looped, starts) in steps { fresh &= looped; @@ -1131,8 +1113,9 @@ impl Clipboard { matched.clear(); } // A loop of uses that the document has all at once is known under those names before - // its definitions are compared. - if let Some(group) = starts { + // its definitions are compared. In its own document, each definition is the + // document's of its name, as outside a loop. + if let Some(group) = starts.filter(|_| !same_doc) { matched.clear(); match names_of_loop(d, group, &out.relink) { Some(names) => { @@ -1161,7 +1144,7 @@ impl Clipboard { out.relink.attrs(&mut s.attrs); let theirs = if r == Res::CharStyle { &mut d.char_styles } else { &mut d.para_styles }; let p = place(theirs, &s, same_doc, |a, b| !fresh && a == b); - if in_use_order && let Some(name) = p.new_name(&def.name) { + if let Some(name) = p.new_name(&def.name) { added_styles.push((r, name, def)); } out.placed(r, &def.name, &p); @@ -1215,9 +1198,6 @@ impl Clipboard { } } } - if !in_use_order { - added_brushes.extend(self.import_brushes(d, used, same_doc, true, &mut out)); - } self.import_graphic_styles(d, used, same_doc, &mut out); for (r, name, def) in added_styles { let theirs = if r == Res::CharStyle { &mut d.char_styles } else { &mut d.para_styles }; @@ -1338,28 +1318,6 @@ impl Clipboard { } } - /// The brushes whose art shows symbols or patterns (`late`), or the others: each one the - /// document has (its art compared once relinked) is used, the others are added. → the names of - /// those added, whose art is relinked at the end. - fn import_brushes(&self, d: &mut Document, used: &Used, same_doc: bool, late: bool, out: &mut Imported) -> Vec { - let brushes: Vec<&Brush> = self.brushes.iter().filter(|b| used.has(Res::Brush, &b.name) && shows_definitions(b) == late).collect(); - if brushes.is_empty() { - return vec![]; - } - let mut lib = vectorcraft_brush::library(d); - let mut added = vec![]; - for b in brushes { - let r = &out.relink; - let p = place(&mut lib, b, same_doc, |ours, theirs| same_brush(r, ours, theirs)); - added.extend(p.new_name(&b.name)); - out.placed(Res::Brush, &b.name, &p); - } - if !added.is_empty() { - vectorcraft_brush::store(d, &lib); - } - added - } - /// Global and spot colours (a name conflict merges or adds as `choices` say), then the tint /// swatches of the tints used and the gradient swatches. fn import_swatches(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool, out: &mut Imported) { @@ -1444,7 +1402,7 @@ pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool, let used = Used::of_text_styles(&Defs::of(src, &library), chars, paras); let clip = Clipboard::with_used(src, &used, &library, vec![]); let before = [&d.char_styles, &d.para_styles].map(|l| l.iter().map(|s| s.name.clone()).collect::>()); - let out = clip.import_used(d, &used, &SwatchChoices::default(), false, true)?; + let out = clip.import_used(d, &used, &SwatchChoices::default(), false)?; let mut placed: Vec = vec![]; for (para, r, list) in [(false, Res::CharStyle, &clip.char_styles), (true, Res::ParaStyle, &clip.para_styles)] { for s in list { diff --git a/crates/engine/src/cmd/docinfo.rs b/crates/engine/src/cmd/docinfo.rs index 942b5a0087..833c7d22bf 100644 --- a/crates/engine/src/cmd/docinfo.rs +++ b/crates/engine/src/cmd/docinfo.rs @@ -18,7 +18,7 @@ pub fn specs() -> Vec { "Document Info", ["Window", "Document Info"], None, - "{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient with a stop above opacity 0, at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone", + "{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient with a stop above opacity 0, at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone", has_doc, info ), @@ -627,6 +627,11 @@ fn info(s: &mut Session, p: &Value) -> Result { } }); } + // The document's fonts include those of the type in opacity masks and in the art of its + // symbols and patterns, as Find Font lists them. + if !selection_only { + fonts.extend(super::fonts::art_texts_of(d).into_iter().flat_map(|(_, t, _)| t.runs.iter().map(|r| super::fonts::font_of(&r.style)))); + } let font_names: Vec = fonts.iter().map(super::fonts::font_label).collect(); // Each brush the art uses with its type, found by name in the Brushes panel as the renderer finds it (the last of two // brushes with one name); a brush the panel does not hold draws as a plain stroke and has no type. A row names the type @@ -756,6 +761,40 @@ mod tests { assert!(i["objects"]["textObjects"].is_null() && i["objects"]["paths"] == 1); } + /// Document Info's fonts include the type in an opacity mask, in a symbol's art and in a + /// pattern swatch that nothing paints with; with `selectionOnly`, only the selected type's. + #[test] + fn info_fonts_include_masks_symbols_and_patterns() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let id = |v: Value| NodeId(v["id"].as_u64().unwrap()); + let text = |s: &mut Session, font: &str| id(s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": font})).unwrap()); + let rect = |s: &mut Session| id(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()); + let (masked, in_symbol) = (rect(&mut s), rect(&mut s)); + for (owner, font) in [(masked, "Mask Family"), (in_symbol, "Symbol Mask Family")] { + let t = text(&mut s, font); + s.edit("Mask", |d, _| { + let art = d.remove(t)?; + d.node_mut(owner).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true))); + Ok(()) + }) + .unwrap(); + } + s.execute("symbol.new", &json!({"name": "Mark", "ids": [in_symbol.0]})).unwrap(); + let t = text(&mut s, "Pattern Family"); + s.execute("object.pattern.make", &json!({"ids": [t.0], "name": "Unused", "edit": false})).unwrap(); + s.execute("select.set", &json!({"ids": [t.0]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let plain = text(&mut s, "Source Sans 3"); + let fonts = |s: &mut Session, p: Value| s.execute("document.info", &p).unwrap()["fonts"].clone(); + assert_eq!( + fonts(&mut s, json!({})), + json!(["Mask Family Regular", "Pattern Family Regular", "Source Sans 3 Regular", "Symbol Mask Family Regular"]) + ); + s.execute("select.set", &json!({"ids": [plain.0]})).unwrap(); + assert_eq!(fonts(&mut s, json!({"selectionOnly": true})), json!(["Source Sans 3 Regular"])); + } + /// Document Info › Objects gives the paths' total length in the document's units (#1958): an /// open line, a closed rectangle's perimeter and a compound path's pieces count, a guide doesn't. #[test] @@ -1379,6 +1418,43 @@ mod tests { assert_eq!(i["objects"]["spots"].as_u64(), Some(1), "{}", i["objects"]); } + /// Spot Color Objects leaves out a fill or stroke at an opacity of 0, which prints no ink, and + /// keeps the object while another of its fills or strokes prints the spot color. Gradient + /// Objects leaves out a clear gradient fill as well. + #[test] + fn spot_color_objects_skip_clear_fills_and_strokes() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap(); + let rect = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone(); + s.execute("paint.setFill", &json!({"ids": [rect], "swatch": "Ink"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [rect], "swatch": "Ink"})).unwrap(); + let ramp = s.execute("shape.rectangle", &json!({"x": 50, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone(); + let stops = json!([{"offset": 0, "color": "#000", "swatch": "Ink"}, {"offset": 1, "color": "#fff", "swatch": "Ink"}]); + s.execute("paint.setFill", &json!({"ids": [ramp], "gradient": {"kind": "linear", "stops": stops}})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [ramp], "none": true})).unwrap(); + let items = |s: &Session, id: &Value| s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().appearance.items.clone(); + let spots = |s: &mut Session| { + let i = s.execute("document.info", &json!({})).unwrap(); + let mut ids: Vec = i["spotObjects"].as_array().unwrap().iter().map(|o| o["id"].as_u64().unwrap()).collect(); + ids.sort_unstable(); + (ids, i["objects"]["spots"].as_u64(), i["objects"]["gradients"].as_u64()) + }; + // The rectangle's fill at an opacity of 0: its stroke still prints the spot color. + s.execute("select.set", &json!({"ids": [rect]})).unwrap(); + let fill = items(&s, &rect).iter().position(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap(); + s.execute("appearance.setItem", &json!({"index": fill, "opacity": 0})).unwrap(); + assert_eq!(spots(&mut s), (vec![rect.as_u64().unwrap(), ramp.as_u64().unwrap()], Some(2), Some(1))); + // Every fill and stroke of both objects at an opacity of 0. + for id in [&rect, &ramp] { + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + for index in 0..items(&s, id).len() { + s.execute("appearance.setItem", &json!({"index": index, "opacity": 0})).unwrap(); + } + } + assert_eq!(spots(&mut s), (vec![], None, None)); + } + /// Document Info › Objects counts an object with a gradient or a pattern on both its fill and /// its stroke once, and with Selection Only a selection that holds a group and an object inside /// it counts that object once. diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 1be80f2c56..31539ff51d 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -408,15 +408,31 @@ pub(crate) fn anti_alias(id: &str) -> std::result::Result { /// The `useArtboards` param of a PDF, AI, DXF or raster export (SVG has its own): `true` writes every /// chosen artboard (default all), `false` the bounds of the visible art instead, absent one -/// artboard (raster, DXF) or the chosen pages (PDF, AI). -fn use_artboards(p: &Value) -> Result> { +/// artboard (raster, DXF) or the chosen pages (PDF, AI). Errors name the command `cmd`. +pub(super) fn use_artboards(cmd: &str, p: &Value) -> Result> { match p.get("useArtboards") { None | Some(Value::Null) => Ok(None), Some(Value::Bool(b)) => Ok(Some(*b)), - Some(v) => Err(bad(C, format!("useArtboards must be true or false, not {v}"))), + Some(v) => Err(bad(cmd, format!("useArtboards must be true or false, not {v}"))), } } +/// With `useArtboards: false` in `p`: `doc` without its opacity-mask or symbol editing layer and +/// with one artboard, the bounds of its visible art, and `p` without the artboard choice. `None` +/// when `useArtboards` is absent, null or true. A document with no visible art is refused. +pub(super) fn art_page(cmd: &str, doc: &Document, p: &Value) -> Result> { + if use_artboards(cmd, p)? != Some(false) { + return Ok(None); + } + let doc = &*doc.without_edit_modes(); + let bounds = vectorcraft_render::encode::art_bounds(doc).ok_or_else(|| bad(cmd, "nothing to export: the document has no visible art"))?; + let mut q = super::export::without_artboards(p); + if let Some(o) = q.as_object_mut() { + o.remove("useArtboards"); + } + Ok(Some((single_artboard(doc, bounds, "Art"), q))) +} + /// The `rect` param of a raster export: `[x, y, width, height]` in points, y down. `None` when /// absent; an error when it is not four finite numbers with a positive size, when the format isn't /// a raster one, or when it comes with an artboard choice (`rect` is the area, so those would @@ -596,7 +612,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result { let doc = &*doc.without_edit_modes(); let n = doc.artboards.len(); // SVG reads its own `useArtboards` (an SVG option). - let use_artboards = if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "emf" | "wmf" | "hpgl") { use_artboards(p)? } else { None }; + let use_artboards = if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "emf" | "wmf" | "hpgl") { use_artboards(C, p)? } else { None }; // `rect`: that area of the page, as if it were the only artboard (the document is not changed). if let Some(rect) = page_rect(f, p)? { let mut q = super::export::without_artboards(p); @@ -606,13 +622,17 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result { } return encode_files(&single_artboard(doc, rect, "Rect"), f, &q); } - if use_artboards == Some(false) { - let bounds = vectorcraft_render::encode::art_bounds(doc).ok_or_else(|| bad(C, "nothing to export: the document has no visible art"))?; - let mut q = super::export::without_artboards(p); - if let Some(o) = q.as_object_mut() { - o.remove("useArtboards"); - } - return encode_files(&single_artboard(doc, bounds, "Art"), f, &q); + // A PDF of the art's bounds carries no editing data (it would replace the artboards). + if use_artboards == Some(false) + && f.id == "pdf" + && let Some((bytes, notes)) = super::pdf::encode_art_page(C, doc, p)? + { + return Ok(Encoded::one_with_notes(bytes, notes)); + } + if use_artboards == Some(false) + && let Some((art, q)) = art_page(C, doc, p)? + { + return encode_files(&art, f, &q); } let bytes = match f.id { "vectorcraft" => super::native::encode(C, f, doc, p)?, diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index d5137c8b1a..3492fd6051 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -782,9 +782,9 @@ pub fn open_extensions() -> &'static [&'static str] { /// File › Open's filters: "All readable files" first, then one per readable format, then one per /// importer plug-in (under its name, with the extensions [`open_extensions`] takes from it), then -/// swatch libraries (which open in the library panel), Libraries panel libraries, flattener, PDF, -/// print and export presets (imported), scripts (checked without running them) and plug-ins -/// (installed). +/// swatch and graphic style libraries (which open in their library panels), Libraries panel +/// libraries, flattener, PDF, print, perspective grid and export presets and composite fonts +/// (imported), shortcut sets, scripts (checked without running them) and plug-ins (installed). pub fn open_filters() -> impl Iterator { let (all, importers) = importer_open_part(); std::iter::once(("All readable files", all)).chain(format_filters()).chain(importers).chain(other_open_filters()) @@ -797,14 +797,17 @@ pub fn builtin_open_filters() -> impl Iterator impl Iterator { std::iter::once(("Swatch libraries", crate::cmd::swatchlib::LIBRARY_EXTS)) + .chain(std::iter::once(("Graphic Style Libraries", std::slice::from_ref(&vectorcraft_doc::style_libs::STYLES_EXT)))) .chain(std::iter::once(("Libraries", crate::cmd::library::LIBRARY_EXTS))) .chain(std::iter::once(("Flattener presets", crate::cmd::flatten::PRESET_EXTS))) .chain(std::iter::once(("PDF presets", crate::cmd::pdfcmds::PRESET_EXTS))) .chain(std::iter::once(("Print presets", crate::cmd::printpresets::PRESET_EXTS))) + .chain(std::iter::once(("Perspective grid presets", crate::cmd::perspgrid::PRESET_EXTS))) .chain(std::iter::once(("Export presets", screens::PRESET_FILE_EXTS))) .chain(std::iter::once(("Composite fonts", crate::cmd::compositefonts::EXTS))) .chain(std::iter::once(("Shortcut sets", crate::cmd::shortcutset::EXTS))) @@ -815,13 +818,13 @@ fn other_open_filters() -> impl Iterator impl Iterator { - std::iter::once((library_label, library_exts)).chain(builtin_open_filters()) + std::iter::once((library_label, library_exts)).chain(builtin_open_filters().filter(move |f| *f != (library_label, library_exts))) } /// File → Place dialog filters: "All placeable files", then one per placeable format, then text, diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index b11251ba34..acc22c7876 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "Export PDF", [], None, - "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: false (true: such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", + "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art, as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: false (true: such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", has_doc, export_pdf ), @@ -137,7 +137,7 @@ pub fn specs() -> Vec { "PDF Settings", [], None, - "{preset?, includeDocument?: false, …options of document.exportPdf} → {settings (the preset with the options applied), presets: [name…], changed: [{option: \"compression.compressText\", value}] (what differs from the preset), warnings}; includeDocument also exports the active document in memory and adds its warnings (knockout groups approximated, effects left out…). A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", + "{preset?, includeDocument?: false, …options of document.exportPdf} → {settings (the preset with the options applied), presets: [name…], changed: [{option: \"compression.compressText\", value}] (what differs from the preset), warnings}; includeDocument also exports the active document in memory (one page of the art's bounds with useArtboards: false) and adds its warnings (knockout groups approximated, effects left out…). A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", always, pdf_settings ), @@ -280,6 +280,27 @@ fn options_at(cmd: &str, doc: &Document, p: &Value, now: Option) -> Result< pub const EDITING_NEEDS_EVERY_ARTBOARD: &str = "Preserve editing was left out: it needs a PDF of every artboard, in order (reopened, this one would show the others too)"; +/// Why a PDF of the art's bounds (`useArtboards: false`) carries no editing data. +pub const EDITING_NEEDS_THE_ARTBOARDS: &str = + "Preserve editing was left out: it needs a PDF of the artboards (reopened, this one would replace them with one artboard around the art)"; + +/// With `useArtboards: false` in `p`: the PDF of one page, the bounds of `doc`'s visible art +/// ([`super::encode::art_page`]) → (bytes, notes). It carries no editing data: with Preserve +/// Editing on, the notes end with [`EDITING_NEEDS_THE_ARTBOARDS`]. `None` when `p` asks for the +/// artboards. +pub(super) fn encode_art_page(cmd: &str, doc: &Document, p: &Value) -> Result, Vec)>> { + let Some((art, mut q)) = super::encode::art_page(cmd, doc, p)? else { return Ok(None) }; + let left_out = settings(cmd, &q)?.preserve_editing; + if left_out && let Some(o) = q.as_object_mut() { + o.insert("preserveEditing".into(), json!(false)); + } + let (bytes, mut notes) = encode(cmd, &art, &q)?; + if left_out { + notes.push(Note::setting(EDITING_NEEDS_THE_ARTBOARDS)); + } + Ok(Some((bytes, notes))) +} + /// The warning for a PDF/X file that leaves out the document's bleed /// ([`vectorcraft_pdf::PdfSettings::leaves_out_bleed`]). pub const BLEED_LEFT_OUT: &str = "the document sets a bleed that this PDF/X file leaves out: turn on Use document bleed settings"; @@ -482,7 +503,12 @@ fn export_pdf(s: &mut Session, p: &Value) -> Result { } else { q = json!({ "_displayDocTitle": display_doc_title }); } - let (bytes, notes) = encode(C, titled.as_ref().unwrap_or(&st.doc), &q)?; + // The opacity-mask or symbol editing layer is left out. + let doc = titled.as_ref().unwrap_or(&st.doc).without_edit_modes(); + let (bytes, notes) = match encode_art_page(C, &doc, &q)? { + Some(encoded) => encoded, + None => encode(C, &doc, &q)?, + }; write_or_return(str_param(p, "path"), &bytes, json!({ "warnings": note_texts(¬es) })) } @@ -513,9 +539,18 @@ fn pdf_settings(s: &mut Session, p: &Value) -> Result { const Q: &str = "document.pdfSettings"; let saved = &s.prefs.pdf_presets; let set = settings_with(Q, p, saved)?; + super::encode::use_artboards(Q, p)?; let diff = changes(&set, &preset_settings(Q, p, saved)?); let warnings = match s.active() { - Some(st) if bool_or(p, "includeDocument", false) => note_texts(&encode(Q, &st.doc, &*expand_preset(s, Q, p)?)?.1), + Some(st) if bool_or(p, "includeDocument", false) => { + let q = expand_preset(s, Q, p)?; + let doc = st.doc.without_edit_modes(); + let (_, notes) = match encode_art_page(Q, &doc, &q)? { + Some(encoded) => encoded, + None => encode(Q, &doc, &q)?, + }; + note_texts(¬es) + } _ => set.warnings(), }; let v = serde_json::to_value(&set).map_err(|e| EngineError::Other(e.to_string()))?; diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index 5ea57858cc..18bb4853b1 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -390,9 +390,20 @@ fn open_exts_cover_every_readable_format() { assert_eq!(filters[0], ("All readable files", OPEN_EXTS)); assert_eq!( filters.len(), - 11 + FORMATS.iter().filter(|f| f.read).count(), - "and swatch libraries, libraries, flattener, PDF, print and export presets, composite fonts, shortcut sets, scripts, plug-ins" + 13 + FORMATS.iter().filter(|f| f.read).count(), + "and swatch and graphic style libraries, libraries, flattener, PDF, print, perspective grid and export presets, composite \ + fonts, shortcut sets, scripts, plug-ins" ); + let at = |label: &str| filters.iter().position(|f| f.0 == label).unwrap_or_else(|| panic!("File › Open has no {label} filter")); + let styles: &[&str] = &[vectorcraft_doc::style_libs::STYLES_EXT]; + assert_eq!(filters[at("Graphic Style Libraries")].1, styles, "File › Open opens graphic style libraries"); + assert_eq!(at("Graphic Style Libraries"), at("Swatch libraries") + 1, "next to the swatch libraries"); + assert_eq!(filters[at("Perspective grid presets")].1, crate::cmd::perspgrid::PRESET_EXTS, "File › Open imports perspective grid presets"); + assert_eq!(at("Perspective grid presets"), at("Print presets") + 1, "among the presets"); + assert_eq!(at("Export presets"), at("Perspective grid presets") + 1, "among the presets"); + for e in [vectorcraft_doc::style_libs::STYLES_EXT].iter().chain(crate::cmd::perspgrid::PRESET_EXTS) { + assert!(!filters[0].1.contains(e), "All readable files lists documents only, not .{e}"); + } assert!(filters.contains(&("Export presets", SCREEN_EXPORT_PRESET_EXTS)), "File › Open imports export presets"); assert!(filters.contains(&("Scripts", crate::cmd::scripts::EXTS)), "File › Open checks scripts"); assert_eq!(filters.last(), Some(&("Plug-ins", crate::cmd::plugin::EXTS)), "File › Open installs plug-ins"); @@ -404,6 +415,11 @@ fn library_open_filters_list_library_formats_first() { assert_eq!(filters[0], ("Swatch libraries", crate::cmd::swatchlib::LIBRARY_EXTS)); assert!(filters[0].1.contains(&"ase")); assert_eq!(filters[1], ("All readable files", OPEN_EXTS)); + let styles: &'static [&'static str] = std::slice::from_ref(&vectorcraft_doc::style_libs::STYLES_EXT); + for (label, exts) in [("Swatch libraries", crate::cmd::swatchlib::LIBRARY_EXTS), ("Graphic Style Libraries", styles)] { + let filters: Vec<_> = library_open_filters(label, exts).collect(); + assert_eq!(filters.iter().filter(|f| f.0 == label).count(), 1, "{label} is listed once"); + } } /// The extensions usage texts list for export: one per writable format, each picking that format diff --git a/crates/engine/src/cmd/fileio/tests_pdf.rs b/crates/engine/src/cmd/fileio/tests_pdf.rs index 6f47307290..91fe9701e7 100644 --- a/crates/engine/src/cmd/fileio/tests_pdf.rs +++ b/crates/engine/src/cmd/fileio/tests_pdf.rs @@ -56,6 +56,126 @@ fn export_pdf_writes_the_compatibility_header_and_the_range() { assert!(b64(&v).starts_with(b"%PDF-1.6")); } +/// `useArtboards: false` writes one page, the bounds of the visible art, as `document.export` +/// does, whatever artboards are chosen. Art longer than 200 in keeps its size with +/// `longPagesInPoints`. A document with no visible art and a value that isn't a boolean are +/// refused. +#[test] +fn use_artboards_false_writes_one_page_of_the_arts_bounds() { + let mut s = session(3); + let page = |bytes: &[u8]| { + let d = vectorcraft_pdf::import(bytes).unwrap(); + (d.artboards.len(), d.artboards[0].rect.size()) + }; + let through_export = page(&b64(&s.execute("document.export", &as_export(&json!({"useArtboards": false}))).unwrap())); + assert!(through_export.0 == 1 && through_export.1.width < 50.0 && through_export.1.height < 40.0, "{through_export:?}"); + for p in [ + json!({"useArtboards": false}), + json!({"useArtboards": false, "range": "2"}), + json!({"useArtboards": false, "artboards": [0, 1]}), + json!({"useArtboards": false, "artboard": 2}), + ] { + assert_eq!(page(&b64(&export(&mut s, p.clone()))), through_export, "{p}"); + } + assert_eq!(pages(&b64(&export(&mut s, json!({"useArtboards": true})))), 3); + assert_eq!(pages(&b64(&export(&mut s, json!({"useArtboards": null})))), 3); + + // A 10 m drawing on a small artboard: its page is 10 m long, in points. + s.execute("shape.rectangle", &json!({"x": 0, "y": 200, "width": 28_346.46, "height": 100})).unwrap(); + let v = export(&mut s, json!({"useArtboards": false, "longPagesInPoints": true})); + let pdf = b64(&v); + let (n, size) = page(&pdf); + assert!(n == 1 && size.width > 28_346.0 && size.width < 28_350.0, "{size:?}"); + assert!(!String::from_utf8_lossy(&pdf).contains("/UserUnit")); + assert!(warnings(&v).iter().any(|w| w.contains("written without a UserUnit, in points")), "{v}"); + // The Summary's export in memory writes the same page. + let mut long = |p: Value| warnings(&s.execute("document.pdfSettings", &p).unwrap()).iter().any(|w| w.contains("longer than PDF's page limit")); + assert!(long(json!({"includeDocument": true, "useArtboards": false}))); + assert!(!long(json!({"includeDocument": true})), "the artboards are small"); + let e = s.execute("document.pdfSettings", &json!({"useArtboards": "no"})).unwrap_err(); + assert!(matches!(e, crate::EngineError::BadParams { .. }), "without includeDocument too: {e}"); + + s.execute("select.all", &json!({})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + for p in [json!({"useArtboards": false}), json!({"useArtboards": "no"})] { + let e = s.execute("document.exportPdf", &p).unwrap_err(); + assert!(matches!(e, crate::EngineError::BadParams { .. }), "{p}: {e}"); + } +} + +/// A PDF of the art's bounds carries no Preserve Editing data, through `document.exportPdf`, +/// `document.export` and the Summary's export in memory, and says so in a warning: reopened, its +/// editing data would replace the document's artboards with the one around the art. A PDF of the +/// artboards keeps the data, and it reopens with every artboard. With Preserve Editing off, there +/// is no warning. +#[test] +fn a_pdf_of_the_arts_bounds_carries_no_editing_data() { + let mut s = session(3); + let left_out = |v: &Value| warnings(v).iter().any(|w| w == super::pdf::EDITING_NEEDS_THE_ARTBOARDS); + let art = json!({"useArtboards": false}); + for v in [export(&mut s, art.clone()), s.execute("document.export", &as_export(&art)).unwrap()] { + let pdf = b64(&v); + assert!(vectorcraft_pdf::editing(&pdf).is_none(), "{:?}", warnings(&v)); + assert!(left_out(&v), "{:?}", warnings(&v)); + assert_eq!(pages(&pdf), 1); + } + let summary = s.execute("document.pdfSettings", &json!({"includeDocument": true, "useArtboards": false})).unwrap(); + assert!(left_out(&summary), "{summary}"); + let quiet = export(&mut s, json!({"useArtboards": false, "preserveEditing": false})); + assert!(!left_out(&quiet), "{:?}", warnings(&quiet)); + + for v in [export(&mut s, json!({})), export(&mut s, json!({"useArtboards": true}))] { + let editing = vectorcraft_pdf::editing(&b64(&v)).expect("editing data"); + let reopened = vectorcraft_format::load(&editing.data).unwrap(); + assert_eq!(reopened.artboards.len(), 3); + assert!(!left_out(&v), "{:?}", warnings(&v)); + } +} + +/// While an opacity mask is edited, a PDF of the art's bounds measures the art without the +/// editing layer, as `document.export` does: a mask shape drawn past the masked object doesn't +/// widen the page. +#[test] +fn a_pdf_of_the_art_leaves_out_the_mask_editing_layer() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); + let obj = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 200, "height": 200})).unwrap()["id"].clone(); + let mask = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 200})).unwrap()["id"].clone(); + s.execute("paint.setFill", &json!({"color": "#ffffff", "ids": [mask]})).unwrap(); + s.execute("select.set", &json!({"ids": [obj, mask]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + s.execute("transparency.editOpacityMask", &json!({})).unwrap(); + s.execute("shape.ellipse", &json!({"x": 250, "y": 250, "width": 40, "height": 40})).unwrap(); + assert!(s.doc().unwrap().doc.mask_edit.is_some()); + let width = |bytes: &[u8]| vectorcraft_pdf::import(bytes).unwrap().artboards[0].rect.width(); + let through_export = width(&b64(&s.execute("document.export", &as_export(&json!({"useArtboards": false}))).unwrap())); + assert!(through_export < 250.0, "{through_export}"); + assert_eq!(width(&b64(&export(&mut s, json!({"useArtboards": false})))), through_export); +} + +/// While an opacity mask is edited, a PDF of the artboards leaves out the editing layer too, as +/// `document.export` does: from the drawn page and from the Preserve Editing data. +#[test] +fn a_pdf_of_the_artboards_leaves_out_the_mask_editing_layer() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); + let obj = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 200, "height": 200})).unwrap()["id"].clone(); + let mask = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 200})).unwrap()["id"].clone(); + s.execute("paint.setFill", &json!({"color": "#ffffff", "ids": [mask]})).unwrap(); + s.execute("select.set", &json!({"ids": [obj, mask]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + s.execute("transparency.editOpacityMask", &json!({})).unwrap(); + s.execute("shape.ellipse", &json!({"x": 250, "y": 250, "width": 40, "height": 40})).unwrap(); + assert!(s.doc().unwrap().doc.mask_edit.is_some()); + let nodes = |bytes: &[u8]| vectorcraft_pdf::import(bytes).unwrap().node_count(); + let plain = json!({"preserveEditing": false}); + let through_export = nodes(&b64(&s.execute("document.export", &as_export(&plain)).unwrap())); + assert_eq!(nodes(&b64(&export(&mut s, plain))), through_export, "the drawn page"); + let layers = |v: &Value| vectorcraft_format::load(&vectorcraft_pdf::editing(&b64(v)).unwrap().data).unwrap().layers; + let through_export = layers(&s.execute("document.export", &as_export(&json!({}))).unwrap()); + assert_eq!(layers(&export(&mut s, json!({}))), through_export, "the Preserve Editing data"); +} + #[test] fn bad_options_are_refused() { let mut s = session(2); diff --git a/crates/engine/src/cmd/fontfiles.rs b/crates/engine/src/cmd/fontfiles.rs index 0ccf1ab94a..fde85dd92d 100644 --- a/crates/engine/src/cmd/fontfiles.rs +++ b/crates/engine/src/cmd/fontfiles.rs @@ -67,7 +67,7 @@ pub fn specs() -> Vec { "Missing Fonts", [], None, - "{} → {fonts: [{family, style, status: missing|substitute, resolved: {family, style}}] (sorted by name; at most 1000), count, fontsNextToDocument?} the fonts the active document's type uses, in its layers and its symbols (for type in a composite font, the fonts of the parts its characters are drawn in), that aren't available as named: missing (the family is unknown and the fallback family stands in) or substitute (the family is there but not the style; resolved names the stand-in), as text.fonts says. CSS generic families such as sans-serif and names longer than 256 bytes are left out. fontsNextToDocument: the Fonts folder next to the saved document (File › Package writes it), when there is one and a search may start there (not in another app's folders, such as a mail app's attachments)", + "{} → {fonts: [{family, style, status: missing|substitute, resolved: {family, style}}] (sorted by name; at most 1000), count, fontsNextToDocument?} the fonts the active document's type uses, in its layers, its symbols and its patterns, opacity masks included (for type in a composite font, the fonts of the parts its characters are drawn in), that aren't available as named: missing (the family is unknown and the fallback family stands in) or substitute (the family is there but not the style; resolved names the stand-in), as text.fonts says. CSS generic families such as sans-serif and names longer than 256 bytes are left out. fontsNextToDocument: the Fonts folder next to the saved document (File › Package writes it), when there is one and a search may start there (not in another app's folders, such as a mail app's attachments)", has_doc, missing ), @@ -103,7 +103,7 @@ pub struct MissingFont { pub resolved: Option<(String, String)>, } -/// The fonts the type of `d` uses, in its layers and its symbols (a composite font's parts, those +/// The fonts the type of `d` uses, in its layers, symbols and patterns, opacity masks included (a composite font's parts, those /// its characters are drawn in, in place of its name), that aren't available as named (sorted by family and style, each once whatever version its type names; at most 1000). CSS generic families such as `sans-serif` /// ([`GENERIC_FAMILIES`]) and names longer than 256 bytes are left out. pub fn missing_fonts(d: &Document) -> Vec { diff --git a/crates/engine/src/cmd/fonts.rs b/crates/engine/src/cmd/fonts.rs index 2a6d1cb0df..74cece5af3 100644 --- a/crates/engine/src/cmd/fonts.rs +++ b/crates/engine/src/cmd/fonts.rs @@ -21,7 +21,7 @@ pub fn specs() -> Vec { "Fonts in Document", [], None, - "{selectionOnly?} (the type in the art of the symbols in scope included: all of the document's, or those the selected instances show) → [{family, style, runs, objects, missing, status: exact|substitute|missing, resolved: {family, style}, missingGlyphs, version?: the installed version the type names (when it names one)}] sorted by name. A font is found by any of its names (ヒラギノ角ゴシック = Hiragino Sans) among the loaded and installed fonts; substitute: the family is there but not the style (resolved names the stand-in); missing: the family is unknown (the fallback family stands in); missingGlyphs: characters of its text the resolved font lacks (drawn by a fallback font). For a composite font, status is the worst among the parts its characters are drawn in, and missingGlyphs counts the characters their part's font lacks", + "{selectionOnly?} (the type in the opacity masks of the objects in scope and in the art of the symbols and patterns in scope included: all of the document's, a pattern swatch that nothing paints included, or those the selected objects show through their instances and paints; disabled masks too) → [{family, style, runs, objects, missing, status: exact|substitute|missing, resolved: {family, style}, missingGlyphs, version?: the installed version the type names (when it names one)}] sorted by name. A font is found by any of its names (ヒラギノ角ゴシック = Hiragino Sans) among the loaded and installed fonts; substitute: the family is there but not the style (resolved names the stand-in); missing: the family is unknown (the fallback family stands in); missingGlyphs: characters of its text the resolved font lacks (drawn by a fallback font). For a composite font, status is the worst among the parts its characters are drawn in, and missingGlyphs counts the characters their part's font lacks", has_doc, fonts ), @@ -30,7 +30,7 @@ pub fn specs() -> Vec { "Replace Font", [], None, - "{from: {family, style?}, to: {family (any of its names; stored as the font's own family name, a composite font's as its own name), style?}, selectionOnly?} (style omitted: every style of the family / keep the closest style); the type in the art of the symbols in scope changes too (all of the document's, or those the selected instances show, so every instance of them follows); text that is hidden or locked, in a hidden or locked group or layer (or group of a symbol's art), or on a locked artboard keeps its font; when no run changes (text already set in the new font, or none to change), the document and its undo history stay as they are → {runs: the runs changed, skipped?: the text objects left in the font, warning?: text (some text was left in its font, or the style set isn't available: its type is drawn in the family's closest style)}", + "{from: {family, style?}, to: {family (any of its names; stored as the font's own family name, a composite font's as its own name), style?}, selectionOnly?} (style omitted: every style of the family / keep the closest style); the type in the opacity masks of the objects in scope (disabled masks too) and in the art of the symbols and patterns in scope changes too (all of the document's, or those the selected objects show through their instances and paints, so every instance of a symbol and every object a pattern paints follows); text that is hidden or locked, in a hidden or locked group or layer (or group of a symbol's, pattern's or mask's art), in the mask of a hidden or locked object, or on a locked artboard keeps its font; when no run changes (text already set in the new font, or none to change), the document and its undo history stay as they are → {runs: the runs changed, skipped?: the text objects left in the font, warning?: text (some text was left in its font, or the style set isn't available: its type is drawn in the family's closest style)}", has_doc, replace ), @@ -39,7 +39,7 @@ pub fn specs() -> Vec { "Select Text by Font", [], None, - "{family, style?, scope?: \"document\" (default) | {artboards: [index, …] (0-based)} | {layers: [id, …] (layers or sublayers)}} select the text objects using the font, and the instances of the symbols whose art uses it, that are not hidden or locked, in a hidden or locked group or layer, or on a locked artboard; with scope, only those on one of the artboards (as All on Active Artboard takes them: their bounds overlap it or their center is on it) or in one of the layers → {count}", + "{family, style?, scope?: \"document\" (default) | {artboards: [index, …] (0-based)} | {layers: [id, …] (layers or sublayers)}} select the text objects using the font, the instances of the symbols whose art uses it, the objects painted with a pattern whose art uses it and the objects whose opacity mask uses it (in type that is not hidden or locked in that art), that are not hidden or locked, in a hidden or locked group or layer, or on a locked artboard; a pattern swatch that nothing paints, or a layer's mask, selects nothing; with scope, only those on one of the artboards (as All on Active Artboard takes them: their bounds overlap it or their center is on it) or in one of the layers → {count}", has_doc, select_font ), @@ -64,15 +64,23 @@ pub fn specs() -> Vec { ] } -/// Text objects in scope: the selection's (and their descendants') or the whole document's. -fn scope(s: &Session, selection_only: bool, selected: Option<&[NodeId]>) -> Result> { +/// Text objects in scope: the selection's (and their descendants') or the whole document's, and +/// the objects among them that have an opacity mask (not the object whose mask is being edited: +/// its art is on the editing layer). +fn scope(s: &Session, selection_only: bool, selected: Option<&[NodeId]>) -> Result<(Vec, Vec)> { let st = s.doc()?; - let mut v = vec![]; + let editing = st.doc.mask_edit.map(|m| m.object); + let (mut texts, mut masked) = (vec![], vec![]); let mut seen = HashSet::new(); let mut add = |n: &vectorcraft_doc::Node| { n.walk(&mut |c| { - if matches!(c.kind, NodeKind::Text(_)) && seen.insert(c.id) { - v.push(c.id); + if seen.insert(c.id) { + if matches!(c.kind, NodeKind::Text(_)) { + texts.push(c.id); + } + if c.extras().mask.is_some() && Some(c.id) != editing { + masked.push(c.id); + } } }) }; @@ -87,7 +95,7 @@ fn scope(s: &Session, selection_only: bool, selected: Option<&[NodeId]>) -> Resu add(l); } } - Ok(v) + Ok((texts, masked)) } /// Whether `name` is the symbol being edited, whose art is on the editing layer. @@ -95,106 +103,269 @@ fn being_edited(d: &Document, name: &str) -> bool { d.symbol_edit.as_ref().is_some_and(|e| e.symbol == name) } -/// The symbols that the selected objects of `s` show: those of the instances among them and their -/// descendants, and of the instances in those symbols' art that are not hidden or locked, nor in a -/// hidden or locked group of the art. Returned as (all of them, those shown by instances the -/// Selection tool can reach: not hidden or locked, as `Document::editable` says). -fn selected_symbols(s: &Session, selected: Option<&[NodeId]>) -> Result<(BTreeSet, BTreeSet)> { - fn open_instances(n: &Node, out: &mut BTreeSet) { +/// Whether `name` is the pattern being edited, whose tile art is on the editing layer. +fn pattern_being_edited(d: &Document, name: &str) -> bool { + d.pattern_edit.as_ref().is_some_and(|e| e.pattern == name) +} + +/// The patterns that the fills and strokes `n` draws name (of a text object, also those of its +/// characters): visible ones, and strokes wider than 0. +fn paint_patterns(n: &Node) -> impl Iterator { + let runs = match &n.kind { + NodeKind::Text(t) => t.runs.as_slice(), + _ => &[], + }; + n.appearance + .items + .iter() + .filter(|i| i.visible() && !matches!(i, AppearanceItem::Stroke(s) if s.width <= 0.0)) + .map(AppearanceItem::paint) + .chain(runs.iter().flat_map(|r| [Some(&r.style.fill), (r.style.stroke_width > 0.0).then_some(&r.style.stroke)]).flatten()) + .filter_map(|p| match p { + Paint::Pattern { pattern, .. } => Some(pattern.as_str()), + _ => None, + }) +} + +/// Symbols and patterns, by name: those whose art is in scope. +#[derive(Clone, Debug, Default)] +struct Resources { + symbols: BTreeSet, + patterns: BTreeSet, +} + +impl Resources { + /// Adds what `n` itself shows: the symbol of an instance, the patterns its paints name, and + /// what the art of its opacity mask shows (not hidden or locked objects of that art). + fn add_own(&mut self, n: &Node) { + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind { + self.symbols.insert(symbol.clone()); + } + self.patterns.extend(paint_patterns(n).map(str::to_string)); + if let Some(m) = n.extras().mask.as_deref() { + self.add(&m.art); + } + } + + /// Adds what `n` and its descendants show, leaving out hidden or locked objects and what they + /// hold. + fn add(&mut self, n: &Node) { if !n.visible || n.locked { return; } - if let NodeKind::SymbolInstance { symbol, .. } = &n.kind { - out.insert(symbol.clone()); - } + self.add_own(n); for c in n.children().map(Vec::as_slice).unwrap_or_default() { - open_instances(c, out); + self.add(c); } } - let expand = |names: &mut BTreeSet, d: &Document| loop { - let mut more = BTreeSet::new(); - for sym in d.symbols.iter().filter(|sym| names.contains(&sym.name)) { - open_instances(&sym.art, &mut more); + + /// Adds what the art of the symbols and patterns named shows, until nothing more is added; each + /// symbol and pattern is read once, so art that shows itself ends. + fn expand(&mut self, d: &Document) { + let mut symbols: Vec = self.symbols.iter().cloned().collect(); + let mut patterns: Vec = self.patterns.iter().cloned().collect(); + while !symbols.is_empty() || !patterns.is_empty() { + let mut more = Resources::default(); + for name in symbols.drain(..) { + if let Some(sym) = d.symbols.iter().find(|sym| sym.name == name) { + more.add(&sym.art); + } + } + for name in patterns.drain(..) { + for art in d.pattern(&name).map(|p| p.art.as_slice()).unwrap_or_default() { + more.add(art); + } + } + symbols.extend(more.symbols.into_iter().filter(|name| self.symbols.insert(name.clone()))); + patterns.extend(more.patterns.into_iter().filter(|name| self.patterns.insert(name.clone()))); } - let before = names.len(); - names.extend(more); - if names.len() == before { - break; + } + + /// The symbols and patterns of `self` that are not in `other`. + fn difference(&self, other: &Self) -> Self { + Self { + symbols: self.symbols.difference(&other.symbols).cloned().collect(), + patterns: self.patterns.difference(&other.patterns).cloned().collect(), } - }; + } +} + +/// The symbols and patterns that the selected objects of `s` show: those of the instances among +/// them and their descendants and the patterns their paints name (also in the art of their +/// opacity masks), and those that the art of these symbols and patterns shows through objects that +/// are not hidden or locked, nor in a hidden or locked group of the art. Returned as (all of them, +/// those shown by objects the Selection tool can reach: not hidden or locked, as +/// `Document::editable` says). +fn selected_art(s: &Session, selected: Option<&[NodeId]>) -> Result<(Resources, Resources)> { let st = s.doc()?; - let (mut all, mut open) = (BTreeSet::new(), BTreeSet::new()); + let (mut all, mut open) = (Resources::default(), Resources::default()); let editable = st.doc.editable(); for id in selected.unwrap_or(&st.selection.objects) { if let Some(n) = st.doc.node(*id) { n.walk(&mut |c| { - if let NodeKind::SymbolInstance { symbol, .. } = &c.kind { - all.insert(symbol.clone()); - if editable(c.id) { - open.insert(symbol.clone()); - } + all.add_own(c); + if editable(c.id) { + open.add_own(c); } }); } } drop(editable); - expand(&mut all, &st.doc); - expand(&mut open, &st.doc); + all.expand(&st.doc); + open.expand(&st.doc); Ok((all, open)) } -/// The text objects in the art of `d`'s symbols (with `only`, of those it names), each with -/// whether it is open: neither it nor a group around it in the art is hidden or locked. The symbol -/// being edited is left out: its art is on the editing layer. -pub(super) fn symbol_texts<'a>(d: &'a Document, only: Option<&BTreeSet>) -> Vec<(&'a TextObject, bool)> { - fn visit<'a>(n: &'a Node, open: bool, out: &mut Vec<(&'a TextObject, bool)>) { - let open = open && n.visible && !n.locked; - if let NodeKind::Text(t) = &n.kind { - out.push((&**t, open)); - } - for c in n.children().map(Vec::as_slice).unwrap_or_default() { - visit(c, open, out); - } +/// A text object found in art: its id, the text and whether it is open (neither it nor a group +/// around it, nor an object whose opacity mask holds it, is hidden or locked). +pub(super) type ArtText<'a> = (NodeId, &'a TextObject, bool); + +/// Adds the text objects of `n` and its descendants, the art of their opacity masks included, to +/// `out`; each is open when `open` holds and [`ArtText`] says so. +fn art_texts<'a>(n: &'a Node, open: bool, out: &mut Vec>) { + let open = open && n.visible && !n.locked; + if let NodeKind::Text(t) = &n.kind { + out.push((n.id, &**t, open)); } + if let Some(m) = n.extras().mask.as_deref() { + art_texts(&m.art, open, out); + } + for c in n.children().map(Vec::as_slice).unwrap_or_default() { + art_texts(c, open, out); + } +} + +/// The text objects in the art of the opacity masks of the objects `masked` (each with whether +/// the object is open: when it isn't, none of its mask's text is). +fn mask_texts<'a>(d: &'a Document, masked: &[(NodeId, bool)]) -> Vec> { let mut out = vec![]; - for s in d.symbols.iter().filter(|s| !being_edited(d, &s.name) && only.is_none_or(|o| o.contains(&s.name))) { - visit(&s.art, true, &mut out); + for (id, open) in masked { + if let Some(m) = d.node(*id).and_then(|n| n.extras().mask.as_deref()) { + art_texts(&m.art, *open, &mut out); + } } out } -/// Calls `f` on each text object in the art of `d`'s symbols (with `only`, of those it names) for -/// which `wants(text, open)` holds (open as in [`symbol_texts`]), the symbol being edited left out. -/// Art without such text is left as it is. -pub(super) fn edit_symbol_texts( - d: &mut Document, - only: Option<&BTreeSet>, - wants: &impl Fn(&TextObject, bool) -> bool, - f: &mut impl FnMut(&mut TextObject), -) { - fn wanted(n: &Node, open: bool, wants: &impl Fn(&TextObject, bool) -> bool) -> bool { - let open = open && n.visible && !n.locked; - matches!(&n.kind, NodeKind::Text(t) if wants(t, open)) || n.children().is_some_and(|ch| ch.iter().any(|c| wanted(c, open, wants))) +/// The text objects in the art of `d`'s symbols and patterns (with `only`, of those it names, a +/// pattern's art read once however many objects it paints), opacity masks in that art included. +/// The symbol and the pattern being edited are left out: their art is on the editing layer. +fn resource_texts<'a>(d: &'a Document, only: Option<&Resources>) -> Vec> { + let mut out = vec![]; + for s in d.symbols.iter().filter(|s| !being_edited(d, &s.name) && only.is_none_or(|o| o.symbols.contains(&s.name))) { + art_texts(&s.art, true, &mut out); } - fn visit(n: &mut Node, open: bool, wants: &impl Fn(&TextObject, bool) -> bool, f: &mut impl FnMut(&mut TextObject)) { - let open = open && n.visible && !n.locked; - if let NodeKind::Text(t) = &mut n.kind - && wants(t, open) - { - f(t); + for p in d.patterns.iter().filter(|p| !pattern_being_edited(d, &p.name) && only.is_none_or(|o| o.patterns.contains(&p.name))) { + for art in &p.art { + art_texts(art, true, &mut out); } - for c in n.children_mut().into_iter().flatten() { - if wanted(c, open, wants) { - visit(Arc::make_mut(c), open, wants, f); + } + out +} + +/// The text objects in the art of `d`'s symbols (with `only`, of those it names), as +/// [`resource_texts`] finds them, each with whether it is open. +#[cfg(test)] +pub(super) fn symbol_texts<'a>(d: &'a Document, only: Option<&BTreeSet>) -> Vec<(&'a TextObject, bool)> { + let mut out = vec![]; + for s in d.symbols.iter().filter(|s| !being_edited(d, &s.name) && only.is_none_or(|o| o.contains(&s.name))) { + art_texts(&s.art, true, &mut out); + } + out.into_iter().map(|(_, t, open)| (t, open)).collect() +} + +/// Whether `n` or a descendant (the art of their opacity masks included) holds a text object for +/// which `wants(text, open)` holds, open as [`ArtText`] says. +fn wanted(n: &Node, open: bool, wants: &impl Fn(&TextObject, bool) -> bool) -> bool { + let open = open && n.visible && !n.locked; + matches!(&n.kind, NodeKind::Text(t) if wants(t, open)) + || n.extras().mask.as_deref().is_some_and(|m| wanted(&m.art, open, wants)) + || n.children().is_some_and(|ch| ch.iter().any(|c| wanted(c, open, wants))) +} + +/// Calls `f` on each text object of `n` and its descendants (the art of their opacity masks +/// included) for which `wants(text, open)` holds; only the nodes on the way to such text are +/// copied. +fn edit_art(n: &mut Node, open: bool, wants: &impl Fn(&TextObject, bool) -> bool, f: &mut impl FnMut(&mut TextObject)) { + let open = open && n.visible && !n.locked; + if let NodeKind::Text(t) = &mut n.kind + && wants(t, open) + { + f(t); + } + if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) + && wanted(&m.art, open, wants) + { + edit_art(Arc::make_mut(&mut m.art), open, wants, f); + } + for c in n.children_mut().into_iter().flatten() { + if wanted(c, open, wants) { + edit_art(Arc::make_mut(c), open, wants, f); + } + } +} + +/// Calls `f` on each text object in the opacity masks of the objects `masked` (as [`mask_texts`] +/// finds them) for which `wants(text, open)` holds. Masks without such text are left as they are. +fn edit_mask_texts(d: &mut Document, masked: &[(NodeId, bool)], wants: &impl Fn(&TextObject, bool) -> bool, f: &mut impl FnMut(&mut TextObject)) { + for (id, open) in masked { + if d.node(*id).and_then(|n| n.extras().mask.as_deref()).is_some_and(|m| wanted(&m.art, *open, wants)) + && let Some(m) = d.node_mut(*id).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_mut()) + { + edit_art(Arc::make_mut(&mut m.art), *open, wants, f); + } + } +} + +/// Calls `f` on each text object in the art of `d`'s symbols and patterns (as [`resource_texts`] +/// finds them) for which `wants(text, open)` holds. Art without such text is left as it is. +fn edit_resource_texts(d: &mut Document, only: Option<&Resources>, wants: &impl Fn(&TextObject, bool) -> bool, f: &mut impl FnMut(&mut TextObject)) { + let symbol = d.symbol_edit.as_ref().map(|e| e.symbol.clone()); + let pattern = d.pattern_edit.as_ref().map(|e| e.pattern.clone()); + for s in &mut d.symbols { + if symbol.as_ref() != Some(&s.name) && only.is_none_or(|o| o.symbols.contains(&s.name)) && wanted(&s.art, true, wants) { + edit_art(Arc::make_mut(&mut s.art), true, wants, f); + } + } + for p in &mut d.patterns { + if pattern.as_ref() != Some(&p.name) && only.is_none_or(|o| o.patterns.contains(&p.name)) { + for art in &mut p.art { + if wanted(art, true, wants) { + edit_art(Arc::make_mut(art), true, wants, f); + } } } } - let edited = d.symbol_edit.as_ref().map(|e| e.symbol.clone()); - for s in &mut d.symbols { - if edited.as_ref() != Some(&s.name) && only.is_none_or(|o| o.contains(&s.name)) && wanted(&s.art, true, wants) { - visit(Arc::make_mut(&mut s.art), true, wants, f); +} + +/// Every text object of `d` outside the objects of its layers: in the opacity masks of the +/// objects on its layers, and in the art of its symbols and patterns (as [`mask_texts`] and +/// [`resource_texts`] find them, each mask's text open). +pub(super) fn art_texts_of(d: &Document) -> Vec> { + let masked = masked_objects(d); + let mut out = mask_texts(d, &masked); + out.extend(resource_texts(d, None)); + out +} + +/// Calls `f` on each text object of [`art_texts_of`] for which `wants(text)` holds. +pub(super) fn edit_art_texts_of(d: &mut Document, wants: &impl Fn(&TextObject) -> bool, f: &mut impl FnMut(&mut TextObject)) { + let masked = masked_objects(d); + edit_mask_texts(d, &masked, &|t, _| wants(t), f); + edit_resource_texts(d, None, &|t, _| wants(t), f); +} + +/// The objects on the layers of `d` that have an opacity mask (not the object whose mask is being +/// edited), each as open. +fn masked_objects(d: &Document) -> Vec<(NodeId, bool)> { + let editing = d.mask_edit.map(|m| m.object); + let mut out = vec![]; + d.walk(|n| { + if n.extras().mask.is_some() && Some(n.id) != editing { + out.push((n.id, true)); } - } + }); + out } /// A font as type names it: family, style and, when it names one, the installed version. @@ -218,14 +389,16 @@ pub(super) fn run_fonts(r: &TextRun) -> Vec { } } -/// The fonts (family, style, version) the type in the layers and symbols of `d` is drawn in, a -/// composite font's parts in place of its name ([`run_fonts`]). +/// The fonts (family, style, version) the type in the layers, symbols and patterns of `d` is drawn +/// in, the type in opacity masks included, a composite font's parts in place of its name +/// ([`run_fonts`]). pub(super) fn used_fonts(d: &Document) -> BTreeSet { art_fonts(d, &[]) } -/// The fonts (family, style, version) of the type in the layers and symbols of `d` and in `art` -/// (art read from a file, its resources in `d`). +/// The fonts (family, style, version) of the type in the layers, symbols and patterns of `d` and +/// in `art` (art read from a file, its resources in `d`), the type in opacity masks included. The +/// pattern being edited is read from the editing layer only. pub(super) fn art_fonts(d: &Document, art: &[Node]) -> BTreeSet { let mut fonts = BTreeSet::new(); let mut add = |n: &Node| { @@ -233,12 +406,9 @@ pub(super) fn art_fonts(d: &Document, art: &[Node]) -> BTreeSet { fonts.extend(t.runs.iter().flat_map(run_fonts)); } }; - d.walk(&mut add); - for s in &d.symbols { - s.art.walk(&mut add); - } - for n in art { - n.walk(&mut add); + let patterns = d.patterns.iter().filter(|p| !pattern_being_edited(d, &p.name)).flat_map(|p| p.art.iter().map(|a| &**a)); + for n in d.layers.iter().map(|l| &**l).chain(d.symbols.iter().map(|s| &*s.art)).chain(patterns).chain(art) { + vectorcraft_doc::swatches::walk_with_masks(n, &mut add); } fonts } @@ -513,50 +683,78 @@ impl Session { pub fn skipped_font_ids(&self, params: &Value, selected: Option<&[NodeId]>) -> Result> { let (family, style) = font_param(params, "from", "text.replaceFont")?; let selection_only = bool_or(params, "selectionOnly", false); - let selected_symbols = selection_only.then(|| selected_symbols(self, selected)).transpose()?; - let d = &self.doc()?.doc; - let other: Vec = { - let editable = d.editable(); - scope(self, selection_only, selected)?.into_iter().filter(|id| !editable(*id)).collect() - }; + let in_scope = ReplaceScope::read(self, selection_only, selected)?; let uses = |t: &TextObject| { t.runs.iter().any(|r| { r.style.font_family.eq_ignore_ascii_case(&family) && style.as_ref().is_none_or(|name| r.style.font_style.eq_ignore_ascii_case(name)) }) }; - let mut ids = other.into_iter().filter(|id| text(d, *id).is_some_and(uses)).collect::>(); - fn visit(n: &Node, open: bool, closed: bool, uses: &impl Fn(&TextObject) -> bool, ids: &mut Vec) { - let open = open && n.visible && !n.locked; - if let NodeKind::Text(t) = &n.kind - && (!open || closed) - && uses(t) - { - ids.push(n.id); - } - for child in n.children().map(Vec::as_slice).unwrap_or_default() { - visit(child, open, closed, uses, ids); - } + Ok(in_scope.skipped(&self.doc()?.doc, &uses)) + } +} + +/// What Replace Font looks at: the text objects in scope that the Selection tool can reach and +/// those it can't, the objects with an opacity mask (each with whether it can reach them), and the +/// symbols and patterns whose art is in scope (`None`: all of the document's) with those shown +/// only by hidden or locked objects of the selection. +struct ReplaceScope { + ids: Vec, + other: Vec, + masked: Vec<(NodeId, bool)>, + resources: Option, + closed: Resources, +} + +impl ReplaceScope { + fn read(s: &Session, selection_only: bool, selected: Option<&[NodeId]>) -> Result { + // With selectionOnly: the symbols and patterns the selection shows; those shown only by + // hidden or locked objects keep their type, counted in `skipped`. + let (resources, closed) = if selection_only { + let (all, open) = selected_art(s, selected)?; + let closed = all.difference(&open); + (Some(open), closed) + } else { + (None, Resources::default()) + }; + let d = &s.doc()?.doc; + let editable = d.editable(); + let (texts, masked) = scope(s, selection_only, selected)?; + let (ids, other): (Vec, Vec) = texts.into_iter().partition(|id| editable(*id)); + let masked = masked.into_iter().map(|id| (id, editable(id))).collect(); + Ok(Self { ids, other, masked, resources, closed }) + } + + /// The text objects in the art of opacity masks, symbols and patterns in scope. + fn art<'a>(&self, d: &'a Document) -> Vec> { + let mut texts = mask_texts(d, &self.masked); + texts.extend(resource_texts(d, self.resources.as_ref())); + texts + } + + /// The text objects in scope set in a font `uses` matches that Replace Font leaves as they are: + /// those the Selection tool can't reach, hidden or locked text in art, and the text of the + /// symbols and patterns shown only by hidden or locked objects of the selection. + fn skipped(&self, d: &Document, uses: &impl Fn(&TextObject) -> bool) -> Vec { + let mut ids: Vec = self.other.iter().copied().filter(|id| text(d, *id).is_some_and(uses)).collect(); + ids.extend(self.art(d).into_iter().filter(|(_, t, open)| !open && uses(t)).map(|(id, ..)| id)); + if !self.closed.symbols.is_empty() || !self.closed.patterns.is_empty() { + ids.extend(resource_texts(d, Some(&self.closed)).into_iter().filter(|(_, t, _)| uses(t)).map(|(id, ..)| id)); } - for symbol in d - .symbols - .iter() - .filter(|symbol| !being_edited(d, &symbol.name) && selected_symbols.as_ref().is_none_or(|(all, _)| all.contains(&symbol.name))) - { - let closed = selected_symbols.as_ref().is_some_and(|(_, open)| !open.contains(&symbol.name)); - visit(&symbol.art, true, closed, &uses, &mut ids); - } - Ok(ids) + ids } } fn font_inventory(s: &Session, selected: Option<&[NodeId]>) -> Result { - let ids = scope(s, selected.is_some(), selected)?; + let (ids, masked) = scope(s, selected.is_some(), selected)?; let d = &s.doc()?.doc; let db = vectorcraft_text::FontDb::global(); - // The type in the art of the symbols in scope too: all of them, or those the selection shows. - let symbols = if selected.is_some() { Some(selected_symbols(s, selected)?.0) } else { None }; + // The type in the art of the opacity masks of the objects in scope, and of the symbols and + // patterns in scope: all of them, or those the selection shows. + let resources = if selected.is_some() { Some(selected_art(s, selected)?.0) } else { None }; let mut texts: Vec<&TextObject> = ids.iter().filter_map(|id| text(d, *id)).collect(); - texts.extend(symbol_texts(d, symbols.as_ref()).into_iter().map(|(t, _)| t)); + let masked: Vec<(NodeId, bool)> = masked.into_iter().map(|id| (id, true)).collect(); + texts.extend(mask_texts(d, &masked).into_iter().map(|(_, t, _)| t)); + texts.extend(resource_texts(d, resources.as_ref()).into_iter().map(|(_, t, _)| t)); // Each font's runs, objects and the text of its runs. let mut found: BTreeMap)> = BTreeMap::new(); for t in texts { @@ -617,21 +815,6 @@ fn font_param(p: &Value, k: &str, c: &str) -> Result<(String, Option)> { Ok((family.to_string(), v.get("style").and_then(Value::as_str).map(str::to_string))) } -fn skipped_font_texts( - d: &Document, - other: &[NodeId], - symbols: &[(&TextObject, bool)], - closed: &BTreeSet, - uses: &impl Fn(&TextObject) -> bool, -) -> usize { - let mut skipped = other.iter().filter(|id| text(d, **id).is_some_and(uses)).count(); - skipped += symbols.iter().filter(|(t, open)| !open && uses(t)).count(); - if !closed.is_empty() { - skipped += symbol_texts(d, Some(closed)).into_iter().filter(|(t, _)| uses(t)).count(); - } - skipped -} - fn replace(s: &mut Session, p: &Value) -> Result { const C: &str = "text.replaceFont"; let (ff, fs) = font_param(p, "from", C)?; @@ -660,35 +843,25 @@ fn replace(s: &mut Session, p: &Value) -> Result { }; // Only text the Selection tool can reach changes: not hidden or locked, in a hidden or locked // group or layer, or on a locked artboard. The text left in the font is counted. The type in - // the art of the symbols in scope (all of them, or those the selection shows) changes too, - // unless it or a group around it in the art is hidden or locked. + // the opacity masks of the objects in scope, and in the art of the symbols and patterns in + // scope (all of them, or those the selection shows), changes too, unless it, a group around it + // in the art or the object whose mask holds it is hidden or locked. let selection_only = bool_or(p, "selectionOnly", false); - // With selectionOnly: the symbols the selection shows; those shown only by hidden or locked - // instances keep their type, counted in `skipped`. - let (symbols, closed) = if selection_only { - let (all, open) = selected_symbols(s, None)?; - let closed: BTreeSet = all.difference(&open).cloned().collect(); - (Some(open), closed) - } else { - (None, BTreeSet::new()) - }; let uses = |t: &TextObject| t.runs.iter().any(|r| matches(&r.style)); // Whether a run of `t` changes. let changes = |t: &TextObject| t.runs.iter().any(|r| new_style(&r.style).is_some()); - let (ids, skipped, in_symbols) = { + let in_scope = ReplaceScope::read(s, selection_only, None)?; + let (ids, skipped, in_art) = { let d = &s.doc()?.doc; - let editable = d.editable(); - let (ids, other): (Vec, Vec) = scope(s, selection_only, None)?.into_iter().partition(|id| editable(*id)); - let texts = symbol_texts(d, symbols.as_ref()); - let skipped = skipped_font_texts(d, &other, &texts, &closed, &uses); + let skipped = in_scope.skipped(d, &uses).len(); // The text that changes: when none does, the document and its undo history stay as they are. - let ids: Vec = ids.into_iter().filter(|id| text(d, *id).is_some_and(changes)).collect(); - let in_symbols = texts.iter().any(|(t, open)| *open && changes(t)); - (ids, skipped, in_symbols) + let ids: Vec = in_scope.ids.iter().copied().filter(|id| text(d, *id).is_some_and(changes)).collect(); + let in_art = in_scope.art(d).iter().any(|(_, t, open)| *open && changes(t)); + (ids, skipped, in_art) }; // The fonts the replaced runs are set in, for the warning. let mut set = BTreeSet::new(); - let n = if ids.is_empty() && !in_symbols { + let n = if ids.is_empty() && !in_art { 0 } else { s.edit("Replace Font", |d, _| { @@ -717,7 +890,9 @@ fn replace(s: &mut Session, p: &Value) -> Result { replace_in(t); } } - edit_symbol_texts(d, symbols.as_ref(), &|t, open| open && changes(t), &mut replace_in); + let wants = |t: &TextObject, open: bool| open && changes(t); + edit_mask_texts(d, &in_scope.masked, &wants, &mut replace_in); + edit_resource_texts(d, in_scope.resources.as_ref(), &wants, &mut replace_in); Ok(n) })? }; @@ -734,13 +909,26 @@ fn replace(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// Whether `n` or a descendant that is not hidden or locked, nor in a hidden or locked group, +/// shows type in a font `uses` matches: text set in it, an instance of a symbol in `found`, a paint +/// naming a pattern in `found`, or such type in the art of its opacity mask. +fn reaches(n: &Node, uses: &impl Fn(&TextObject) -> bool, found: &Resources) -> bool { + n.visible + && !n.locked + && (matches!(&n.kind, NodeKind::Text(t) if uses(t)) + || matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if found.symbols.contains(symbol)) + || paint_patterns(n).any(|p| found.patterns.contains(p)) + || n.extras().mask.as_deref().is_some_and(|m| reaches(&m.art, uses, found)) + || n.children().is_some_and(|ch| ch.iter().any(|c| reaches(c, uses, found)))) +} + /// What Replace Font says when it left text in the font that it can't reach. const REPLACE_SKIPPED: &str = "some text is hidden or locked, so its font wasn't replaced"; fn select_font(s: &mut Session, p: &Value) -> Result { let family = str_param(p, "family").ok_or_else(|| bad("select.font", "missing `family`"))?.to_string(); let style = str_param(p, "style").map(str::to_string); - let ids = scope(s, false, None)?; + let (ids, masked) = scope(s, false, None)?; let d = &s.doc()?.doc; let within = FontScope::read(d, p)?; // Only text the Selection tool can reach: not hidden or locked, in a hidden or locked group @@ -752,37 +940,40 @@ fn select_font(s: &mut Session, p: &Value) -> Result { .any(|r| r.style.font_family.eq_ignore_ascii_case(&family) && style.as_ref().is_none_or(|x| r.style.font_style.eq_ignore_ascii_case(x))) }; let mut hits: Vec = ids.into_iter().filter(|id| editable(*id) && text(d, *id).is_some_and(uses)).collect(); - // The symbols whose art uses the font in type that is not hidden or locked, nor in a hidden or - // locked group of the art, also through the instances of other symbols it holds. - fn reaches(n: &Node, uses: &impl Fn(&TextObject) -> bool, symbols: &BTreeSet<&str>) -> bool { - n.visible - && !n.locked - && match &n.kind { - NodeKind::Text(t) => uses(t), - NodeKind::SymbolInstance { symbol, .. } => symbols.contains(symbol.as_str()), - _ => n.children().is_some_and(|ch| ch.iter().any(|c| reaches(c, uses, symbols))), - } - } - let mut symbols: BTreeSet<&str> = BTreeSet::new(); + // The symbols and patterns whose art uses the font in type that is not hidden or locked, nor in + // a hidden or locked group of the art, also through the instances, patterns and opacity masks + // it holds. The pattern being edited is left out: its art is on the editing layer. + let mut found = Resources::default(); loop { - let found: Vec<&str> = d + let symbols: Vec = d .symbols .iter() - .filter(|sym| !symbols.contains(sym.name.as_str()) && reaches(&sym.art, &uses, &symbols)) - .map(|sym| sym.name.as_str()) + .filter(|sym| !found.symbols.contains(&sym.name) && reaches(&sym.art, &uses, &found)) + .map(|sym| sym.name.clone()) .collect(); - if found.is_empty() { + let patterns: Vec = d + .patterns + .iter() + .filter(|p| !pattern_being_edited(d, &p.name) && !found.patterns.contains(&p.name) && p.art.iter().any(|a| reaches(a, &uses, &found))) + .map(|p| p.name.clone()) + .collect(); + if symbols.is_empty() && patterns.is_empty() { break; } - symbols.extend(found); + found.symbols.extend(symbols); + found.patterns.extend(patterns); } - // Their instances the Selection tool can reach. - if !symbols.is_empty() { + // The objects the Selection tool can reach that show such type: the instances of those + // symbols, the objects that those patterns paint, and the objects whose opacity mask holds it + // (not layers, which the Selection tool doesn't select). + let masked: HashSet = masked.into_iter().collect(); + if !found.symbols.is_empty() || !found.patterns.is_empty() || !masked.is_empty() { + let texts: HashSet = hits.iter().copied().collect(); d.walk(&mut |n: &Node| { - if let NodeKind::SymbolInstance { symbol, .. } = &n.kind - && symbols.contains(symbol.as_str()) - && editable(n.id) - { + let shows = matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if found.symbols.contains(symbol)) + || paint_patterns(n).any(|p| found.patterns.contains(p)) + || (masked.contains(&n.id) && n.extras().mask.as_deref().is_some_and(|m| reaches(&m.art, &uses, &found))); + if shows && !n.is_layer() && !texts.contains(&n.id) && editable(n.id) { hits.push(n.id); } }); @@ -1311,6 +1502,255 @@ mod tests { assert_eq!(s.execute("text.replaceFont", &serif_to_sans).unwrap(), json!({"runs": 0})); } + /// Moves object `art` of the layers into the opacity mask of `owner` (a layer or an object). + fn mask_with(s: &mut Session, owner: u64, art: u64) { + s.edit("Mask", |d, _| { + let art = d.remove(NodeId(art))?; + d.node_mut(NodeId(owner)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true))); + Ok(()) + }) + .unwrap(); + } + + /// The font families of the first runs of the text in the opacity mask of `owner`. + fn mask_families(s: &Session, owner: u64) -> Vec { + let d = &s.doc().unwrap().doc; + mask_texts(d, &[(NodeId(owner), true)]).iter().map(|(_, t, _)| t.runs[0].style.font_family.clone()).collect() + } + + /// The font families of the first runs of the text in the art of pattern `name`. + fn pattern_families(s: &Session, name: &str) -> Vec { + let d = &s.doc().unwrap().doc; + let mut out = vec![]; + for art in &d.pattern(name).unwrap().art { + art_texts(art, true, &mut out); + } + out.iter().map(|(_, t, _)| t.runs[0].style.font_family.clone()).collect() + } + + /// The rows of `text.fonts` with `p`: family, runs and objects. + fn font_rows(s: &mut Session, p: Value) -> Vec<(String, u64, u64)> { + let fonts = s.execute("text.fonts", &p).unwrap(); + fonts + .as_array() + .unwrap() + .iter() + .map(|f| (f["family"].as_str().unwrap().to_string(), f["runs"].as_u64().unwrap(), f["objects"].as_u64().unwrap())) + .collect() + } + + /// Find Font lists, selects and changes the type in opacity masks: on objects, on a layer, + /// disabled and inside the art of another mask. The type in the mask of a locked object is + /// listed and left in its font; Find selects the objects whose mask holds the type. + #[test] + fn find_font_reaches_the_type_in_opacity_masks() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let text = |s: &mut Session, y: i32| { + s.execute("text.create", &json!({"x": 10, "y": y, "text": "Serif", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap() + }; + let rect = |s: &mut Session, y: i32| { + s.execute("shape.rectangle", &json!({"x": 0, "y": y, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap() + }; + let mut owners = vec![]; + for y in [20, 50, 80] { + let owner = rect(&mut s, y); + let t = text(&mut s, y); + mask_with(&mut s, owner, t); + owners.push(owner); + } + let (open, locked, disabled) = (owners[0], owners[1], owners[2]); + s.execute("select.set", &json!({"ids": [locked]})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [disabled]})).unwrap(); + s.execute("transparency.disableOpacityMask", &json!({})).unwrap(); + // A mask whose art is an object with a mask of its own, and a layer's mask. + let nested = rect(&mut s, 110); + let inner = rect(&mut s, 110); + let t = text(&mut s, 110); + mask_with(&mut s, inner, t); + mask_with(&mut s, nested, inner); + let layer = s.doc().unwrap().doc.layers[0].id.0; + let t = text(&mut s, 140); + mask_with(&mut s, layer, t); + let mut on_layers = 0; + s.doc().unwrap().doc.walk(|n| on_layers += usize::from(matches!(n.kind, NodeKind::Text(_)))); + assert_eq!(on_layers, 0, "the type is only in masks"); + assert_eq!(font_rows(&mut s, json!({})), [("Source Serif 4".to_string(), 5, 5)]); + s.execute("select.set", &json!({"ids": [open]})).unwrap(); + assert_eq!(font_rows(&mut s, json!({"selectionOnly": true})), [("Source Serif 4".to_string(), 1, 1)]); + // Find selects the objects whose mask holds the type, not the locked one or the layer. + assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 3); + let mut selected = s.doc().unwrap().selection.objects.clone(); + selected.sort(); + assert_eq!(selected, [NodeId(open), NodeId(disabled), NodeId(nested)]); + assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4", "scope": {"artboards": [0]}})).unwrap()["count"], 3); + // Change All: one undo step, the locked object's mask left in its font and counted. + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let before = steps(&s); + let serif_to_sans = json!({"from": {"family": "Source Serif 4"}, "to": {"family": "Source Sans 3"}}); + let r = s.execute("text.replaceFont", &serif_to_sans).unwrap(); + assert_eq!((r["runs"].as_u64(), r["skipped"].as_u64()), (Some(4), Some(1)), "{r}"); + assert_eq!(steps(&s), before + 1); + for owner in [open, disabled, nested, layer] { + assert_eq!(mask_families(&s, owner), ["Source Sans 3"], "the mask of {owner}"); + } + assert_eq!(mask_families(&s, locked), ["Source Serif 4"]); + let r = s.execute("text.replaceFont", &serif_to_sans).unwrap(); + assert_eq!(r, json!({"runs": 0, "skipped": 1, "warning": REPLACE_SKIPPED})); + assert_eq!(steps(&s), before + 1); + s.execute("edit.undo", &json!({})).unwrap(); + for owner in [open, disabled, nested, layer] { + assert_eq!(mask_families(&s, owner), ["Source Serif 4"], "the mask of {owner} after Undo"); + } + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(mask_families(&s, nested), ["Source Sans 3"]); + // While a mask is edited, its type on the editing layer is counted and changed once. + s.execute("transparency.editOpacityMask", &json!({"id": open})).unwrap(); + assert_eq!(font_rows(&mut s, json!({})), [("Source Sans 3".to_string(), 4, 4), ("Source Serif 4".to_string(), 1, 1)]); + let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Inter"}})).unwrap(); + assert_eq!(r["runs"].as_u64(), Some(4), "{r}"); + let families: Vec = used_fonts(&s.doc().unwrap().doc).into_iter().map(|(family, ..)| family).collect(); + assert_eq!(families, ["Inter", "Source Serif 4"], "the edited mask is written back after each edit"); + s.execute("transparency.stopEditingOpacityMask", &json!({})).unwrap(); + assert_eq!(mask_families(&s, open), ["Inter"]); + } + + /// Find Font lists the type in pattern swatches once, also when nothing paints with them; + /// Find selects the objects the pattern paints, and Change changes the pattern's art once for + /// every object it paints. While a pattern is edited, its type is taken from the editing layer. + #[test] + fn find_font_reaches_the_type_in_patterns() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let pattern = |s: &mut Session, name: &str, font: &str| { + let t = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Ab", "font": font})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.pattern.make", &json!({"ids": [t], "name": name, "edit": false})).unwrap(); + s.execute("select.set", &json!({"ids": [t]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + }; + pattern(&mut s, "Dots", "Source Serif 4"); + pattern(&mut s, "Unused", "Inter"); + let mut on_layers = 0; + s.doc().unwrap().doc.walk(|n| on_layers += usize::from(matches!(n.kind, NodeKind::Text(_)))); + assert_eq!(on_layers, 0, "the type is only in patterns"); + let all = [("Inter".to_string(), 1, 1), ("Source Serif 4".to_string(), 1, 1)]; + assert_eq!(font_rows(&mut s, json!({})), all); + assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 0); + let mut painted = vec![]; + for y in [20, 60] { + painted.push(s.execute("shape.rectangle", &json!({"x": 0, "y": y, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap()); + } + s.execute("paint.setFill", &json!({"swatch": "Dots", "ids": painted})).unwrap(); + assert_eq!(font_rows(&mut s, json!({})), all, "a pattern's type counts once"); + assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 2); + assert_eq!(s.doc().unwrap().selection.objects, [NodeId(painted[0]), NodeId(painted[1])]); + assert_eq!(s.execute("select.font", &json!({"family": "Inter"})).unwrap()["count"], 0); + // Only the selection: the patterns the selected objects paint with. + s.execute("select.set", &json!({"ids": [painted[0]]})).unwrap(); + assert_eq!(font_rows(&mut s, json!({"selectionOnly": true})), [("Source Serif 4".to_string(), 1, 1)]); + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let before = steps(&s); + let r = s + .execute("text.replaceFont", &json!({"from": {"family": "Source Serif 4"}, "to": {"family": "Source Sans 3"}, "selectionOnly": true})) + .unwrap(); + assert_eq!(r, json!({"runs": 1})); + assert_eq!(steps(&s), before + 1); + assert_eq!(pattern_families(&s, "Dots"), ["Source Sans 3"]); + assert_eq!(pattern_families(&s, "Unused"), ["Inter"]); + // No run changes: no undo step. + let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Source Sans 3"}})).unwrap(); + assert_eq!(r, json!({"runs": 0})); + assert_eq!(steps(&s), before + 1); + // Change All reaches the swatch nothing paints with. + let r = s.execute("text.replaceFont", &json!({"from": {"family": "Inter"}, "to": {"family": "Source Serif 4"}})).unwrap(); + assert_eq!(r, json!({"runs": 1})); + assert_eq!(pattern_families(&s, "Unused"), ["Source Serif 4"]); + // A pattern in a hidden fill doesn't show: Find doesn't select the object for its type. + let hidden = s.execute("shape.rectangle", &json!({"x": 100, "y": 20, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Unused", "ids": [hidden]})).unwrap(); + assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 1); + s.edit("Hide the fill", |d, _| { + for it in d.node_mut(NodeId(hidden)).unwrap().appearance.items.iter_mut() { + if let AppearanceItem::Fill(f) = it { + f.visible = false; + } + } + Ok(()) + }) + .unwrap(); + assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 0); + // Nor does a pattern on a stroke of no width. + s.execute("paint.setStroke", &json!({"swatch": "Unused", "ids": [hidden]})).unwrap(); + assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 1); + s.edit("Thin the stroke", |d, _| { + for it in d.node_mut(NodeId(hidden)).unwrap().appearance.items.iter_mut() { + if let AppearanceItem::Stroke(st) = it { + st.width = 0.0; + } + } + Ok(()) + }) + .unwrap(); + assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 0); + // A locked painted object: its pattern's type is listed and left in its font. + s.execute("select.set", &json!({"ids": [painted[1]]})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [painted[1]]})).unwrap(); + let r = + s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Inter"}, "selectionOnly": true})).unwrap(); + assert_eq!((r["runs"].as_u64(), r["skipped"].as_u64()), (Some(0), Some(1)), "{r}"); + assert_eq!(s.execute("select.font", &json!({"family": "Source Sans 3"})).unwrap()["count"], 1); + assert_eq!(s.doc().unwrap().selection.objects, [NodeId(painted[0])]); + // While the pattern is edited, its type on the editing layer is counted and changed once. + s.execute("object.pattern.edit", &json!({"name": "Dots"})).unwrap(); + let rows = font_rows(&mut s, json!({})); + assert_eq!(rows, [("Source Sans 3".to_string(), 1, 1), ("Source Serif 4".to_string(), 1, 1)]); + let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Inter"}})).unwrap(); + assert_eq!(r, json!({"runs": 1})); + let families: Vec = used_fonts(&s.doc().unwrap().doc).into_iter().map(|(family, ..)| family).collect(); + assert_eq!(families, ["Inter", "Source Serif 4"], "the pattern's stored art is left out while it is edited"); + s.execute("object.pattern.done", &json!({})).unwrap(); + assert_eq!(pattern_families(&s, "Dots"), ["Inter"]); + } + + /// A pattern whose art holds a symbol instance, painting objects inside and outside a symbol: + /// Find Font lists each pattern's and symbol's type once and reaches the symbol's type through + /// the pattern. + #[test] + fn find_font_reaches_symbols_through_patterns() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let inter = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "In", "font": "Inter"})).unwrap()["id"].clone(); + s.execute("symbol.new", &json!({"name": "Mark", "ids": [inter]})).unwrap(); + let instance = s.doc().unwrap().selection.objects[0].0; + let serif = s.execute("text.create", &json!({"x": 10, "y": 60, "text": "Se", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap(); + let tile = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 80})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.pattern.make", &json!({"ids": [tile, serif, instance], "name": "Loop", "edit": false})).unwrap(); + s.execute("select.set", &json!({"ids": [tile, serif, instance]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + // Another object paints with the pattern too: its type is still read once. + let other = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Loop", "ids": [other]})).unwrap(); + s.execute("symbol.new", &json!({"name": "Outer", "ids": [other]})).unwrap(); + let outer = s.doc().unwrap().selection.objects[0]; + let painted = s.execute("shape.rectangle", &json!({"x": 0, "y": 100, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Loop", "ids": [painted]})).unwrap(); + let both = [("Inter".to_string(), 1, 1), ("Source Serif 4".to_string(), 1, 1)]; + assert_eq!(font_rows(&mut s, json!({})), both); + s.execute("select.set", &json!({"ids": [painted]})).unwrap(); + assert_eq!(font_rows(&mut s, json!({"selectionOnly": true})), both); + // Find reaches the symbol's type through the pattern, and through a symbol whose art paints + // with the pattern. + assert_eq!(s.execute("select.font", &json!({"family": "Inter"})).unwrap()["count"], 2); + assert_eq!(s.doc().unwrap().selection.objects, [outer, NodeId(painted)]); + s.execute("select.set", &json!({"ids": [painted]})).unwrap(); + let r = + s.execute("text.replaceFont", &json!({"from": {"family": "Inter"}, "to": {"family": "Source Sans 3"}, "selectionOnly": true})).unwrap(); + assert_eq!(r, json!({"runs": 1})); + assert_eq!(symbol_texts(&s.doc().unwrap().doc, None)[0].0.runs[0].style.font_family, "Source Sans 3"); + } + /// The font family of text object `id`'s first run. fn text_family(s: &Session, id: u64) -> String { text(&s.doc().unwrap().doc, NodeId(id)).unwrap().runs[0].style.font_family.clone() diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 9b37bfaa6f..1ab5707d58 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -67,7 +67,7 @@ pub fn specs() -> Vec { "Character / Paragraph", [], None, - "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", + "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options, as text.setRangeStyle: space before and after each character in reading order), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", has_doc, set_format ), @@ -571,6 +571,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result { "tateChuYoko", "tcyUpDown", "tcyLeftRight", + "akiLeft", + "akiRight", "standardVerticalRoman", "noBreak", "digits", @@ -613,6 +615,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result { let font_height_reference = super::textedit::font_height_reference_param(p, C)?; let tcy_up_down = super::textedit::tcy_offset_param(p, "tcyUpDown", C)?; let tcy_left_right = super::textedit::tcy_offset_param(p, "tcyLeftRight", C)?; + let aki_left = super::textedit::aki_param(p, "akiLeft", C)?; + let aki_right = super::textedit::aki_param(p, "akiRight", C)?; let mojikumi = match p.get("mojikumi") { None | Some(Value::Null) => None, Some(v) => Some(match v.as_str() { @@ -773,6 +777,12 @@ fn set_format(s: &mut Session, p: &Value) -> Result { if let Some(v) = tcy.1 { st.tcy_left_right = v; } + if let Some(v) = aki_left { + st.aki_left = v; + } + if let Some(v) = aki_right { + st.aki_right = v; + } if let Some(v) = flag("standardVerticalRoman") { st.standard_vertical_roman = v; } diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 0f5ada29fe..11c9c0dca7 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -472,6 +472,7 @@ pub(super) const ALLOWED: &[&str] = &[ "perspective.transform", "recolor.apply", "recolor.colors", + "recolor.pickTheme", "recolor.randomize", "recolor.reduce", "select.add", diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index 74347caa04..34091017e3 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -11,6 +11,7 @@ use vectorcraft_color::recolor::{ColorKey, GlobalAdjust, Method, Preserve, Rng, use vectorcraft_color::{Color, Paint, Swatch}; use vectorcraft_doc::swatches::{node_colors, node_paints, override_paints}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Point, Rect}; use super::colorcmds::{NotChanged, Recolor, Scope, left_out}; use super::{CommandSpec, Result, Session, always, bad, checked_ids_param, cmd, color_value, has_doc, index, str_param, switch_or, text_param}; @@ -53,9 +54,827 @@ pub fn specs() -> Vec { always, randomize ), + cmd!( + query "recolor.pickTheme", + "Color Theme Picker", + [], + None, + "{picks: [{at: [x, y]} (a click: the object a Selection tool click there takes, with everything inside it) | {rect: [x0, y0, x1, y1]} (a marquee: every painted object it touches, and the part of each image inside it)] (1 to 256, in document points), colors?: 5 (1 to 64)} → {colors: [colour keys, the most used first], objects: the number of objects read} the colour palette of the art picked, for Recolor Artwork's Color Theme Picker: visible fills and strokes, gradient stops, text, mesh points, pattern tiles (with the patterns they use), the art of symbol instances (placed through their 9-slice guides), the colorize colour of an image it applies to and other images' pixels (at most 65,536 pixels of each pick of an image, spread evenly, and 1,048,576 pixels of at most 64 images in all; pixels less than half opaque and images that can't be decoded are left out). In a clip group, or under an opacity mask that clips, only what shows inside the clipping path or the mask art is read; a blend, envelope or repeat a marquee touches is read whole. Hidden or fully transparent objects and fill or stroke items are left out; locked objects are read. Each object read weighs the same, shared among its colours (an image's among its pixels; the vector art a symbol instance places counts as one object, each image it places on its own); similar colours merge (k-means in Lab) into at most `colors`, each shown by its most used colour in its own model. Picks that touch no art give no colours. Changes nothing", + has_doc, + pick_theme + ), ] } +/// The pixels one read of an image by the Color Theme Picker takes, at most, the pixels all its +/// reads share, and the images one pick reads, at most. +const THEME_PIXELS: usize = 65_536; +const THEME_TOTAL_PIXELS: usize = 1 << 20; +const MAX_THEME_IMAGES: usize = 64; +/// The image reads one pick queues, at most. +const MAX_THEME_READS: usize = 4096; +/// The stroke segments the opacity masks one pick reads are outlined along, at most. +const MASK_OUTLINE_SEGMENTS: usize = 20_000; +/// The point-in-region tests one pick makes to find whether outlines show through clip groups, +/// and the clipping-path elements the pixels of one image are tested against, at most. +const THEME_WORK: usize = 4_000_000; +/// The picks one `recolor.pickTheme` takes, and the colours it gives, at most. +const MAX_PICKS: usize = 256; +const MAX_THEME_COLORS: u64 = 64; +/// The objects the Color Theme Picker reads through, one inside another, at most. +const MAX_THEME_DEPTH: usize = 256; + +/// A pick of the Color Theme Picker: a click at a point or a marquee. +enum Pick { + At(Point), + Area(Rect), +} + +impl Pick { + /// `{at: [x, y]}` or `{rect: [x0, y0, x1, y1]}`, finite numbers. + fn param(v: &Value, cmd: &str) -> Result { + let numbers = |a: &Value, n: usize| -> Option> { + let a = a.as_array().filter(|a| a.len() == n)?; + a.iter().map(|x| x.as_f64().filter(|x| x.is_finite())).collect() + }; + match (v.get("at"), v.get("rect")) { + (Some(at), None) => { + numbers(at, 2).map(|p| Pick::At(Point::new(p[0], p[1]))).ok_or_else(|| bad(cmd, format!("`at` must be [x, y] (got {at})"))) + } + (None, Some(r)) => numbers(r, 4) + .map(|r| Pick::Area(Rect::new(r[0], r[1], r[2], r[3]).abs())) + .ok_or_else(|| bad(cmd, format!("`rect` must be [x0, y0, x1, y1] (got {r})"))), + _ => Err(bad(cmd, format!("each pick is {{at: [x, y]}} or {{rect: [x0, y0, x1, y1]}} (got {v})"))), + } + } +} + +/// A filled region: its outline and fill rule. +type Region = (vectorcraft_geom::BezPath, vectorcraft_geom::FillRule); + +/// An image the Color Theme Picker reads: its pixels, where it lies, the marquee it is read in +/// (`None`: all of it) and the region the clip groups around it show (`None`: unclipped). An +/// image its colorize paint applies to ([`vectorcraft_doc::ImageBlob::takes_colorize`]) gives that +/// paint's colours where a pixel read shows ink (opaque and darker than white). +#[derive(Clone)] +struct ImageRead<'a> { + blob: &'a vectorcraft_doc::ImageBlob, + xf: vectorcraft_geom::Affine, + size: (f64, f64), + area: Option, + clip: Option>, + colorize: Option>, +} + +/// The colours the Color Theme Picker has read: each object weighs 1, shared among its colours. +struct Theme<'a> { + d: &'a Document, + boxes: vectorcraft_doc::SymbolBoxes<'a>, + samples: Vec<(Color, f32)>, + /// The images to read, each image decoded once for all its reads ([`Self::read_images`]), + /// and the images they read. + images: Vec>, + blobs: std::collections::HashSet<*const vectorcraft_doc::ImageBlob>, + /// What the clip groups being read show, in document space: the union of these regions + /// (none: nothing shows); `None` outside clip groups. + clip: Option>, + /// The colours of the patterns read so far, and the patterns whose tiles are being read. + pattern_colors: HashMap, Vec>)>, + pattern_stack: Vec, + /// The region tests [`Self::shows`] has made. + work: std::cell::Cell, + /// The object isolated in isolation mode. + scope: Option, + /// The stroke segments opacity masks may still be outlined along ([`mask_regions`]). + mask_budget: usize, + objects: usize, +} + +/// The region both `a` and `b` (each a union of regions) cover, filled non-zero. +fn intersect_regions(a: &[Region], b: &[Region]) -> Vec { + let paths: Vec = a.iter().chain(b).map(|(bp, _)| vectorcraft_geom::PathData::from_bezpath(bp)).collect(); + let inputs: Vec<(&vectorcraft_geom::PathData, vectorcraft_geom::FillRule)> = + paths.iter().zip(a.iter().chain(b)).map(|(p, (_, rule))| (p, *rule)).collect(); + let split = a.len(); + let both = vectorcraft_pathops::boolean_n(&inputs, |inside| inside.iter().any(|i| *i < split) && inside.iter().any(|i| *i >= split)); + if both.subpaths.is_empty() { vec![] } else { vec![(both.to_bezpath(), vectorcraft_geom::FillRule::NonZero)] } +} + +impl<'a> Theme<'a> { + fn new(d: &'a Document) -> Self { + Self { + d, + boxes: d.symbol_boxes(), + samples: vec![], + images: vec![], + blobs: std::collections::HashSet::new(), + clip: None, + pattern_colors: HashMap::new(), + pattern_stack: vec![], + work: std::cell::Cell::new(0), + scope: None, + mask_budget: MASK_OUTLINE_SEGMENTS, + objects: 0, + } + } + + fn add(&mut self, colors: Vec) { + if colors.is_empty() { + return; + } + let w = 1.0 / colors.len() as f32; + self.samples.extend(colors.into_iter().map(|c| (c, w))); + self.objects += 1; + } + + /// Read the images queued, each image's pixels decoded once, as colours: the pixels a read + /// gives that fall in one cell of 16 levels a channel merge into their average, weighted by how + /// many there are, and the cells of all the reads add up, so the images give at most 16³ + /// colours. Images that can't be decoded give none. The first [`MAX_THEME_IMAGES`] images + /// are read, and all the reads share [`THEME_TOTAL_PIXELS`] pixels (each read at least one, at + /// most [`THEME_PIXELS`]). + fn read_images(&mut self) { + let reads = std::mem::take(&mut self.images); + // The reads of each image, in the order its first read came. + let mut by_image: Vec<(*const vectorcraft_doc::ImageBlob, Vec<&ImageRead>)> = vec![]; + for r in &reads { + let key: *const vectorcraft_doc::ImageBlob = r.blob; + match by_image.iter().position(|(k, _)| *k == key) { + Some(i) => by_image[i].1.push(r), + None if by_image.len() < MAX_THEME_IMAGES => by_image.push((key, vec![r])), + None => {} + } + } + let count: usize = by_image.iter().map(|(_, g)| g.len()).sum(); + let budget = (THEME_TOTAL_PIXELS / count.max(1)).clamp(1, THEME_PIXELS); + let mut pixels: HashMap<[u8; 3], ([f64; 3], f64)> = HashMap::new(); + for (_, group) in by_image { + let keeps: Vec bool + '_>> = group + .iter() + .map(|r| { + let (xf, (w, h), area, clip) = (r.xf, r.size, r.area, &r.clip); + Box::new(move |u: f64, v: f64| { + let p = xf * Point::new(u * w, v * h); + area.is_none_or(|a| a.contains(p)) + && clip.as_ref().is_none_or(|rs| rs.iter().any(|(bp, rule)| vectorcraft_geom::hit::fill_contains(bp, *rule, p))) + }) as Box bool + '_> + }) + .collect(); + let picks: Vec = group + .iter() + .zip(&keeps) + .map(|(r, keep)| { + use vectorcraft_geom::kurbo::Shape; + let (w, h) = r.size; + let inv = r.xf.inverse(); + // The box sampled: the marquee, cut to the clipping paths' bounds, so a small + // region a clip shows of a large image is still sampled densely. + let clip_box = r.clip.as_ref().map(|rs| rs.iter().map(|(bp, _)| bp.bounding_box()).reduce(|a, b| a.union(b)).unwrap_or_default()); + let region = match (r.area, clip_box) { + (Some(a), Some(c)) => Some(a.intersect(c)), + (a, c) => a.or(c), + }; + let box_uv = region.map(|a| { + let uv: Vec = + [(a.x0, a.y0), (a.x1, a.y0), (a.x0, a.y1), (a.x1, a.y1)].into_iter().map(|(x, y)| inv * Point::new(x, y)).collect(); + let low = |f: fn(&Point) -> f64| uv.iter().map(f).fold(f64::INFINITY, f64::min); + let high = |f: fn(&Point) -> f64| uv.iter().map(f).fold(f64::NEG_INFINITY, f64::max); + [low(|p| p.x) / w, low(|p| p.y) / h, high(|p| p.x) / w, high(|p| p.y) / h] + }); + (box_uv, keep.as_ref()) + }) + .collect(); + // Each sampled pixel inside a clip group is tested against the clipping regions: the + // pixels one image gives keep that work within THEME_WORK path elements. + let elements = + group.iter().map(|r| r.clip.as_ref().map_or(0, |rs| rs.iter().map(|(bp, _)| bp.elements().len()).sum::())).max().unwrap_or(0); + let budget = THEME_WORK.checked_div(elements).map_or(budget, |w| budget.min(w.max(1))); + let Some(each) = group[0].blob.sample_pixels(&picks, budget) else { continue }; + for (px, read) in each.into_iter().zip(&group) { + if let Some(colors) = &read.colorize { + // Ink: an opaque pixel darker than white takes the colorize paint. + if !colors.is_empty() && px.iter().any(|p| p[3] >= 128 && p[..3].iter().any(|v| *v < 255)) { + let w = 1.0 / colors.len().max(1) as f32; + self.samples.extend(colors.iter().map(|c| (*c, w))); + self.objects += 1; + } + continue; + } + let mut cells: HashMap<[u8; 3], ([u64; 3], u64)> = HashMap::new(); + for [r, g, b, _] in px.into_iter().filter(|p| p[3] >= 128) { + let cell = cells.entry([r >> 4, g >> 4, b >> 4]).or_default(); + for (sum, v) in cell.0.iter_mut().zip([r, g, b]) { + *sum += u64::from(v); + } + cell.1 += 1; + } + let total: u64 = cells.values().map(|c| c.1).sum(); + if total == 0 { + continue; + } + for (key, (sum, n)) in cells { + let cell = pixels.entry(key).or_default(); + for (acc, s) in cell.0.iter_mut().zip(sum) { + *acc += s as f64 / total as f64; + } + cell.1 += n as f64 / total as f64; + } + self.objects += 1; + } + } + let mut cells: Vec<_> = pixels.into_iter().collect(); + // The same order on every run. + cells.sort_unstable_by_key(|c| c.0); + for (_, (sum, w)) in cells { + let [r, g, b] = sum.map(|s| (s / w).round().clamp(0.0, 255.0) as u8); + self.samples.push((Color::rgb8(r, g, b), w as f32)); + } + } + + /// Read `n` and everything visible inside it: each image (its part inside `area` when given, + /// and inside the clipping paths around it) and each other object with colours of its own + /// (that touches `area` when given, and shows inside the clipping paths around it). The art a + /// symbol instance shows (with a dynamic instance's own paints), placed where the instance + /// draws it, and the objects a blend, an envelope or a repeat draws elsewhere than they lie, + /// are read whole when the instance or the live object touches `area`. `depth` counts the + /// objects passed through: deeper art is left out. An enabled opacity mask that clips (and is + /// not inverted) shows the object only where its mask art is lighter than black + /// ([`mask_regions`]), as a clip group would. + fn read(&mut self, n: &Node, area: Option, depth: usize) { + let Some(mask) = n.extras().mask.as_deref().filter(|m| !m.disabled && m.clip && !m.invert) else { + return self.read_unmasked(n, area, depth); + }; + let regions = mask_regions(&mask.art, &mut self.mask_budget); + let outer = self.clip.clone(); + self.clip = Some(match &outer { + None => regions, + Some(o) => intersect_regions(o, ®ions), + }); + self.read_unmasked(n, area, depth); + self.clip = outer; + } + + /// [`Self::read`] without `n`'s opacity mask. + fn read_unmasked(&mut self, n: &Node, area: Option, depth: usize) { + // Hidden and fully transparent objects show nothing. + if depth > MAX_THEME_DEPTH || !n.visible || n.opacity <= 0.0 || matches!(n.kind, NodeKind::Path { guide: true, .. }) { + return; + } + let touches = area.is_none_or(|r| self.touches(n, r)); + match &n.kind { + NodeKind::Image(im) => { + if !touches { + return; + } + // A document keeps its images' pixels in its image store. + let Some(blob) = self.d.images.get(&im.key) else { return }; + // An image with a colorize paint shows that paint's color, not its own pixels; + // other paints its appearance has (with effects that draw them) count as well. + let colorized = n.extras().colorize.is_some() && blob.takes_colorize(); + let own = if colorized || n.extras().colorize.is_none() { + self.own(n, true) + } else { + // A colorize paint the image does not take (a linked image's preview) + // shows nothing. + let mut plain = n.clone(); + plain.extras_mut().colorize = None; + self.own(&plain, true) + }; + let colorize = if colorized { + Some(own) + } else { + if self.shows(n, area) { + self.add(own); + } + None + }; + let size = (f64::from(im.width.max(1)), f64::from(im.height.max(1))); + self.queue_image(ImageRead { blob, xf: im.xf, size, area, clip: self.clip.clone(), colorize }); + return; + } + NodeKind::SymbolInstance { symbol, xf } => { + if touches + && self.shows(n, area) + && let Some(s) = self.d.symbols.iter().find(|s| s.name == *symbol) + { + // The instance's own paints; its overrides show in its art. + let own = self.own(n, false); + self.add(own); + // The art as the instance places it: through the symbol's 9-slice guides when + // it has them, else by the instance's transform. Art that would place too many + // objects is left out, as the renderer leaves it out. + let dynamic = (!n.extras().symbol_overrides.is_empty()).then(|| vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, n)); + if let Some(placed) = self.d.place_symbol_art(symbol, dynamic.as_ref().unwrap_or(&s.art), *xf) { + // The vector art counts as one object, each of its colours once, so an + // object the 9-slice guides cut into several copies does not count more. + // Each image placed is read on its own, as images are elsewhere. + let (samples, objects) = (self.samples.len(), self.objects); + self.read(&placed, None, depth + 1); + let added = self.samples.split_off(samples); + self.objects = objects; + let mut seen = std::collections::HashSet::new(); + let colors: Vec = added.into_iter().map(|(c, _)| c).filter(|c| seen.insert(ColorKey::of(c))).collect(); + self.add(colors); + } + } + return; + } + NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) => { + if touches && self.shows(n, area) { + let own = self.own(n, true); + self.add(own); + // The copies are drawn elsewhere than the objects lie: the clipping paths + // around the live object, tested above, do not apply to the objects. + let clip = self.clip.take(); + for c in n.children().into_iter().flatten() { + self.read(c, None, depth + 1); + } + self.clip = clip; + } + return; + } + _ => {} + } + if touches && self.shows(n, area) { + let own = self.own(n, true); + self.add(own); + } + // A compound path's members are its geometry: the compound paints them. + if matches!(n.kind, NodeKind::Compound { .. }) { + return; + } + // A clip group's clipping path paints whole, over the art it clips: it is read in the + // marquee as given and under the clip groups around it alone. + let clip_child = n.children().and_then(|c| c.first()).filter(|_| n.clips()); + if let Some(first) = clip_child { + self.read(first, area, depth + 1); + } + let inner = match area { + Some(r) => match vectorcraft_doc::hit::marquee_in(n, r) { + Some(inner) => Some(inner), + None => return, + }, + None => None, + }; + // A clip group shows its art where its clipping path's regions and the clip groups around + // it all show. + let outer = self.clip.clone(); + if n.clips() + && let Some(first) = n.children().and_then(|c| c.first()) + { + let regions: Vec = vectorcraft_doc::hit::clip_regions(first); + self.clip = Some(match &outer { + None => regions, + Some(o) => intersect_regions(o, ®ions), + }); + } + // A Shaper Group's original shapes, which the group keeps but does not show, are left out. + for (i, c) in n.children().into_iter().flatten().enumerate().skip(usize::from(clip_child.is_some())) { + if !vectorcraft_doc::hit::shaper_hides(n, i, self.scope) { + self.read(c, inner, depth + 1); + } + } + self.clip = outer; + } + + /// Does `n` show inside the region the clip groups around it show, in `area` when given? Its + /// box (cut to `area`) meets a region of it: the region's outline crosses the box, or a point + /// on a 9 × 9 grid over the part of the box inside the region's bounds lies in the region. + fn shows(&self, n: &Node, area: Option) -> bool { + use vectorcraft_geom::kurbo::Shape; + let Some(regions) = &self.clip else { return true }; + let Some(b) = n.visual_bounds_with(&self.boxes) else { return false }; + let b = area.map_or(b, |r| b.intersect(r)); + let valid = |r: &Rect| r.width() >= 0.0 && r.height() >= 0.0; + if !valid(&b) { + return false; + } + // A path or compound path paints along its outline, and inside it where it has a visible + // fill: a point along the outline, or (filled) a point of a 9 × 9 grid over the part of the + // box inside a region's bounds that lies in both its fill and the region, must show. + let filled = has_fill(n); + let outline: Option<(Vec<&vectorcraft_geom::PathData>, vectorcraft_geom::FillRule)> = match &n.kind { + NodeKind::Path { path, rule, .. } => Some((vec![path], *rule)), + NodeKind::Compound { children, rule } => Some((children.iter().filter(|c| c.visible).filter_map(|c| c.path_data()).collect(), *rule)), + _ => None, + }; + if let Some((paths, own_rule)) = outline { + use vectorcraft_geom::ParamCurve; + use vectorcraft_geom::kurbo::ParamCurveArclen; + // The work all these tests do is bounded: past it, objects count as shown. + if self.work.get() > THEME_WORK { + return true; + } + let half = stroke_reach(n); + let cost: usize = regions.iter().map(|(bp, _)| bp.elements().len().max(1)).sum(); + let in_region = |p: Point| { + // Past the work allowed, the outline counts as shown. + if self.work.get() > THEME_WORK { + return true; + } + self.work.set(self.work.get() + cost); + regions.iter().any(|(bp, rule)| { + vectorcraft_geom::hit::fill_contains(bp, *rule, p) || half > 0.0 && vectorcraft_geom::hit::stroke_contains(bp, 0.0, half, p) + }) + }; + let mut fill = vectorcraft_geom::BezPath::new(); + for p in &paths { + fill.extend(p.to_bezpath().elements().iter().copied()); + } + // At most 4,096 points along the outline, shared among its segments by length, no + // farther apart than half the smallest region's width or height where that allows. + let step = regions + .iter() + .map(|(bp, _)| bp.bounding_box()) + .chain(area) + .map(|rb| rb.width().min(rb.height())) + .fold(f64::INFINITY, f64::min) + .max(0.01) + / 2.0; + // With a marquee, only the outline inside it (within the stroke's reach) counts. + let picked = area.map(|r| r.inflate(half, half)); + let segs: Vec<(vectorcraft_geom::PathSeg, f64)> = fill + .segments() + .take(4096) + .map(|s| { + let len = s.arclen(0.5); + (s, if len.is_finite() { len } else { 0.0 }) + }) + .collect(); + let total: f64 = segs.iter().map(|(_, l)| l).sum(); + let points = (total / step).ceil().clamp(64.0, 4096.0); + let along = segs.iter().any(|(seg, len)| { + let n = if total > 0.0 { (points * len / total).round().clamp(1.0, 4096.0) as u32 } else { 1 }; + (0..=n).any(|i| { + let p = seg.eval(f64::from(i) / f64::from(n)); + picked.is_none_or(|r| r.contains(p)) && in_region(p) + }) + }); + return along + || filled + && regions.iter().any(|(bp, _)| { + let g = b.intersect(bp.bounding_box()); + valid(&g) + && (0..81).any(|i| { + let p = Point::new(g.x0 + g.width() * f64::from(i % 9) / 8.0, g.y0 + g.height() * f64::from(i / 9) / 8.0); + in_region(p) && vectorcraft_geom::hit::fill_contains(&fill, own_rule, p) + }) + }); + } + regions.iter().any(|(bp, rule)| { + let g = b.intersect(bp.bounding_box()); + valid(&g) + && (vectorcraft_geom::hit::intersects_rect(&vectorcraft_geom::PathData::from_bezpath(bp), b) + || (0..81).any(|i| { + let p = Point::new(g.x0 + g.width() * f64::from(i % 9) / 8.0, g.y0 + g.height() * f64::from(i / 9) / 8.0); + vectorcraft_geom::hit::fill_contains(bp, *rule, p) + })) + }) + } + + /// Does the marquee `r` touch what `n` paints? A path or a compound path is touched where its + /// outline comes within half its widest visible stroke of `r` or, when it has a visible fill, + /// where `r`'s centre lies in that fill; any other object is touched by its box. + fn touches(&self, n: &Node, r: Rect) -> bool { + let boxed = n.visual_bounds_with(&self.boxes).is_some_and(|b| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1); + let filled = || has_fill(n); + let half = stroke_reach(n); + let near = r.inflate(half, half); + let crosses = |paths: &[&vectorcraft_geom::PathData], rule: vectorcraft_geom::FillRule| { + paths.iter().any(|p| vectorcraft_geom::hit::intersects_rect(p, near)) + || filled() && { + let mut bp = vectorcraft_geom::BezPath::new(); + for p in paths { + bp.extend(p.to_bezpath().elements().iter().copied()); + } + // A point on a 5 × 5 grid over the part of the marquee in the path's box lies + // in its fill. + use vectorcraft_geom::kurbo::Shape; + let g = r.intersect(bp.bounding_box()); + g.width() >= 0.0 + && g.height() >= 0.0 + && (0..25).any(|i| { + let p = Point::new(g.x0 + g.width() * f64::from(i % 5) / 4.0, g.y0 + g.height() * f64::from(i / 5) / 4.0); + vectorcraft_geom::hit::fill_contains(&bp, rule, p) + }) + } + }; + match &n.kind { + NodeKind::Path { path, rule, .. } => boxed && crosses(&[path], *rule), + NodeKind::Compound { children, rule } => { + let paths: Vec<&vectorcraft_geom::PathData> = children.iter().filter(|c| c.visible).filter_map(|c| c.path_data()).collect(); + boxed && crosses(&paths, *rule) + } + _ => boxed, + } + } +} + +/// The regions where opacity mask art `art` lets the masked object show: the regions +/// ([`vectorcraft_doc::hit::clip_regions`]) of its visible paths and compound paths filled lighter +/// than black (a solid color, a gradient with a stop lighter than black, or a pattern), the +/// outlines of the strokes lighter than black they have (dashes read as solid), the frames of its +/// images, the boxes of its type painted lighter than black, the boxes of art with effects (with +/// what the effects reach), and the regions of its clip groups and live objects whole. Black, +/// unfilled and unstroked paths without effects hide; how light the art is beyond that is not +/// read. Strokes are outlined along at most `budget` segments in all (it counts down); past that +/// a stroke counts by its box grown by half its width. +fn mask_regions(art: &Node, budget: &mut usize) -> Vec { + // Any color but black lets the masked art show. + fn light(p: &Paint) -> bool { + let lit = |c: &Color| c.to_rgba8(1.0)[..3].iter().any(|v| *v > 0); + match p { + Paint::None => false, + Paint::Solid { color, .. } => lit(color), + Paint::Gradient(g) => g.gradient.stops.iter().any(|s| lit(&s.color)), + _ => true, + } + } + fn walk(n: &Node, depth: usize, out: &mut Vec, budget: &mut usize) { + use vectorcraft_geom::kurbo::Shape; + // The mask art's root masks even when it is hidden. + // Guides draw nothing. + if depth > MAX_THEME_DEPTH || depth > 0 && (!n.visible || n.opacity <= 0.0) || matches!(n.kind, NodeKind::Path { guide: true, .. }) { + return; + } + // Art with effects can show light anywhere near it (a glow on black art): it counts + // whole, as a clipping path would. + let effects = !n.appearance.effects.is_empty() + || n.appearance.items.iter().any(|it| match it { + vectorcraft_doc::AppearanceItem::Fill(l) => l.visible && !l.effects.is_empty(), + vectorcraft_doc::AppearanceItem::Stroke(l) => l.visible && !l.effects.is_empty(), + }); + if effects { + if let Some(b) = n.visual_bounds() { + out.push((b.to_path(0.1), vectorcraft_geom::FillRule::NonZero)); + } + return; + } + let lit = n + .appearance + .items + .iter() + .any(|it| matches!(it, vectorcraft_doc::AppearanceItem::Fill(l) if l.visible && l.opacity > 0.0 && light(&l.paint))); + let stroke = n + .appearance + .items + .iter() + .filter_map(|it| match it { + vectorcraft_doc::AppearanceItem::Stroke(l) if l.visible && l.opacity > 0.0 && l.width > 0.0 && light(&l.paint) => Some(l.width / 2.0), + _ => None, + }) + .fold(None, |a: Option, w| Some(a.map_or(w, |a| a.max(w)))); + let boxed = |out: &mut Vec| { + if let Some(b) = n.geometric_bounds() { + out.push((b.to_path(0.1), vectorcraft_geom::FillRule::NonZero)); + } + }; + match &n.kind { + NodeKind::Path { .. } | NodeKind::Compound { .. } => { + if lit { + out.extend(vectorcraft_doc::hit::clip_regions(n)); + } + // A stroke shows the art along it: its outline with round ends and corners, a + // dashed stroke read as solid (the most it can show). + if let Some(half) = stroke { + let paths: Vec<&vectorcraft_geom::PathData> = match &n.kind { + NodeKind::Path { path, .. } => vec![path], + NodeKind::Compound { children, .. } => children.iter().filter_map(|c| c.path_data()).collect(), + _ => vec![], + }; + for p in paths { + // Past MASK_OUTLINE_SEGMENTS outlined segments, a stroke counts by its + // box grown by half its width. + let segments = p.to_bezpath().elements().len(); + if *budget < segments { + if let Some(b) = p.bounds().filter(|_| half.is_finite()) { + out.push((b.inflate(half, half).to_path(0.1), vectorcraft_geom::FillRule::NonZero)); + } + continue; + } + *budget -= segments; + let region = vectorcraft_pathops::outline_stroke( + p, + half * 2.0, + vectorcraft_pathops::Cap::Round, + vectorcraft_pathops::Join::Round, + 10.0, + ); + if !region.subpaths.is_empty() { + out.push((region.to_bezpath(), vectorcraft_geom::FillRule::NonZero)); + } + } + } + } + NodeKind::Image(_) => out.extend(vectorcraft_doc::hit::clip_regions(n)), + NodeKind::Text(t) => { + if lit || stroke.is_some() || t.runs.iter().any(|r| light(&r.style.fill) || r.style.stroke_width > 0.0 && light(&r.style.stroke)) { + boxed(out); + } + } + NodeKind::Group { clip: false, .. } | NodeKind::Layer { clip: false, .. } => { + // A Shaper Group's original shapes are kept but not drawn. + for (i, c) in n.children().into_iter().flatten().enumerate() { + if !vectorcraft_doc::hit::shaper_hides(n, i, None) { + walk(c, depth + 1, out, budget); + } + } + } + // Clip groups, live objects and placed documents count by the regions they clip to. + _ => out.extend(vectorcraft_doc::hit::clip_regions(n)), + } + } + let mut out = vec![]; + walk(art, 0, &mut out, budget); + out +} + +/// Does `n` have a fill item that paints: visible, not fully transparent and not None? +fn has_fill(n: &Node) -> bool { + n.appearance + .items + .iter() + .any(|it| matches!(it, vectorcraft_doc::AppearanceItem::Fill(l) if l.visible && l.opacity > 0.0 && !matches!(l.paint, Paint::None))) +} + +/// How far `n`'s widest painting stroke reaches from its path: half its width (0 without one). +fn stroke_reach(n: &Node) -> f64 { + let paints = |l: &vectorcraft_doc::StrokeLayer| l.visible && l.opacity > 0.0 && !matches!(l.paint, Paint::None) && l.width.is_finite(); + n.appearance + .items + .iter() + .filter_map(|it| match it { + vectorcraft_doc::AppearanceItem::Stroke(l) if paints(l) => Some(l.width.max(0.0) / 2.0), + _ => None, + }) + .fold(0.0, f64::max) +} + +/// The paints `m` shows: its visible fill items and its visible strokes wider than 0, its text's +/// fills and strokes wider than 0, and its colorize paint. +fn shown_paints(m: &Node) -> impl Iterator { + let runs = match &m.kind { + NodeKind::Text(t) => t.runs.as_slice(), + _ => &[], + }; + let items = m.appearance.items.iter().filter_map(|it| match it { + vectorcraft_doc::AppearanceItem::Fill(l) if l.visible && l.opacity > 0.0 => Some(&l.paint), + vectorcraft_doc::AppearanceItem::Stroke(l) if l.visible && l.opacity > 0.0 && l.width > 0.0 => Some(&l.paint), + _ => None, + }); + let text = runs.iter().flat_map(|r| std::iter::once(&r.style.fill).chain((r.style.stroke_width > 0.0).then_some(&r.style.stroke))); + items.chain(text).chain(m.extras().colorize.as_deref()) +} + +/// Add the colours `m` shows itself to `out` (solid colours, gradient stops, its text's colours +/// and its mesh points; the paints a dynamic symbol instance keeps for objects of its art only +/// when `overrides` is set), and the names of the patterns it paints with to `patterns`, leaving +/// out names already there. +fn paint_colors_of(m: &Node, overrides: bool, out: &mut Vec, patterns: &mut Vec) { + let kept = override_paints(m).filter(|_| overrides); + for p in shown_paints(m).chain(kept) { + match p { + Paint::Solid { color, .. } => out.push(*color), + Paint::Gradient(g) => out.extend(g.gradient.stops.iter().map(|s| s.color)), + Paint::Pattern { pattern, .. } if !patterns.contains(pattern) => patterns.push(pattern.clone()), + _ => {} + } + } + if let NodeKind::Mesh(mesh) = &m.kind { + out.extend(mesh.points.iter().map(|p| p.color)); + } +} + +impl<'a> Theme<'a> { + /// Queue image read `r`, within the limits of a pick: at most [`MAX_THEME_READS`] reads of + /// [`MAX_THEME_IMAGES`] images; nothing inside clip groups that show nothing. + fn queue_image(&mut self, r: ImageRead<'a>) { + if self.images.len() >= MAX_THEME_READS || r.clip.as_ref().is_some_and(Vec::is_empty) { + return; + } + let key: *const vectorcraft_doc::ImageBlob = r.blob; + if !self.blobs.contains(&key) { + if self.blobs.len() >= MAX_THEME_IMAGES { + return; + } + self.blobs.insert(key); + } + self.images.push(r); + } + + /// The colours `m` paints itself ([`paint_colors_of`]; a dynamic symbol instance's paints for + /// objects of its art only with `overrides`), and the colours its pattern tiles show, read as + /// document art is read (clip groups and symbols included; the tiles' images join this pick's + /// image reads). Each pattern's colours + /// are read once; a pattern whose tile uses itself, directly or through other patterns, adds + /// nothing more the second time. + fn own(&mut self, m: &Node, overrides: bool) -> Vec { + let mut out = vec![]; + let mut patterns: Vec = vec![]; + paint_colors_of(m, overrides, &mut out, &mut patterns); + for name in patterns { + if let Some((colors, reads)) = self.pattern_colors.get(&name) { + out.extend(colors); + // The tiles' images count again for each use, within the pick's limits. + let reads = reads.clone(); + for r in reads { + self.queue_image(r); + } + continue; + } + if self.pattern_stack.contains(&name) || self.pattern_stack.len() >= MAX_THEME_DEPTH { + continue; + } + let Some(def) = self.d.pattern(&name) else { continue }; + let mut sub = Theme::new(self.d); + sub.pattern_stack = std::mem::take(&mut self.pattern_stack); + sub.pattern_stack.push(name.clone()); + sub.pattern_colors = std::mem::take(&mut self.pattern_colors); + // The tiles' images join this pick's image reads, within its limits. + sub.images = std::mem::take(&mut self.images); + sub.blobs = std::mem::take(&mut self.blobs); + // The tiles share this pick's limits on work too. + sub.work.set(self.work.get()); + sub.mask_budget = self.mask_budget; + let before = sub.images.len(); + for a in &def.art { + sub.read(a, None, 0); + } + sub.pattern_stack.pop(); + self.pattern_stack = std::mem::take(&mut sub.pattern_stack); + self.pattern_colors = std::mem::take(&mut sub.pattern_colors); + let reads: Vec> = sub.images.get(before..).unwrap_or_default().to_vec(); + self.images = std::mem::take(&mut sub.images); + self.blobs = std::mem::take(&mut sub.blobs); + self.work.set(sub.work.get()); + self.mask_budget = sub.mask_budget; + let colors: Vec = sub.samples.iter().map(|(c, _)| *c).collect(); + out.extend(&colors); + self.pattern_colors.insert(name, (colors, reads)); + } + out + } +} + +fn pick_theme(s: &mut Session, p: &Value) -> Result { + const C: &str = "recolor.pickTheme"; + let picks = match p.get("picks") { + Some(Value::Array(a)) if !a.is_empty() && a.len() <= MAX_PICKS => a.iter().map(|v| Pick::param(v, C)).collect::>>()?, + Some(Value::Array(a)) => return Err(bad(C, format!("`picks` must hold 1 to {MAX_PICKS} picks (got {})", a.len()))), + Some(v) => return Err(bad(C, format!("`picks` must be an array (got {v})"))), + None => return Err(bad(C, "missing `picks`")), + }; + let n = super::menucmds::whole_or(p, "colors", 5, C)?; + if !(1..=MAX_THEME_COLORS).contains(&n) { + return Err(bad(C, format!("`colors` must be between 1 and {MAX_THEME_COLORS} (got {n})"))); + } + let st = s.doc()?; + let d = &st.doc; + let mut theme = Theme::new(d); + theme.scope = st.isolation; + // In isolation mode: the isolated object, everything inside it and the containers around it. + let scope: Option> = st.isolation.and_then(|iso| d.node(iso)).map(|iso| { + let mut allowed = std::collections::HashSet::new(); + iso.walk(&mut |m| { + allowed.insert(m.id); + }); + let mut up = d.parent_of(iso.id); + while let Some(p) = up { + allowed.insert(p); + up = d.parent_of(p); + } + allowed + }); + for pick in picks { + match pick { + Pick::At(pt) => { + // In isolation mode only the isolated art (and the groups around it) can be hit; + // isolated Shaper Group originals are hittable then. + let opt = vectorcraft_doc::hit::HitOptions { scope: st.isolation, ..Default::default() }; + let hit = match &scope { + Some(allowed) => vectorcraft_doc::hit::hit_test_visible_skipping(d, pt, opt, &|id| !allowed.contains(&id)), + None => vectorcraft_doc::hit::hit_test_visible(d, pt, opt), + }; + if let Some(n) = hit.and_then(|h| d.node(h.top_object(st.isolation))) { + theme.read(n, None, 0); + } + } + Pick::Area(r) => match st.isolation.and_then(|iso| d.node(iso)) { + // In isolation mode a marquee reads the isolated art alone. + Some(iso) => theme.read(iso, Some(r), 0), + None => { + for l in &d.layers { + theme.read(l, Some(r), 0); + } + } + }, + } + } + theme.read_images(); + let colors = vectorcraft_color::recolor::theme_palette(&theme.samples, index(n)); + Ok(json!({"colors": colors.iter().map(key_str).collect::>(), "objects": theme.objects})) +} + /// A colour the art uses: how often, and the global swatch it is linked to. struct Used { color: Color, diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index eae92d87af..6fc8b12edc 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -40,7 +40,7 @@ pub fn specs() -> Vec { "Character", [], None, - "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes), glyphAlternate?: null (takes away the glyph choice text.setGlyphAlternate made on the characters, in the same undo step as the other attributes; any other value is refused)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes), glyphAlternate?: null (takes away the glyph choice text.setGlyphAlternate made on the characters, in the same undo step as the other attributes; any other value is refused)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_range_style ), @@ -459,6 +459,9 @@ pub(crate) struct CharChange { /// Tate-chu-yoko Settings › Up/Down and Left/Right, in points. tcy_up_down: Option, tcy_left_right: Option, + /// Insert Aki Left and Right, in 1/1000 em. + aki_left: Option, + aki_right: Option, standard_vertical_roman: Option, no_break: Option, digits: Option, @@ -492,6 +495,15 @@ pub(crate) fn tcy_offset_param(p: &Value, key: &str, cmd: &str) -> Result