From b8846ee00f78e085d910dcd569bad85712fb7a9e Mon Sep 17 00:00:00 2001 From: datatimp <12644819+datatimp@users.noreply.github.com> Date: Fri, 30 Oct 2026 21:16:40 -0400 Subject: [PATCH 001/513] Color Halftone: Max Radius in pixels of the raster effects resolution (#3260) --- crates/doc/src/halftone_radii.rs | 145 ++++++++++++++++++ crates/doc/src/lib.rs | 1 + crates/doc/src/limits.rs | 5 +- crates/effects/src/catalog.rs | 19 ++- crates/effects/src/lib.rs | 2 +- crates/effects/src/params.rs | 9 +- crates/effects/src/pixel.rs | 15 +- crates/effects/src/pixel/pixelate.rs | 7 +- crates/effects/src/pixel/tests.rs | 75 +++++---- crates/effects/src/pixel/tests_sketch.rs | 2 +- crates/effects/src/tests.rs | 25 ++- crates/engine/src/cmd/fileio/tests_pdfedit.rs | 29 ++++ crates/engine/src/cmd/fileio/tests_svgedit.rs | 2 +- crates/format/src/lib.rs | 25 +++ crates/render/src/fx/pixels.rs | 16 +- crates/render/src/fx/raster.rs | 8 +- crates/ui-egui/src/dialogs/form.rs | 10 ++ crates/ui-egui/src/dialogs/tests.rs | 72 ++++++--- crates/ui-egui/src/panels/appearance.rs | 2 + docs/effects-parity.md | 1 + docs/target-app-parity.md | 5 +- 21 files changed, 391 insertions(+), 84 deletions(-) create mode 100644 crates/doc/src/halftone_radii.rs diff --git a/crates/doc/src/halftone_radii.rs b/crates/doc/src/halftone_radii.rs new file mode 100644 index 0000000000..6c3d4544d6 --- /dev/null +++ b/crates/doc/src/halftone_radii.rs @@ -0,0 +1,145 @@ +//! Color Halftone's Max Radius was a distance in points until documents of version 2; since then +//! it is in pixels of the Document Raster Effects resolution, as public documentation gives it +//! (#3260). [`Document::migrate_halftone_radii`] converts the radii of older documents. + +use std::sync::Arc; + +use serde_json::{Value, json}; + +use crate::limits::FORMAT_VERSION; +use crate::{Appearance, Document, Effect, Node}; + +/// The first document version whose Color Halftone radii are in pixels. +const PIXEL_RADII_SINCE: u32 = 2; +const HALFTONE: &str = "pixelate.colorHalftone"; +const RADIUS: &str = "maxRadius"; +/// The radius (points) an older document's halftone without one drew with. +const OLD_DEFAULT: f64 = 8.0; +/// The range the radius was kept within in points, and is kept within in pixels. +const RANGE: std::ops::RangeInclusive = 4.0..=127.0; + +impl Document { + /// Saved before version 2: each Color Halftone's Max Radius in points becomes the pixels of + /// the document's raster effects resolution that draw the same dots, within the 4 to 127 px + /// the effect takes (a radius over 127 px, from a large radius at a high resolution, draws + /// smaller dots than before). In the art, symbols, patterns, graph designs, opacity masks and + /// graphic styles. + pub fn migrate_halftone_radii(&mut self) { + if self.version >= PIXEL_RADII_SINCE { + return; + } + self.version = FORMAT_VERSION; + let k = self.raster_ppi() / 72.0; + let fix = &mut |e: &mut Effect| to_pixels(e, k); + for l in &mut self.layers { + node(l, fix); + } + for s in &mut self.symbols { + node(&mut s.art, fix); + } + for p in &mut self.patterns { + for a in &mut p.art { + node(a, fix); + } + } + for g in &mut self.graph_designs { + node(&mut g.art, fix); + } + if self.graphic_styles.iter().any(|s| has_halftone(&s.appearance)) { + for s in self.graphic_styles.iter_mut() { + appearance(&mut s.appearance, fix); + } + } + } +} + +/// `e`'s radius in points as pixels, `k` pixels a point, when it is a Color Halftone. +fn to_pixels(e: &mut Effect, k: f64) { + if e.id != HALFTONE { + return; + } + let pt = e.params.get(RADIUS).and_then(Value::as_f64).filter(|v| v.is_finite()).unwrap_or(OLD_DEFAULT); + let px = pt.clamp(*RANGE.start(), *RANGE.end()) * k; + if !e.params.is_object() { + e.params = Value::Object(Default::default()); + } + e.params[RADIUS] = json!(px.clamp(*RANGE.start(), *RANGE.end())); +} + +fn has_halftone(a: &Appearance) -> bool { + a.effects.iter().chain(a.items.iter().flat_map(|i| i.effects())).any(|e| e.id == HALFTONE) +} + +fn appearance(a: &mut Appearance, fix: &mut dyn FnMut(&mut Effect)) { + for e in a.effects.iter_mut().chain(a.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut())) { + fix(e); + } +} + +/// Fix the effects of `n`'s subtree and its opacity masks (copying only what changes). +fn node(n: &mut Arc, fix: &mut dyn FnMut(&mut Effect)) { + let n = Arc::make_mut(n); + if has_halftone(&n.appearance) { + appearance(&mut n.appearance, fix); + } + if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) { + node(&mut m.art, fix); + } + if let Some(ch) = n.children_mut() { + for c in ch { + node(c, fix); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn halftone(radius: Option) -> Effect { + let params = radius.map_or_else(|| json!({"channel1": 108.0}), |r| json!({"maxRadius": r, "channel1": 108.0})); + Effect { id: HALFTONE.into(), params, visible: true } + } + + fn radius(e: &Effect) -> f64 { + e.params[RADIUS].as_f64().unwrap() + } + + #[test] + fn older_radii_become_the_pixels_that_draw_the_same_dots() { + for (ppi, pt, px) in [(72.0, 8.0, 8.0), (300.0, 8.0, 33.333333333333336), (300.0, 4.0, 16.666666666666668), (150.0, 127.0, 127.0)] { + let mut e = halftone(Some(pt)); + to_pixels(&mut e, ppi / 72.0); + assert!((radius(&e) - px).abs() < 1e-9, "{pt} pt at {ppi} ppi: {}", radius(&e)); + assert_eq!(e.params["channel1"], json!(108.0), "the angles stay"); + } + // A radius left out drew at the old default, 8 pt. + let mut e = halftone(None); + to_pixels(&mut e, 300.0 / 72.0); + assert!((radius(&e) - 33.333333333333336).abs() < 1e-9); + // Other effects keep their parameters. + let mut blur = Effect { id: "blur.gaussian".into(), params: json!({"radius": 8.0}), visible: true }; + to_pixels(&mut blur, 300.0 / 72.0); + assert_eq!(blur.params, json!({"radius": 8.0})); + } + + #[test] + fn only_documents_before_version_2_are_converted_once() { + let mut d = Document::new(100.0, 100.0); + d.raster_effects_ppi = 300.0; + let mut style = d.graphic_styles.first().cloned().unwrap(); + style.appearance.effects.push(halftone(Some(8.0))); + d.graphic_styles.push(style); + let fresh = d.clone(); + d.migrate_halftone_radii(); + assert_eq!(d, fresh, "a new document's radii are already pixels"); + d.version = 1; + d.migrate_halftone_radii(); + assert_eq!(d.version, FORMAT_VERSION); + let r = d.graphic_styles.last().map(|s| radius(&s.appearance.effects[0])).unwrap(); + assert!((r - 33.333333333333336).abs() < 1e-9, "{r}"); + let once = d.clone(); + d.migrate_halftone_radii(); + assert_eq!(d, once, "converted documents are left alone"); + } +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index b6a9a60efc..0b3c3f1fb2 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -16,6 +16,7 @@ pub mod corners; pub mod depth; pub mod dimension; pub mod graph; +mod halftone_radii; pub mod hit; mod id_index; pub mod inks; diff --git a/crates/doc/src/limits.rs b/crates/doc/src/limits.rs index 027148ade2..c143e545f2 100644 --- a/crates/doc/src/limits.rs +++ b/crates/doc/src/limits.rs @@ -13,7 +13,10 @@ pub enum DocError { Invalid(String), } -pub const FORMAT_VERSION: u32 = 1; +/// The version of the document model new documents are made in: 2 measures Color Halftone's Max +/// Radius in pixels of the raster effects resolution (older documents are converted on opening, +/// [`crate::Document::migrate_halftone_radii`]). +pub const FORMAT_VERSION: u32 = 2; /// Node, slice and asset ids are handed out below this: no document gets near it by counting, so /// larger ids in a file are damage (or made by hand) and the counter never follows them (#1718). diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 32e611c62a..b060bed1b4 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -43,13 +43,25 @@ pub fn is_length(id: &str, key: &str, relative: bool) -> bool { } /// The range in points that distance parameter `key` of effect `id` is kept within, as its -/// parameter documentation gives it (`{maxRadius: pt 4..127 (8), …}`); `None` when it gives none. +/// parameter documentation gives it (`{edgeWidth: pt 1..14 (2), …}`); `None` when it gives none. pub fn length_range(id: &str, key: &str) -> Option> { + documented_range(id, key, "pt") +} + +/// The range of parameter `key` of effect `id` when it is a size in pixels of the Document Raster +/// Effects resolution (`{maxRadius: px 4..127 (8), …}`), which no unit setting changes and which +/// stays in pixels when the resolution does; `None` for other parameters. +pub fn raster_px_range(id: &str, key: &str) -> Option> { + documented_range(id, key, "px") +} + +/// The range parameter `key` of effect `id` is documented with in `unit` (`key: unit lo..hi`). +fn documented_range(id: &str, key: &str, unit: &str) -> Option> { let doc = catalog_index().get(id)?.params; let starts = |at: usize| doc.get(..at).and_then(|s| s.chars().last()).is_some_and(|c| c == '{' || c == ' '); let rest = doc.match_indices(key).map(|(at, _)| at).filter(|at| starts(*at)).find_map(|at| { let rest = doc.get(at + key.len()..)?; - rest.strip_prefix(": pt ").or_else(|| rest.strip_prefix("?: pt ")) + rest.strip_prefix(": ").or_else(|| rest.strip_prefix("?: "))?.strip_prefix(unit)?.strip_prefix(' ') })?; let (lo, hi) = rest.split_whitespace().next()?.split_once("..")?; let (lo, hi) = (lo.parse::().ok()?, hi.trim_end_matches(',').parse::().ok()?); @@ -81,7 +93,6 @@ fn lengths_of(id: &str) -> Lengths { "brushStrokes.spatter" => always(&["sprayRadius"]), "brushStrokes.sprayedStrokes" => always(&["strokeLength", "sprayRadius"]), "brushStrokes.sumiE" => always(&["strokeWidth"]), - "pixelate.colorHalftone" => always(&["maxRadius"]), "pixelate.crystallize" | "pixelate.pointillize" => always(&["cellSize"]), "texture.craquelure" => always(&["crackSpacing"]), "texture.mosaicTiles" => always(&["tileSize"]), @@ -633,7 +644,7 @@ pub fn effect_catalog() -> Vec { "pixelate.colorHalftone", "Color Halftone…", PIXELATE, - "{maxRadius: pt 4..127 (8; the radius of a dot at full strength, which fills its square cell), channel1: screen angle deg -360..360 (108), channel2: deg (162), channel3: deg (90), channel4: deg (45)} screens each colour channel (red, green, blue: channels 1 to 3; in CMYK documents cyan, magenta, yellow, black: 1 to 4) at its angle into dots whose area follows the channel's mean over their cell", + "{maxRadius: px 4..127 (8; the radius of a dot at full strength, which fills its square cell, in pixels of the Document Raster Effects resolution), channel1: screen angle deg -360..360 (108), channel2: deg (162), channel3: deg (90), channel4: deg (45)} screens each colour channel (red, green, blue: channels 1 to 3; in CMYK documents cyan, magenta, yellow, black: 1 to 4) at its angle into dots whose area follows the channel's mean over their cell", json!({"maxRadius": 8.0, "channel1": 108.0, "channel2": 162.0, "channel3": 90.0, "channel4": 45.0}), ), r( diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index b15a642c3d..c080784c8a 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -95,7 +95,7 @@ mod catalog; mod geometry; mod params; -pub use catalog::{EffectInfo, Lengths, WARP_STYLES, effect_catalog, effect_info, is_length, length_range, plugin_effects}; +pub use catalog::{EffectInfo, Lengths, WARP_STYLES, effect_catalog, effect_info, is_length, length_range, plugin_effects, raster_px_range}; pub(crate) use geometry::{Budget, apply_one}; pub use geometry::{GeomContext, apply_geometry, apply_geometry_bez, apply_geometry_with}; #[cfg(test)] diff --git a/crates/effects/src/params.rs b/crates/effects/src/params.rs index d64ac7b780..e4b478423f 100644 --- a/crates/effects/src/params.rs +++ b/crates/effects/src/params.rs @@ -95,13 +95,16 @@ pub fn new_effect(id: &str, params: &Value) -> Option { } /// Scale the distance parameters of `e` by `s` (Scale Strokes & Effects; see -/// [`EffectInfo::lengths`]). A distance left at its default is written out scaled; one the -/// effect doesn't have (Outline Stroke's weight following its stroke) stays absent. +/// [`EffectInfo::lengths`]), and its sizes in raster pixels ([`crate::raster_px_range`]), which +/// keep their share of the object so. A distance left at its default is written out scaled; one +/// the effect doesn't have (Outline Stroke's weight following its stroke) stays absent. pub fn scale_effect(e: &mut Effect, s: f64) { let Some(info) = catalog_index().get(e.id.as_str()) else { return }; let merged = merged_params(&e.id, &e.params); let relative = util::flag(&merged, "relative", false); - for k in info.lengths.keys(relative) { + let mut keys: Vec<&str> = info.lengths.keys(relative).collect(); + keys.extend(merged.as_object().into_iter().flat_map(|m| m.keys()).map(String::as_str).filter(|k| crate::raster_px_range(&e.id, k).is_some())); + for k in keys { let v = util::num(&merged, k, f64::NAN); if v.is_finite() { if !e.params.is_object() { diff --git a/crates/effects/src/pixel.rs b/crates/effects/src/pixel.rs index 8885c9def4..2a122bb664 100644 --- a/crates/effects/src/pixel.rs +++ b/crates/effects/src/pixel.rs @@ -254,7 +254,8 @@ pub enum PixelFx { /// Stylize › Glowing Edges: bright coloured Sobel outlines on black. GlowingEdges { width: f64, brightness: f64, smoothness: f64 }, /// Pixelate › Color Halftone: each colour channel screened at its angle (`angles`° of channels - /// 1 to 4) into dots of up to `max_radius`, whose area follows the channel's strength. + /// 1 to 4) into dots of up to `max_radius` pixels of the Document Raster Effects resolution + /// ([`PixelSpace::line`] each), whose area follows the channel's strength. ColorHalftone { max_radius: f64, angles: [f64; 4] }, /// Pixelate › Crystallize: polygons of solid colour around random points about `cell` apart. Crystallize { cell: f64 }, @@ -668,9 +669,10 @@ impl PixelFx { } } - /// How far (document units) from a pixel the content that decides it lies; `None` when that - /// is anywhere in the object (Radial Blur). - pub fn reach(&self) -> Option { + /// How far (document units) from a pixel the content that decides it lies, with lines of the + /// raster grid `line` apart ([`PixelSpace::line`]); `None` when that is anywhere in the object + /// (Radial Blur). + pub fn reach(&self, line: f64) -> Option { match *self { PixelFx::RadialBlur { .. } => None, PixelFx::SmartBlur { radius, mode: SmartBlurMode::Normal, .. } => Some(radius), @@ -703,7 +705,10 @@ impl PixelFx { PixelFx::Stamp { smoothness, .. } => Some(sketch_ink::stamp_reach(smoothness)), PixelFx::GlowingEdges { width, smoothness, .. } => Some(width.max(smoothness * 3.0)), // The cells around the pixel's, and the cells around theirs. - PixelFx::ColorHalftone { max_radius, .. } => Some(3.0 * std::f64::consts::SQRT_2 * max_radius), + // (Without a usable grid there are no dots: see `pixelate::color_halftone`.) + PixelFx::ColorHalftone { max_radius, .. } => { + Some(3.0 * std::f64::consts::SQRT_2 * max_radius * line).filter(|d| d.is_finite()).or(Some(0.0)) + } PixelFx::Crystallize { cell } => Some(1.5 * cell), PixelFx::ColoredPencil { width, .. } => Some(artistic::colored_pencil_reach(width)), PixelFx::ChalkCharcoal { .. } => Some(sketch::CHALK_CHARCOAL_REACH), diff --git a/crates/effects/src/pixel/pixelate.rs b/crates/effects/src/pixel/pixelate.rs index e9997b0cf3..0318eb5f45 100644 --- a/crates/effects/src/pixel/pixelate.rs +++ b/crates/effects/src/pixel/pixelate.rs @@ -436,11 +436,12 @@ impl Screen { } /// Color Halftone: each channel screened at its angle in square cells sized so that a dot of -/// `max_radius` fills one; each cell's dot covers the share of it that is the channel's mean -/// there (white stays white, black black). Coverage stays as it is. +/// `max_radius` (pixels of the document's raster grid, `space.line` each) fills one; each cell's +/// dot covers the share of it that is the channel's mean there (white stays white, black black). +/// Coverage stays as it is. pub(super) fn color_halftone(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, max_radius: f64, angles: [f64; 4]) { let Some(place) = Place::new(space, w, h) else { return }; - let side = max_radius * std::f64::consts::SQRT_2; + let side = max_radius * space.line * std::f64::consts::SQRT_2; // Cells under 3 pixels can't show their dots: on average a screen is the image itself. if !(side.is_finite() && side / place.px >= 3.0) { return; diff --git a/crates/effects/src/pixel/tests.rs b/crates/effects/src/pixel/tests.rs index ef4d9d7abf..8261d408a1 100644 --- a/crates/effects/src/pixel/tests.rs +++ b/crates/effects/src/pixel/tests.rs @@ -80,7 +80,7 @@ fn film_grain_parameters_are_bounded_and_neutral_settings_preserve_the_art() { neutral.apply(&mut out, w, h, &space(w, h)); assert_eq!(out, src); assert_eq!(neutral.outset(Rect::new(0.0, 0.0, w as f64, h as f64)), 0.0); - assert_eq!(neutral.reach(), Some(0.0)); + assert_eq!(neutral.reach(1.0), Some(0.0)); } #[test] @@ -520,12 +520,12 @@ fn outsets_follow_the_object() { assert!((spin.outset(b) - (far - 25.0)).abs() < 1e-9); assert!(fx("blur.radial", json!({"method": "zoom", "amount": 100})).outset(b) > 0.4 * far); assert_eq!(fx("blur.smart", json!({"radius": 4})).outset(b), 4.0); - assert_eq!(fx("blur.smart", json!({"radius": 4})).reach(), Some(4.0)); + assert_eq!(fx("blur.smart", json!({"radius": 4})).reach(1.0), Some(4.0)); // The edge modes also read the copy blurred over a wide radius's samples. - assert_eq!(fx("blur.smart", json!({"radius": 4, "quality": "low", "blurMode": "edgeOnly"})).reach(), Some(5.0)); + assert_eq!(fx("blur.smart", json!({"radius": 4, "quality": "low", "blurMode": "edgeOnly"})).reach(1.0), Some(5.0)); assert_eq!(fx("sharpen.unsharpMask", json!({})).outset(b), 0.0); - assert_eq!(spin.reach(), None); - assert_eq!(fx("sharpen.unsharpMask", json!({"radius": 2})).reach(), Some(6.0)); + assert_eq!(spin.reach(1.0), None); + assert_eq!(fx("sharpen.unsharpMask", json!({"radius": 2})).reach(1.0), Some(6.0)); } #[test] @@ -962,7 +962,7 @@ fn pixelate_params_take_defaults_and_stay_in_range() { assert_eq!(fx("pixelate.crystallize", json!({"cellSize": 20})).outset(b), 30.0); assert_eq!(fx("pixelate.pointillize", json!({"cellSize": 20})).outset(b), 30.0); assert_eq!(fx("pixelate.colorHalftone", json!({})).outset(b), 0.0); - assert_eq!(fx("pixelate.mezzotint", json!({})).reach(), Some(0.0)); + assert_eq!(fx("pixelate.mezzotint", json!({})).reach(1.0), Some(0.0)); } /// Fraction of `d`'s pixels for which `f` holds. @@ -1002,6 +1002,25 @@ fn color_halftone_screens_midtones_into_dots_and_keeps_white_and_black() { assert!(lit(8) < lit(40), "{} < {}", lit(8), lit(40)); } +#[test] +fn color_halftone_sizes_its_dots_in_pixels_of_the_raster_effects_resolution() { + // Max Radius counts the document's raster grid pixels (#3260): 16 px at 144 ppi (lines half a + // point apart) are the 8 px of 72 ppi, and draw the same dots. + let (w, h) = (64, 64); + let src = image(w, h, |x, y| [(x * 4) as u8, (y * 4) as u8, 128, 255]); + let run = |radius: f64, line: f64| { + let mut d = src.clone(); + fx("pixelate.colorHalftone", json!({"maxRadius": radius})).apply(&mut d, w, h, &PixelSpace { line, ..space(w, h) }); + d + }; + assert_eq!(run(16.0, 0.5), run(8.0, 1.0)); + assert_ne!(run(8.0, 0.5), run(8.0, 1.0), "the same radius at a finer resolution draws finer dots"); + // It looks as far around a pixel as its cells reach, in document units. + let halftone = fx("pixelate.colorHalftone", json!({"maxRadius": 8})); + assert_eq!(halftone.reach(0.5), Some(3.0 * std::f64::consts::SQRT_2 * 4.0)); + assert_eq!(halftone.reach(f64::NAN), Some(0.0), "no grid, no dots"); +} + #[test] fn color_halftone_screens_inks_in_cmyk_documents() { let (w, h) = (64, 64); @@ -1241,8 +1260,8 @@ fn texture_params_take_defaults_and_stay_in_range() { for id in ["texture.craquelure", "texture.grain", "texture.mosaicTiles", "texture.texturizer"] { assert_eq!(fx(id, json!({})).outset(b), 0.0, "{id}"); } - assert_eq!(fx("texture.grain", json!({})).reach(), Some(0.0)); - assert_eq!(fx("texture.craquelure", json!({"crackSpacing": 12})).reach(), Some(6.0)); + assert_eq!(fx("texture.grain", json!({})).reach(1.0), Some(0.0)); + assert_eq!(fx("texture.craquelure", json!({"crackSpacing": 12})).reach(1.0), Some(6.0)); } /// The pixels of `d` (`w` wide) in the square `lo..hi` on both axes. @@ -1509,9 +1528,9 @@ fn distort_params_take_defaults_and_stay_in_range() { // Shifted content reaches past the bounds by the longest shift, and comes from as far. let b = Rect::new(0.0, 0.0, 100.0, 50.0); let glass = fx("distort.glass", json!({"distortion": 20})); - assert_eq!((glass.outset(b), glass.reach()), (10.0, Some(10.0))); + assert_eq!((glass.outset(b), glass.reach(1.0)), (10.0, Some(10.0))); let ripple = fx("distort.oceanRipple", json!({})); - assert!((ripple.outset(b) - 0.03 * 9.0 * 11.0).abs() < 1e-9 && ripple.reach() == Some(ripple.outset(b))); + assert!((ripple.outset(b) - 0.03 * 9.0 * 11.0).abs() < 1e-9 && ripple.reach(1.0) == Some(ripple.outset(b))); assert_eq!(fx("distort.diffuseGlow", json!({})).outset(b), 0.0); } @@ -1621,7 +1640,7 @@ fn ocean_ripple_moves_content_no_farther_than_its_magnitude() { fx("distort.oceanRipple", json!({"rippleMagnitude": 0})).apply(&mut d, w, h, &space(w, h)); assert_eq!(d, src, "no magnitude, no ripples"); let f = fx("distort.oceanRipple", json!({"rippleSize": 6, "rippleMagnitude": 20})); - let most = f.reach().unwrap(); + let most = f.reach(1.0).unwrap(); let mut d = src.clone(); f.apply(&mut d, w, h, &space(w, h)); assert_ne!(d, src); @@ -1765,19 +1784,19 @@ fn brush_strokes_outsets() { let reach = brushstrokes::stroke_reach; assert!((reach(20.0) - (0.75 * 20.0 + 1.5 / 15.0 * 20.0 + 1.0)).abs() < 1e-9); assert_eq!(fx("brushStrokes.accentedEdges", json!({})).outset(b), 0.0); - assert_eq!(fx("brushStrokes.accentedEdges", json!({})).reach(), Some(3.0 * (0.35 * 2.0 + 0.5) + 1.0)); + assert_eq!(fx("brushStrokes.accentedEdges", json!({})).reach(1.0), Some(3.0 * (0.35 * 2.0 + 0.5) + 1.0)); assert_eq!(fx("brushStrokes.angledStrokes", json!({})).outset(b), reach(15.0)); assert_eq!(fx("brushStrokes.crosshatch", json!({})).outset(b), reach(9.0) + 0.9); assert_eq!(fx("brushStrokes.darkStrokes", json!({})).outset(b), reach(9.0)); assert_eq!(fx("brushStrokes.inkOutlines", json!({"strokeLength": 50})).outset(b), reach(50.0)); let spatter = fx("brushStrokes.spatter", json!({})); - assert_eq!((spatter.outset(b), spatter.reach()), (4.0, Some(4.0))); + assert_eq!((spatter.outset(b), spatter.reach(1.0)), (4.0, Some(4.0))); assert_eq!(fx("brushStrokes.spatter", json!({"sprayRadius": 0})).outset(b), 0.0); assert_eq!(fx("brushStrokes.sprayedStrokes", json!({})).outset(b), reach(12.0) + 0.3 * 7.0); assert_eq!(fx("brushStrokes.sumiE", json!({})).outset(b), 0.0); for id in brush_strokes() { let f = fx(id, json!({})); - assert!(f.reach().is_some_and(|r| r >= f.outset(b)), "{id}"); + assert!(f.reach(1.0).is_some_and(|r| r >= f.outset(b)), "{id}"); } } @@ -1961,7 +1980,7 @@ fn spatter_scatters_content_no_farther_than_its_radius() { let src = image(w, h, |x, _| if x < 32 { grey(255) } else { [0; 4] }); assert_eq!(run_fx(&src, w, h, "brushStrokes.spatter", json!({"sprayRadius": 0})), src, "no radius, no spatter"); let f = fx("brushStrokes.spatter", json!({"sprayRadius": 15})); - let most = f.reach().unwrap(); + let most = f.reach(1.0).unwrap(); let d = run_fx(&src, w, h, "brushStrokes.spatter", json!({"sprayRadius": 15})); assert_ne!(d, src); let inside = |v: usize, n: usize| (v as f64 + 0.5).min(n as f64 - v as f64 - 0.5) > most + 1.0; @@ -1990,7 +2009,7 @@ fn brush_strokes_look_no_farther_than_their_reach() { ("brushStrokes.sumiE", json!({"strokeWidth": 15})), ]); for (id, p) in cases { - let reach = fx(id, p.clone()).reach().unwrap(); + let reach = fx(id, p.clone()).reach(1.0).unwrap(); // Everything from `cut` on differs; the pixels left of 20 can't tell. let cut = 20 + reach.ceil() as usize + 1; assert!(cut < w, "{id}"); @@ -2047,7 +2066,7 @@ fn chalk_charcoal_params_take_defaults_and_stay_in_range() { assert!(doc.contains("chalkArea") && doc.contains("charcoalArea") && doc.contains("strokePressure"), "{doc}"); let f = fx("sketch.chalkCharcoal", json!({"strokePressure": 5})); assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), 0.0); - assert!(f.reach().unwrap() > 0.0); + assert!(f.reach(1.0).unwrap() > 0.0); } #[test] @@ -2108,7 +2127,7 @@ fn graphic_pen_params_take_defaults_and_stay_in_range() { assert!(STROKE_DIRECTIONS.iter().all(|(_, v)| doc.contains(&format!("\"{v}\""))), "{doc}"); let f = fx("sketch.graphicPen", json!({"strokeLength": 15})); assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), brushstrokes::stroke_reach(15.0)); - assert_eq!(f.reach(), Some(brushstrokes::stroke_reach(15.0).max(brushstrokes::TONE_REACH))); + assert_eq!(f.reach(1.0), Some(brushstrokes::stroke_reach(15.0).max(brushstrokes::TONE_REACH))); assert_eq!( fx("sketch.graphicPen", json!({"strokeLength": 99})), PixelFx::GraphicPen { length: 15.0, balance: 50.0, direction: StrokeDirection::RightDiagonal } @@ -2148,7 +2167,7 @@ fn halftone_pattern_params_take_defaults_and_stay_in_range() { assert!(HALFTONE_TYPES.iter().all(|(_, v)| doc.contains(&format!("\"{v}\""))), "{doc}"); let f = fx("sketch.halftonePattern", json!({"size": 12})); assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), 0.0); - assert_eq!(f.reach(), Some(0.0)); + assert_eq!(f.reach(1.0), Some(0.0)); } #[test] @@ -2162,7 +2181,7 @@ fn note_paper_params_take_defaults_and_stay_in_range() { assert!(doc.contains("imageBalance") && doc.contains("graininess") && doc.contains("relief"), "{doc}"); let f = fx("sketch.notePaper", json!({"relief": 12})); assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), 0.0); - assert_eq!(f.reach(), Some(0.0)); + assert_eq!(f.reach(1.0), Some(0.0)); } /// Note Paper embosses a horizontal gradient and graininess adds fibre. @@ -2198,7 +2217,7 @@ fn water_paper_params_take_defaults_and_stay_in_range() { ); let f = fx("sketch.waterPaper", json!({"fiberLength": 40})); assert!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)) > 0.0); - assert!(f.reach().unwrap_or(0.0) > 0.0); + assert!(f.reach(1.0).unwrap_or(0.0) > 0.0); let doc = crate::effect_info("sketch.waterPaper").unwrap().params; assert!(doc.contains("unverified"), "{doc}"); } @@ -2281,7 +2300,7 @@ fn plaster_params_take_defaults_and_stay_in_range() { let doc = crate::effect_info("sketch.plaster").unwrap().params; assert!(doc.contains("\"bottomRight\""), "{doc}"); let f = fx("sketch.plaster", json!({"smoothness": 24})); - assert_eq!(f.reach(), Some(super::sketch::plaster_reach(15.0))); + assert_eq!(f.reach(1.0), Some(super::sketch::plaster_reach(15.0))); } /// Plaster changes the image and different light directions give different results. @@ -2356,8 +2375,8 @@ fn chrome_params_take_defaults_and_stay_in_range() { assert!(doc.contains("detail") && doc.contains("smoothness"), "{doc}"); let f = fx("sketch.chrome", json!({})); assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), 0.0); - assert_eq!(f.reach(), Some(sketch::chrome_reach(4.0))); - assert_eq!(fx("sketch.chrome", json!({"smoothness": 10})).reach(), Some(sketch::chrome_reach(10.0))); + assert_eq!(f.reach(1.0), Some(sketch::chrome_reach(4.0))); + assert_eq!(fx("sketch.chrome", json!({"smoothness": 10})).reach(1.0), Some(sketch::chrome_reach(10.0))); } /// Chrome redraws in greyscale, keeps coverage, and more detail changes the pattern. @@ -2389,7 +2408,7 @@ fn reticulation_params_take_defaults_and_stay_in_range() { ); let f = fx("sketch.reticulation", json!({})); assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), 0.0); - assert_eq!(f.reach(), Some(0.0)); + assert_eq!(f.reach(1.0), Some(0.0)); } #[test] @@ -2431,7 +2450,7 @@ fn torn_edges_params_take_defaults_and_stay_in_range() { for junk in [json!({"imageBalance": "x"}), json!({"smoothness": null})] { assert_eq!(fx("sketch.tornEdges", junk), fx("sketch.tornEdges", json!({}))); } - assert_eq!(fx("sketch.tornEdges", json!({})).reach(), None); + assert_eq!(fx("sketch.tornEdges", json!({})).reach(1.0), None); } #[test] @@ -2496,7 +2515,7 @@ fn artistic_params_take_defaults_and_stay_in_range() { fx("artistic.coloredPencil", json!({"pencilWidth": 0, "strokePressure": 200, "paperBrightness": -5})), PixelFx::ColoredPencil { width: 1.0, pressure: 15.0, paper: 0.0 } ); - assert_eq!(fx("artistic.coloredPencil", json!({})).reach(), Some(artistic::colored_pencil_reach(5.0))); + assert_eq!(fx("artistic.coloredPencil", json!({})).reach(1.0), Some(artistic::colored_pencil_reach(5.0))); assert_eq!(fx("artistic.cutout", json!({})), PixelFx::Cutout { levels: 4.0, simplicity: 4.0, fidelity: 2.0 }); assert_eq!( fx("artistic.cutout", json!({"levels": 1e308, "edgeSimplicity": -5, "edgeFidelity": "NaN"})), @@ -2860,7 +2879,7 @@ fn dry_brush_repaints_and_preserves_coverage() { let before = clear.clone(); fx("artistic.dryBrush", json!({})).apply(&mut clear, w, h, &space(w, h)); assert_eq!(clear, before); - let reach = fx("artistic.dryBrush", json!({"brushSize": 10, "brushDetail": 1})).reach(); + let reach = fx("artistic.dryBrush", json!({"brushSize": 10, "brushDetail": 1})).reach(1.0); assert!(reach.is_some_and(|r| r > 0.0)); } diff --git a/crates/effects/src/pixel/tests_sketch.rs b/crates/effects/src/pixel/tests_sketch.rs index 2f463f52f6..fd467a23ca 100644 --- a/crates/effects/src/pixel/tests_sketch.rs +++ b/crates/effects/src/pixel/tests_sketch.rs @@ -176,7 +176,7 @@ fn sketch_filters_reach_beyond_nothing_they_do_not_paint() { for id in ["sketch.basRelief", "sketch.charcoal", "sketch.conteCrayon", "sketch.photocopy", "sketch.stamp"] { let f = fx(id, json!({})); assert_eq!(f.outset(Rect::new(0.0, 0.0, 50.0, 50.0)), 0.0, "{id} keeps the object's coverage"); - assert!(f.reach().is_some_and(|r| r.is_finite() && r > 0.0), "{id} reach"); + assert!(f.reach(1.0).is_some_and(|r| r.is_finite() && r > 0.0), "{id} reach"); } } diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index 198da329e8..fba045763e 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -1210,14 +1210,29 @@ fn a_repeat_of_a_symbol_whose_art_is_a_repeat_shares_the_instance_budget() { #[test] fn a_distance_parameters_range_comes_from_its_documentation() { - assert_eq!(length_range("pixelate.colorHalftone", "maxRadius"), Some(4.0..=127.0)); + assert_eq!(length_range("stylize.glowingEdges", "edgeWidth"), Some(1.0..=14.0)); + // A distance documented without a range, and unknown effects and parameters, have none. + assert_eq!(length_range("path.offsetPath", "offset"), None); + assert_eq!(length_range("stylize.glowingEdges", "edgeBrightness"), None); + assert_eq!(length_range("no.such", "edgeWidth"), None); +} + +#[test] +fn color_halftones_radius_is_in_raster_pixels_not_a_distance() { + // Pixels of the Document Raster Effects resolution, as public documentation gives it (#3260): + // no unit setting changes it, so it isn't a distance in points. + assert_eq!(raster_px_range("pixelate.colorHalftone", "maxRadius"), Some(4.0..=127.0)); + assert!(!is_length("pixelate.colorHalftone", "maxRadius", false)); + assert_eq!(length_range("pixelate.colorHalftone", "maxRadius"), None); + assert_eq!(raster_px_range("pixelate.colorHalftone", "channel1"), None); + assert_eq!(raster_px_range("stylize.glowingEdges", "edgeWidth"), None); // The effect applies the range's floor to a radius below it. assert_eq!( crate::pixel::parse("pixelate.colorHalftone", &json!({"maxRadius": 1})), crate::pixel::parse("pixelate.colorHalftone", &json!({"maxRadius": 4})) ); - // A distance documented without a range, and unknown effects and parameters, have none. - assert_eq!(length_range("path.offsetPath", "offset"), None); - assert_eq!(length_range("pixelate.colorHalftone", "channel1"), None); - assert_eq!(length_range("no.such", "maxRadius"), None); + // Scale Strokes & Effects scales it with the object, as it does distances. + let mut e = crate::new_effect("pixelate.colorHalftone", &json!({"maxRadius": 10})).unwrap(); + crate::scale_effect(&mut e, 2.0); + assert_eq!((e.params["maxRadius"].as_f64(), e.params["channel1"].as_f64()), (Some(20.0), Some(108.0))); } diff --git a/crates/engine/src/cmd/fileio/tests_pdfedit.rs b/crates/engine/src/cmd/fileio/tests_pdfedit.rs index 35d3945402..597f67a03c 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfedit.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfedit.rs @@ -403,3 +403,32 @@ fn ai_export_without_artboards_keeps_art_outside_the_original_pages() { assert_eq!(comparable(&s.doc().unwrap().doc), before); assert!(s.execute("document.export", &json!({"format": "ai", "useArtboards": "yes"})).is_err()); } + +/// Color Halftone's Max Radius is in pixels of the raster effects resolution since document +/// version 2 (#3260). A PDF saved with Preserve Editing carries the native document, so one from +/// before that opens with the radius converted, drawing the same dots; one saved since opens as +/// it was. +#[test] +fn a_preserve_editing_pdf_opens_with_its_halftone_radius_in_pixels() { + let halftone = |old: bool| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 200})).unwrap(); + s.execute("document.rasterEffectsSettings", &json!({"resolution": 300})).unwrap(); + let r = super::tests_svgedit::rect(&mut s, 10.0, 10.0); + s.execute("effect.apply", &json!({"effect": "pixelate.colorHalftone", "params": {"maxRadius": 8}, "ids": [r]})).unwrap(); + if old { + // As VectorCraft 0.18 wrote it: the document model's version 1, the radius in points. + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).version = 1; + } + let pdf = b64(&s.execute("document.exportPdf", &json!({})).unwrap()); + let opened = open(&mut s, "halftone.pdf", &pdf); + assert_eq!(opened["restored"], json!(true), "{opened}"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.version, vectorcraft_doc::FORMAT_VERSION); + let n = d.node(vectorcraft_doc::NodeId(r)).unwrap(); + n.appearance.effects.iter().find(|e| e.id == "pixelate.colorHalftone").and_then(|e| e.params["maxRadius"].as_f64()).unwrap() + }; + // 8 pt at 300 ppi are 33⅓ px. + assert!((halftone(true) - 8.0 * 300.0 / 72.0).abs() < 1e-9, "{}", halftone(true)); + assert_eq!(halftone(false), 8.0); +} diff --git a/crates/engine/src/cmd/fileio/tests_svgedit.rs b/crates/engine/src/cmd/fileio/tests_svgedit.rs index 06f9888469..4b0998c643 100644 --- a/crates/engine/src/cmd/fileio/tests_svgedit.rs +++ b/crates/engine/src/cmd/fileio/tests_svgedit.rs @@ -12,7 +12,7 @@ fn new_id(v: &Value) -> u64 { v["id"].as_u64().or_else(|| v["ids"][0].as_u64()).unwrap_or_else(|| panic!("no id in {v}")) } -fn rect(s: &mut Session, x: f64, y: f64) -> u64 { +pub(super) fn rect(s: &mut Session, x: f64, y: f64) -> u64 { new_id(&s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": 20, "height": 20})).unwrap()) } diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index ad9df39ffd..d9fb08c0bb 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -607,6 +607,8 @@ fn load_file_within(bytes: &[u8], max_nodes: usize, max_values: usize) -> Result doc.migrate_overprint_black(); // Saved before v3: the assigned profiles move out of `unknown`. doc.migrate_color_profiles(); + // A document before version 2: Color Halftone's Max Radius in points becomes pixels (#3260). + doc.migrate_halftone_radii(); doc.fix_next_id(); // Untrusted: the bleed and type proportions, within the ranges Document Setup takes. doc.setup.keep_in_range(); @@ -781,6 +783,29 @@ mod tests { use vectorcraft_doc::{Appearance, ImageObject, Node, NodeKind}; use vectorcraft_geom::{Affine, Rect, shapes}; + /// Color Halftone's Max Radius is in pixels of the raster effects resolution since document + /// version 2 (#3260): a file from before opens with its radius in points converted, one saved + /// since opens as it was. + #[test] + fn halftone_radii_of_older_documents_open_in_pixels() { + let mut d = Document::new(100.0, 100.0); + d.raster_effects_ppi = 300.0; + let (l, id) = (d.layers[0].id, d.alloc_id()); + let mut look = Appearance::default_art(); + look.effects.push(vectorcraft_doc::Effect { + id: "pixelate.colorHalftone".into(), + params: serde_json::json!({"maxRadius": 8.0}), + visible: true, + }); + d.insert(Some(l), 0, Node::path(id, shapes::ellipse(Rect::new(0.0, 0.0, 10.0, 10.0)), look)).unwrap(); + let radius = |d: &Document| d.node(id).unwrap().appearance.effects[0].params["maxRadius"].as_f64().unwrap(); + assert_eq!(radius(&load(&save(&d, false)).unwrap()), 8.0, "saved in pixels, opened in pixels"); + d.version = 1; + let old = load(&save(&d, false)).unwrap(); + assert_eq!(old.version, vectorcraft_doc::FORMAT_VERSION); + assert!((radius(&old) - 8.0 * 300.0 / 72.0).abs() < 1e-9, "8 pt at 300 ppi: {}", radius(&old)); + } + #[test] fn roundtrip() { let mut d = Document::new(100.0, 100.0); diff --git a/crates/render/src/fx/pixels.rs b/crates/render/src/fx/pixels.rs index 900e435bc8..5fc706a303 100644 --- a/crates/render/src/fx/pixels.rs +++ b/crates/render/src/fx/pixels.rs @@ -66,7 +66,11 @@ impl Renderer { } let fits = full.area() <= PIXEL_BUDGET; // Device pixels from a pixel to the content deciding it (`None`: anywhere). - let margin = chain.iter().try_fold(2.0, |m, fx| looks_around(fx).map(|d| m + d / f.px)); + // De-Interlace's field lines and Color Halftone's pixels: the rows of the document's + // raster grid (1 to 2400 ppi). + let ppi = doc_raster_ppi(f.doc); + let line = 72.0 / ppi; + let margin = chain.iter().try_fold(2.0, |m, fx| looks_around(fx, line).map(|d| m + d / f.px)); let linear = linear_key(f.view); let key = content.cache.map(|slot| (content.node as *const Node as usize, slot, f.ink)); // Made again at this zoom and rotation (after a pan), a raster cropped to the view covers a @@ -100,13 +104,14 @@ impl Renderer { Ink::Display | Ink::RichBlack if f.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk => effects::pixel::Channels::Cmyk, _ => effects::pixel::Channels::Rgb, }; - // De-Interlace's field lines: the rows of the document's raster grid (1 to 2400 ppi). - let ppi = doc_raster_ppi(f.doc); // What the content reads (as the raster kept for it found it, else found now), with the - // channels the effects run on and, under De-Interlace or Rasterize, the resolution. + // channels the effects run on and, under De-Interlace, Color Halftone (its dots are sized + // in the grid's pixels) or Rasterize, the resolution. let inputs = key.map(|key| { let reads = self.pixel_fx.get(&key).filter(|e| e.node.is(content.node)).map_or_else(|| Reads::of(content.node), |e| e.inputs.reads); - let interlaced = chain.iter().any(|fx| matches!(fx, RasterFx::Pixel(PixelFx::DeInterlace { .. }) | RasterFx::Rasterize(_))); + let interlaced = chain + .iter() + .any(|fx| matches!(fx, RasterFx::Pixel(PixelFx::DeInterlace { .. } | PixelFx::ColorHalftone { .. }) | RasterFx::Rasterize(_))); self.raster_inputs(f, content.node, reads).with((std::mem::discriminant(&channels), interlaced.then_some(ppi.to_bits()))) }); let interacting = f.opts.interacting; @@ -149,7 +154,6 @@ impl Renderer { let to_doc = view.inverse(); let px = f.px / k; let frame = Frame { mt: false, view, visible: to_doc.transform_rect_bbox(Rect::new(0.0, 0.0, w, h)), px, ..*f }; - let line = 72.0 / ppi; let (before, decoded) = (self.stats.moved, crate::paint::decode_failures()); // A Rasterize first in the chain draws the content on its image's own grid instead, unless // that image is too large: the content is drawn once. diff --git a/crates/render/src/fx/raster.rs b/crates/render/src/fx/raster.rs index ca6a2fd375..5f44cd50bf 100644 --- a/crates/render/src/fx/raster.rs +++ b/crates/render/src/fx/raster.rs @@ -70,12 +70,12 @@ pub(super) fn hard_edged(chain: &[&RasterFx], px: f64) -> bool { matches!(chain.first(), Some(RasterFx::Rasterize(r)) if !r.anti_alias && r.cell(72.0) >= px) } -/// How far (document units) from a pixel the content deciding it after `fx` lies; `None` when -/// anywhere in the object. -pub(super) fn looks_around(fx: &RasterFx) -> Option { +/// How far (document units) from a pixel the content deciding it after `fx` lies, with the +/// document's raster grid lines `line` apart; `None` when anywhere in the object. +pub(super) fn looks_around(fx: &RasterFx, line: f64) -> Option { match fx { RasterFx::Feather { radius } | RasterFx::GaussianBlur { radius } => Some(1.5 * radius), - RasterFx::Pixel(p) => p.reach(), + RasterFx::Pixel(p) => p.reach(line), RasterFx::Rasterize(r) => Some(r.reach()), _ => Some(0.0), } diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index ce456fb26d..bb2c187f93 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -384,6 +384,16 @@ pub(super) fn param_fields( changed |= length_within(ui, d, &k, unit, 140.0, range); return; } + // A size in pixels of the raster effects resolution (Color Halftone's Max Radius) + // stays in pixels whatever the document's units, within its documented range. + if let Some(range) = vectorcraft_effects::raster_px_range(&d.str("__effect"), &k) { + let x = v.as_f64().unwrap_or(*range.start()); + if let Some(x) = crate::widgets::range_field_named(ui, ("fx-px", &k), None, x, range, &unit_suffix("px"), 2, 140.0) { + d.fields.insert(k.clone(), typed_number(x)); + changed = true; + } + return; + } if let Some(options) = choices(&k) { let cur = v.as_str().unwrap_or_default(); let label = options.iter().find(|(_, value)| *value == cur).map_or(cur, |(l, _)| choice_label(l)); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index d4b6698a8b..6585015593 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -2488,11 +2488,11 @@ fn artboard_options_selected_fit_spans_other_boards_and_off_board_art() { } /// An effect dialog keeps a distance typed outside the effect's range to the range, so the field -/// shows what the effect applies: Color Halftone's Max Radius below 4 pt is 4 pt (#4637). +/// shows what the effect applies: Crystallize's Cell Size below 3 pt is 3 pt (#4637). #[test] fn an_effect_dialog_keeps_a_typed_distance_within_the_effects_range() { let enter = || egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; - for (typed, applied) in [("1 pt", 4.0), ("0.5 px", 4.0), ("200 pt", 127.0), ("10 pt", 10.0)] { + for (typed, applied) in [("1 pt", 3.0), ("0.5 px", 3.0), ("400 pt", 300.0), ("10 pt", 10.0)] { let mut app = app(); let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); let ctx = egui::Context::default(); @@ -2503,21 +2503,23 @@ fn an_effect_dialog_keeps_a_typed_distance_within_the_effects_range() { out.textures_delta.clear(); }; app.run("select.all", json!({})).unwrap(); - app.run("effect.dialog", json!({"effect": "pixelate.colorHalftone"})).unwrap(); - // Max Radius, the first field, is focused: type over it and press Enter. + app.run("effect.dialog", json!({"effect": "pixelate.crystallize"})).unwrap(); + // Cell Size, the only field, is focused: type over it and press Enter. frame(&mut app, vec![]); frame(&mut app, vec![egui::Event::Text(typed.into())]); frame(&mut app, vec![enter()]); assert!(app.ui.dialog.is_none(), "{typed}"); let node = app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone(); - assert_eq!(node.appearance.effects.last().map(|e| e.params["maxRadius"].clone()), Some(json!(applied)), "{typed}"); + assert_eq!(node.appearance.effects.last().map(|e| e.params["cellSize"].clone()), Some(json!(applied)), "{typed}"); } } /// #4638: typing invalid input in an effect length field does not silently revert to a sub-minimum /// or out-of-range value; sub-minimum input is clamped immediately and invalid input clears cleanly. +/// (Crystallize's Cell Size, 3 to 300 pt: Color Halftone's Max Radius, which #4638 was found on, is +/// in pixels since #3260.) #[test] -fn color_halftone_invalid_input_does_not_revert_to_sub_minimum_value() { +fn effect_length_invalid_input_does_not_revert_to_sub_minimum_value() { let mut app = app(); let _id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); let ctx = egui::Context::default(); @@ -2529,20 +2531,20 @@ fn color_halftone_invalid_input_does_not_revert_to_sub_minimum_value() { out }; app.run("select.all", json!({})).unwrap(); - app.run("effect.dialog", json!({"effect": "pixelate.colorHalftone"})).unwrap(); + app.run("effect.dialog", json!({"effect": "pixelate.crystallize"})).unwrap(); frame(&mut app, vec![]); - // 1. Enter 0.5 px (sub-minimum): clamped immediately to 4 pt on commit + // 1. Enter 0.5 px (sub-minimum): clamped immediately to 3 pt on commit frame(&mut app, vec![egui::Event::Text("0.5 px".into())]); frame(&mut app, vec![egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }]); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields["maxRadius"], serde_json::json!(4.0)); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["cellSize"], serde_json::json!(3.0)); let s1 = frame(&mut app, vec![]); let shows_clamped_text = s1.shapes.iter().any(|s| match &s.shape { - egui::Shape::Text(t) => t.galley.text().trim() == "4 pt", + egui::Shape::Text(t) => t.galley.text().trim() == "3 pt", _ => false, }); - assert!(shows_clamped_text, "rendered field must show clamped '4 pt' text after sub-minimum commit"); + assert!(shows_clamped_text, "rendered field must show clamped '3 pt' text after sub-minimum commit"); - // 2. Return focus to Max Radius with Shift+Tab, type invalid text, and commit with Enter + // 2. Return focus to Cell Size with Shift+Tab, type invalid text, and commit with Enter frame( &mut app, vec![egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::SHIFT }], @@ -2552,9 +2554,9 @@ fn color_halftone_invalid_input_does_not_revert_to_sub_minimum_value() { &mut app, vec![egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }], ); - // Dialog remains open and retains the clamped 4.0 pt rather than reverting to 0.5 px + // Dialog remains open and retains the clamped 3.0 pt rather than reverting to 0.5 px assert!(app.ui.dialog.is_some(), "dialog must remain open on invalid Enter commit"); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields["maxRadius"], serde_json::json!(4.0)); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["cellSize"], serde_json::json!(3.0)); // The field paints with rejection highlight (width 1.5, accent_strong) let next_out = frame(&mut app, vec![]); @@ -2562,12 +2564,12 @@ fn color_halftone_invalid_input_does_not_revert_to_sub_minimum_value() { egui::Shape::Rect(r) => (r.stroke.width - 1.5).abs() < 1e-3 && r.stroke.color.a() > 0, _ => false, }); - assert!(has_rejection_highlight, "Max Radius must display rejection highlight after invalid input"); + assert!(has_rejection_highlight, "Cell Size must display rejection highlight after invalid input"); let shows_clamped_after_invalid = next_out.shapes.iter().any(|s| match &s.shape { - egui::Shape::Text(t) => t.galley.text().trim() == "4 pt", + egui::Shape::Text(t) => t.galley.text().trim() == "3 pt", _ => false, }); - assert!(shows_clamped_after_invalid, "rendered field must retain '4 pt' text after invalid input rejection"); + assert!(shows_clamped_after_invalid, "rendered field must retain '3 pt' text after invalid input rejection"); } #[test] @@ -2584,13 +2586,43 @@ fn bounded_field_with_inches_does_not_clamp_point_bounds_to_inch_numbers() { out.textures_delta.clear(); }; test_app.run("select.all", json!({})).unwrap(); - test_app.run("effect.dialog", json!({"effect": "pixelate.colorHalftone"})).unwrap(); + test_app.run("effect.dialog", json!({"effect": "pixelate.crystallize"})).unwrap(); frame(&mut test_app, vec![]); - // Type 1 in: 72 pt is within 4..127 pt range and must not clamp to ~1.76 pt + // Type 1 in: 72 pt is within 3..300 pt range and must not clamp to ~4.17 pt frame(&mut test_app, vec![egui::Event::Text("1 in".into())]); frame( &mut test_app, vec![egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }], ); - assert_eq!(test_app.ui.dialog.as_ref().unwrap().fields["maxRadius"], serde_json::json!(72.0)); + assert_eq!(test_app.ui.dialog.as_ref().unwrap().fields["cellSize"], serde_json::json!(72.0)); +} + +/// Color Halftone's Max Radius is in pixels of the raster effects resolution whatever the +/// document's units (#3260): in a document in centimetres it still shows and takes pixels, within +/// the documented 4 to 127 px. +#[test] +fn color_halftones_max_radius_stays_in_pixels_whatever_the_units() { + let tab = || egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + for (typed, applied, shown) in [("10", 10.0, "10 px"), ("2", 4.0, "4 px"), ("500", 127.0, "127 px"), ("4.5 px", 4.5, "4.5 px")] { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + app.run("document.setup", json!({"units": "Centimeters"})).unwrap(); + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + theme::apply(&ctx, Default::default()); + let frame = |app: &mut VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| show(app, ui.ctx())); + out.textures_delta.clear(); + out + }; + app.run("select.all", json!({})).unwrap(); + app.run("effect.dialog", json!({"effect": "pixelate.colorHalftone"})).unwrap(); + frame(&mut app, vec![]); + frame(&mut app, vec![egui::Event::Text(typed.into())]); + frame(&mut app, vec![tab()]); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["maxRadius"].as_f64(), Some(applied), "{typed}"); + let out = frame(&mut app, vec![]); + let shows = out.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Text(t) if t.galley.text().trim() == shown)); + assert!(shows, "{typed} shows as {shown}, not in centimetres"); + } } diff --git a/crates/ui-egui/src/panels/appearance.rs b/crates/ui-egui/src/panels/appearance.rs index 19a578137a..dc56ae2b21 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -880,6 +880,8 @@ fn effect_editor(app: &mut VectorcraftApp, ui: &mut Ui, item: Option, k: let suffix = ui_keys.and_then(|u| u.unit.as_deref()).map(crate::dialogs::unit_suffix).unwrap_or_default(); let nx = if vectorcraft_effects::is_length(&e.id, key, relative) { widgets::num_field(ui, id, Some(x), unit, 70.0) + } else if let Some(range) = vectorcraft_effects::raster_px_range(&e.id, key) { + widgets::range_field_named(ui, id, None, x, range, &crate::dialogs::unit_suffix("px"), 2, 70.0) } else { widgets::plain_field(ui, id, x, &suffix, 2, 70.0) }; diff --git a/docs/effects-parity.md b/docs/effects-parity.md index 0c0bc052d2..ade2feab86 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -193,6 +193,7 @@ angular cut caps, exact visibility, 3D Classic, Turntable, 3D export) is 25–45 | Date | Change | Summary | |---|---|---| +| 2026-10-30 | minor | Pixelate › Color Halftone: Max Radius is in pixels of the Document Raster Effects resolution, 4–127 px, as the [filter effects reference](https://helpx.adobe.com/photoshop/using/filter-effects-reference.html) gives it, instead of points (#3260): fine screens are possible at print resolutions (4 px at 300 ppi ≈ 0.96 pt). The dialog and the Appearance panel show it in px whatever the document units; documents saved before (document version 1) open with each radius converted, so their dots stay the same size. Scores unchanged. Tests: `vectorcraft_effects` `color_halftone_sizes_its_dots_in_pixels_of_the_raster_effects_resolution` and `color_halftones_radius_is_in_raster_pixels_not_a_distance`, `vectorcraft_doc` `halftone_radii::tests`, `vectorcraft_format` `halftone_radii_of_older_documents_open_in_pixels`, `vectorcraft_engine` `a_preserve_editing_pdf_opens_with_its_halftone_radius_in_pixels`, `dialogs::tests::color_halftones_max_radius_stays_in_pixels_whatever_the_units`. | | 2026-10-30 | minor | Effect dialogs: bounded length fields (Color Halftone Max Radius) clamp on commit and visibly reject invalid input (#4638); scores unchanged. | | 2026-10-23 | minor | Pathfinder › Trap ([trapping](https://helpx.adobe.com/illustrator/using/trapping.html)): the Pathfinder panel's Trap… (`object.pathfinder.trap`, one undo step, the traps grouped above the topmost selected object and selected) and Effect › Pathfinder › Trap… (`pathfinder.trap`, live on groups) add an overprinting strip of the lighter colour inside the darker one where two solid colours meet (Reverse Traps: the darker into the lighter, but not a rich black), with Thickness, Height/Width, Tint Reduction and Traps with Process Color; the effect also has Precision and Remove Redundant Points. Recounted: Hard Mix (#3061) and Soft Mix had shipped, so Pathfinder 11/13 → 13/13 and Illustrator effects 46/50 → 49/50 (SVG Filters remains); remaining 6–10 → 4–8 h. Tests: `vectorcraft_pathops` `trap::tests`, `vectorcraft_effects` `trap::tests` and `group::tests::trap_effect_adds_an_overprinting_strip_above_the_members`, `vectorcraft_engine` `tests_trap`, `panels::pathfinder::tests::trap_opens_its_options_and_ok_traps_the_selection`. | | 2026-10-22 | minor | The Transform effect has Transform Objects, Transform Patterns and Scale Strokes & Effects, with visible checkboxes (#885); on a fill's or stroke's own Transform effect the last two are still missing. Counts unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e6e5bd60da..c2fdf938df 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1128,8 +1128,9 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Glass's Load Texture:** Effect › Distort › Glass… has a Load Texture… button that reads a PNG, JPEG, GIF, WebP, TIFF, BMP, Targa, PSD, PSB or PCX file and adds Loaded Texture to the Texture menu (`textureImage`: `{path}` or `{name?, dataBase64}`, stored in the effect and saved with the document as a grayscale PNG in base64). The texture lies one image pixel per point at Scaling 100%, centered on the object and repeated; each pixel's luma is the surface's height, from 0 for black to 1 pt for white, and a transparent pixel counts as middle gray. Scaling and Invert act on it as on the built-in textures. A Glass saved without `textureImage` draws and saves as before. -- **Bounded effect length inputs (#4638):** Effect dialog fields with defined length ranges (such as Color Halftone Max Radius 4..127 pt) clamp immediately on commit and reject invalid inputs visibly with an accent highlight without reverting to sub-minimum values. -- **Raster effects after document and view changes:** a cached drop shadow, outer glow or filtered content is made again when something its content reads from outside the object changes: a pattern's art or tiling, a symbol shown inside another symbol, a brush definition, an image's pixels, the raster resolution (De-Interlace), Page Knockout Group, the substitution highlights (Highlight Substituted Fonts and Highlight Alternate Glyphs in Preferences › Type, Highlight Substituted Glyphs in Document Setup), a layer's Dim Images, the color settings, the fonts, Pixel Preview, Anti-aliased Artwork, Overprint Preview and isolation mode. A thumbnail under Color Halftone or Mezzotint is made again when the document's color mode changes. Raster effects (blur, shadow, glow, grain) drawn after a pattern, radial or freeform gradient fill export at their place and size (#1541, fixes #1536). +- **Bounded effect length inputs (#4638):** Effect dialog fields with defined length ranges (such as Crystallize Cell Size 3..300 pt) clamp immediately on commit and reject invalid inputs visibly with an accent highlight without reverting to sub-minimum values. +- **Color Halftone in raster pixels (#3260):** Max Radius is 4–127 px of the Document Raster Effects resolution, as public documentation gives it, shown in px whatever the document units; documents from before open with their radii in points converted (document version 2). +- **Raster effects after document and view changes:** a cached drop shadow, outer glow or filtered content is made again when something its content reads from outside the object changes: a pattern's art or tiling, a symbol shown inside another symbol, a brush definition, an image's pixels, the raster resolution (De-Interlace, Color Halftone), Page Knockout Group, the substitution highlights (Highlight Substituted Fonts and Highlight Alternate Glyphs in Preferences › Type, Highlight Substituted Glyphs in Document Setup), a layer's Dim Images, the color settings, the fonts, Pixel Preview, Anti-aliased Artwork, Overprint Preview and isolation mode. A thumbnail under Color Halftone or Mezzotint is made again when the document's color mode changes. Raster effects (blur, shadow, glow, grain) drawn after a pattern, radial or freeform gradient fill export at their place and size (#1541, fixes #1536). - **Drop Shadow's Darkness:** Effect › Stylize › Drop Shadow… has Color and Darkness as radio buttons, each with its field, and the Appearance panel's inline editor has the two radio buttons in its Shade row (`shade`: `color` or `darkness`; `darkness`: 0 to 100%, 100 by default). Color is the default, and a shadow saved without these keys draws as before. With Darkness, the stored source-color model determines the adjustment before document/profile conversion and blur: subtract Darkness/100 from each RGB channel, clamped at zero, or add it to CMYK black K and Gray black, clamped at one, preserving CMYK C/M/Y. At the near-100% endpoint the shadow source becomes gray black before conversion. Shadow opacity stays separate. Original gradient stops follow the same application rule before interpolation; exact resource-level gradient parity remains open. Application SVG export keeps a live filter for simple uniform sRGB sources and uses rendered shadow images for other working RGB profiles, source models and gradients. Low-level SVG filter output warns when this preparation is needed; proportional intermediate SVG filters are not misread as additive Darkness. Exact spot/custom-color and composite-source parity remain open, and resulting CMYK ink values follow the application color pipeline. CSS export leaves the shadow out and marks the object unsupported. When a `.ai`, EPS or PDF opens from its editing data, a Drop Shadow with Darkness in an object's art style is read as one with Color is, with the shadow's Darkness percentage (100% when the style gives none). Behavior reference: Illustrator CC Help (2014, [PDF](https://help.adobe.com/archive/en/illustrator/cc/2014/illustrator_reference.pdf)), page 428 (PDF page 434). From f4f40285b0a180c45eb1d4651bf4c097b5e21083 Mon Sep 17 00:00:00 2001 From: datatimp <12644819+datatimp@users.noreply.github.com> Date: Fri, 30 Oct 2026 22:03:13 -0400 Subject: [PATCH 002/513] Color Halftone: radii in points for older-version saves; review fixes (#3260) --- crates/doc/src/halftone_radii.rs | 75 ++++++++++++++++++++++++++++---- crates/format/src/lib.rs | 17 ++++++++ docs/effects-parity.md | 4 +- docs/target-app-parity.md | 5 ++- 4 files changed, 89 insertions(+), 12 deletions(-) diff --git a/crates/doc/src/halftone_radii.rs b/crates/doc/src/halftone_radii.rs index 6c3d4544d6..cbafeb0b9b 100644 --- a/crates/doc/src/halftone_radii.rs +++ b/crates/doc/src/halftone_radii.rs @@ -1,6 +1,7 @@ //! Color Halftone's Max Radius was a distance in points until documents of version 2; since then //! it is in pixels of the Document Raster Effects resolution, as public documentation gives it -//! (#3260). [`Document::migrate_halftone_radii`] converts the radii of older documents. +//! (#3260). [`Document::migrate_halftone_radii`] converts the radii of older documents, and +//! [`Document::halftone_radii_to_points`] converts them back for a file saved for an older app. use std::sync::Arc; @@ -30,14 +31,34 @@ impl Document { } self.version = FORMAT_VERSION; let k = self.raster_ppi() / 72.0; - let fix = &mut |e: &mut Effect| to_pixels(e, k); + self.each_halftone(&mut |e| rescale(e, k)); + } + + /// For a file saved for an app before version 2 (every native file version before today's): + /// each Color Halftone's Max Radius in pixels becomes the points that draw the same dots, + /// within the 4 to 127 pt that app takes (a radius under 4 pt, from a fine screen at a high + /// resolution, draws bigger dots there), and the document becomes version 1, so reopening the + /// file here converts them back. + pub fn halftone_radii_to_points(&mut self) { + if self.version < PIXEL_RADII_SINCE { + return; + } + self.version = PIXEL_RADII_SINCE - 1; + let k = 72.0 / self.raster_ppi(); + self.each_halftone(&mut |e| rescale(e, k)); + } + + /// `fix` each effect in the art, symbols, patterns (and the one being edited as it was), graph + /// designs, opacity masks and graphic styles that use a Color Halftone. + fn each_halftone(&mut self, fix: &mut dyn FnMut(&mut Effect)) { for l in &mut self.layers { node(l, fix); } for s in &mut self.symbols { node(&mut s.art, fix); } - for p in &mut self.patterns { + // Pattern editing is saved with the pattern as it was, which Cancel puts back. + for p in self.patterns.iter_mut().chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut())) { for a in &mut p.art { node(a, fix); } @@ -53,8 +74,9 @@ impl Document { } } -/// `e`'s radius in points as pixels, `k` pixels a point, when it is a Color Halftone. -fn to_pixels(e: &mut Effect, k: f64) { +/// `e`'s radius times `k` (pixels a point, or points a pixel), within the effect's range, when it +/// is a Color Halftone. Its default is 8 in either unit. +fn rescale(e: &mut Effect, k: f64) { if e.id != HALFTONE { return; } @@ -109,17 +131,17 @@ mod tests { fn older_radii_become_the_pixels_that_draw_the_same_dots() { for (ppi, pt, px) in [(72.0, 8.0, 8.0), (300.0, 8.0, 33.333333333333336), (300.0, 4.0, 16.666666666666668), (150.0, 127.0, 127.0)] { let mut e = halftone(Some(pt)); - to_pixels(&mut e, ppi / 72.0); + rescale(&mut e, ppi / 72.0); assert!((radius(&e) - px).abs() < 1e-9, "{pt} pt at {ppi} ppi: {}", radius(&e)); assert_eq!(e.params["channel1"], json!(108.0), "the angles stay"); } // A radius left out drew at the old default, 8 pt. let mut e = halftone(None); - to_pixels(&mut e, 300.0 / 72.0); + rescale(&mut e, 300.0 / 72.0); assert!((radius(&e) - 33.333333333333336).abs() < 1e-9); // Other effects keep their parameters. let mut blur = Effect { id: "blur.gaussian".into(), params: json!({"radius": 8.0}), visible: true }; - to_pixels(&mut blur, 300.0 / 72.0); + rescale(&mut blur, 300.0 / 72.0); assert_eq!(blur.params, json!({"radius": 8.0})); } @@ -142,4 +164,41 @@ mod tests { d.migrate_halftone_radii(); assert_eq!(d, once, "converted documents are left alone"); } + + #[test] + fn radii_go_back_to_points_for_an_older_app_and_return_unchanged() { + let mut d = Document::new(100.0, 100.0); + d.raster_effects_ppi = 300.0; + let mut style = d.graphic_styles.first().cloned().unwrap(); + style.appearance.effects.push(halftone(Some(100.0))); + style.appearance.effects.push(halftone(Some(4.0))); + d.graphic_styles.push(style); + let r = |d: &Document, i: usize| d.graphic_styles.last().map(|s| radius(&s.appearance.effects[i])).unwrap(); + d.halftone_radii_to_points(); + assert_eq!(d.version, 1, "reopened here, it converts back"); + assert!((r(&d, 0) - 24.0).abs() < 1e-9, "100 px at 300 ppi is 24 pt: {}", r(&d, 0)); + assert_eq!(r(&d, 1), 4.0, "0.96 pt is under the 4 pt the older app takes"); + let points = d.clone(); + d.halftone_radii_to_points(); + assert_eq!(d, points, "already in points"); + d.migrate_halftone_radii(); + assert!((r(&d, 0) - 100.0).abs() < 1e-9, "{}", r(&d, 0)); + } + + #[test] + fn the_pattern_being_edited_is_converted_as_it_was() { + let mut d = Document::new(100.0, 100.0); + d.raster_effects_ppi = 300.0; + let id = d.alloc_id(); + let mut look = Appearance::default_art(); + look.effects = vec![halftone(Some(8.0))]; + let square = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0)); + let tile = Arc::new(Node::path(id, square, look)); + let original = Some(crate::PatternDef::new("Tile", vec![tile])); + d.pattern_edit = Some(crate::PatternEdit { pattern: "Tile".into(), layer: crate::NodeId(0), original }); + d.version = 1; + d.migrate_halftone_radii(); + let art = &d.pattern_edit.as_ref().unwrap().original.as_ref().unwrap().art[0]; + assert!((radius(&art.appearance.effects[0]) - 33.333333333333336).abs() < 1e-9, "the tile Cancel puts back"); + } } diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index d9fb08c0bb..4cc07c4044 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -319,6 +319,10 @@ fn body(doc: &Document, o: &SaveOptions) -> Result { if version < 3 { d.store_legacy_color_profiles(); } + // Apps before this one's version take Color Halftone's Max Radius in points (#3260). + if version < VERSION { + d.halftone_radii_to_points(); + } let v1 = if version == 1 { let mut v = serde_json::to_value(&d).map_err(encode_err)?; legacy::anchors_to_v1(&mut v); @@ -804,6 +808,19 @@ mod tests { let old = load(&save(&d, false)).unwrap(); assert_eq!(old.version, vectorcraft_doc::FORMAT_VERSION); assert!((radius(&old) - 8.0 * 300.0 / 72.0).abs() < 1e-9, "8 pt at 300 ppi: {}", radius(&old)); + // Saved for an older app, in every older version: the radius in points, which opens here + // in pixels again. + let px = radius(&old); + for version in MIN_VERSION..VERSION { + let bytes = save_with(&old, &SaveOptions { version, ..SaveOptions::default() }).unwrap(); + let json = String::from_utf8(unpack::Unpacked::new(&bytes).unwrap().json().to_vec()).unwrap(); + let at = json.find("\"maxRadius\":").unwrap() + "\"maxRadius\":".len(); + let saved: f64 = json[at..].split([',', '}']).next().unwrap().trim().parse().unwrap(); + assert!((saved - 8.0).abs() < 1e-9, "version {version} holds 8 pt: {saved}"); + let back = load(&bytes).unwrap(); + assert!((radius(&back) - px).abs() < 1e-9, "version {version}: {}", radius(&back)); + } + assert_eq!(radius(&old), px, "saving leaves the open document as it is"); } #[test] diff --git a/docs/effects-parity.md b/docs/effects-parity.md index ade2feab86..4474cff23a 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -1,6 +1,6 @@ # Effects parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-28 · **Change:** minor (Effect dialogs clamp bounded length inputs immediately on commit and flash rejection on invalid input (#4638); previously: Drop Shadow Darkness uses fixed RGB subtraction and CMYK black addition; scores unchanged; Pathfinder › Trap: the Pathfinder panel's Trap… and Effect › Pathfinder › Trap… add an overprinting strip of the lighter colour where two solid colours meet; recounted with Hard Mix (#3061) and Soft Mix already in the catalogue: Pathfinder 13/13, Illustrator effects 49/50) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (Pixelate › Color Halftone: Max Radius in pixels of the Document Raster Effects resolution, 4–127 px, with older documents converted on opening and radii written back in points for older app versions (#3260); previously: Effect dialogs clamp bounded length inputs immediately on commit and flash rejection on invalid input (#4638); Drop Shadow Darkness uses fixed RGB subtraction and CMYK black addition; scores unchanged; Pathfinder › Trap: the Pathfinder panel's Trap… and Effect › Pathfinder › Trap… add an overprinting strip of the lighter colour where two solid colours meet; recounted with Hard Mix (#3061) and Soft Mix already in the catalogue: Pathfinder 13/13, Illustrator effects 49/50) · **Target:** Adobe Illustrator 2026 (30.x) Every entry of Illustrator's Effect menu, by its public feature name, against VectorCraft's effects catalogue (`effect_catalog()` in `crates/effects/src/lib.rs`) and the Effect menu built from it @@ -193,7 +193,7 @@ angular cut caps, exact visibility, 3D Classic, Turntable, 3D export) is 25–45 | Date | Change | Summary | |---|---|---| -| 2026-10-30 | minor | Pixelate › Color Halftone: Max Radius is in pixels of the Document Raster Effects resolution, 4–127 px, as the [filter effects reference](https://helpx.adobe.com/photoshop/using/filter-effects-reference.html) gives it, instead of points (#3260): fine screens are possible at print resolutions (4 px at 300 ppi ≈ 0.96 pt). The dialog and the Appearance panel show it in px whatever the document units; documents saved before (document version 1) open with each radius converted, so their dots stay the same size. Scores unchanged. Tests: `vectorcraft_effects` `color_halftone_sizes_its_dots_in_pixels_of_the_raster_effects_resolution` and `color_halftones_radius_is_in_raster_pixels_not_a_distance`, `vectorcraft_doc` `halftone_radii::tests`, `vectorcraft_format` `halftone_radii_of_older_documents_open_in_pixels`, `vectorcraft_engine` `a_preserve_editing_pdf_opens_with_its_halftone_radius_in_pixels`, `dialogs::tests::color_halftones_max_radius_stays_in_pixels_whatever_the_units`. | +| 2026-10-30 | minor | Pixelate › Color Halftone: Max Radius is in pixels of the Document Raster Effects resolution, 4–127 px, as the [filter effects reference](https://helpx.adobe.com/photoshop/using/filter-effects-reference.html) gives it, instead of points (#3260): fine screens are possible at print resolutions (4 px at 300 ppi ≈ 0.96 pt). The dialog and the Appearance panel show it in px whatever the document units; documents saved before (document version 1) open with each radius converted, so their dots stay the same size, and a file saved for an older app version (native versions before today's) holds them in points again. Scores unchanged. Tests: `vectorcraft_effects` `color_halftone_sizes_its_dots_in_pixels_of_the_raster_effects_resolution` and `color_halftones_radius_is_in_raster_pixels_not_a_distance`, `vectorcraft_doc` `halftone_radii::tests`, `vectorcraft_format` `halftone_radii_of_older_documents_open_in_pixels`, `vectorcraft_engine` `a_preserve_editing_pdf_opens_with_its_halftone_radius_in_pixels`, `dialogs::tests::color_halftones_max_radius_stays_in_pixels_whatever_the_units`. | | 2026-10-30 | minor | Effect dialogs: bounded length fields (Color Halftone Max Radius) clamp on commit and visibly reject invalid input (#4638); scores unchanged. | | 2026-10-23 | minor | Pathfinder › Trap ([trapping](https://helpx.adobe.com/illustrator/using/trapping.html)): the Pathfinder panel's Trap… (`object.pathfinder.trap`, one undo step, the traps grouped above the topmost selected object and selected) and Effect › Pathfinder › Trap… (`pathfinder.trap`, live on groups) add an overprinting strip of the lighter colour inside the darker one where two solid colours meet (Reverse Traps: the darker into the lighter, but not a rich black), with Thickness, Height/Width, Tint Reduction and Traps with Process Color; the effect also has Precision and Remove Redundant Points. Recounted: Hard Mix (#3061) and Soft Mix had shipped, so Pathfinder 11/13 → 13/13 and Illustrator effects 46/50 → 49/50 (SVG Filters remains); remaining 6–10 → 4–8 h. Tests: `vectorcraft_pathops` `trap::tests`, `vectorcraft_effects` `trap::tests` and `group::tests::trap_effect_adds_an_overprinting_strip_above_the_members`, `vectorcraft_engine` `tests_trap`, `panels::pathfinder::tests::trap_opens_its_options_and_ok_traps_the_selection`. | | 2026-10-22 | minor | The Transform effect has Transform Objects, Transform Patterns and Scale Strokes & Effects, with visible checkboxes (#885); on a fill's or stroke's own Transform effect the last two are still missing. Counts unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c2fdf938df..a770371f82 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (Path Precision Tools add-on: the Parametric Shape Tool; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (Effects: Color Halftone's Max Radius in pixels of the Document Raster Effects resolution (#3260); scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -1129,7 +1129,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Glass's Load Texture:** Effect › Distort › Glass… has a Load Texture… button that reads a PNG, JPEG, GIF, WebP, TIFF, BMP, Targa, PSD, PSB or PCX file and adds Loaded Texture to the Texture menu (`textureImage`: `{path}` or `{name?, dataBase64}`, stored in the effect and saved with the document as a grayscale PNG in base64). The texture lies one image pixel per point at Scaling 100%, centered on the object and repeated; each pixel's luma is the surface's height, from 0 for black to 1 pt for white, and a transparent pixel counts as middle gray. Scaling and Invert act on it as on the built-in textures. A Glass saved without `textureImage` draws and saves as before. - **Bounded effect length inputs (#4638):** Effect dialog fields with defined length ranges (such as Crystallize Cell Size 3..300 pt) clamp immediately on commit and reject invalid inputs visibly with an accent highlight without reverting to sub-minimum values. -- **Color Halftone in raster pixels (#3260):** Max Radius is 4–127 px of the Document Raster Effects resolution, as public documentation gives it, shown in px whatever the document units; documents from before open with their radii in points converted (document version 2). +- **Color Halftone in raster pixels (#3260):** Max Radius is 4–127 px of the Document Raster Effects resolution, as public documentation gives it, shown in px whatever the document units; documents from before open with their radii in points converted (document version 2), and a file saved for an older app version holds them in points again. - **Raster effects after document and view changes:** a cached drop shadow, outer glow or filtered content is made again when something its content reads from outside the object changes: a pattern's art or tiling, a symbol shown inside another symbol, a brush definition, an image's pixels, the raster resolution (De-Interlace, Color Halftone), Page Knockout Group, the substitution highlights (Highlight Substituted Fonts and Highlight Alternate Glyphs in Preferences › Type, Highlight Substituted Glyphs in Document Setup), a layer's Dim Images, the color settings, the fonts, Pixel Preview, Anti-aliased Artwork, Overprint Preview and isolation mode. A thumbnail under Color Halftone or Mezzotint is made again when the document's color mode changes. Raster effects (blur, shadow, glow, grain) drawn after a pattern, radial or freeform gradient fill export at their place and size (#1541, fixes #1536). - **Drop Shadow's Darkness:** Effect › Stylize › Drop Shadow… has Color and Darkness as radio buttons, each with its field, and the Appearance panel's inline editor has the two radio buttons in its Shade row (`shade`: `color` or `darkness`; `darkness`: 0 to 100%, 100 by default). Color is the default, and a shadow saved without these keys draws as before. With Darkness, the stored source-color model determines the adjustment before document/profile conversion and blur: subtract Darkness/100 from each RGB channel, clamped at zero, or add it to CMYK black K and Gray black, clamped at one, preserving CMYK C/M/Y. At the near-100% endpoint the shadow source becomes gray black before conversion. Shadow opacity stays separate. Original gradient stops follow the same application rule before interpolation; exact resource-level gradient parity remains open. Application SVG export keeps a live filter for simple uniform sRGB sources and uses rendered shadow images for other working RGB profiles, source models and gradients. Low-level SVG filter output warns when this preparation is needed; proportional intermediate SVG filters are not misread as additive Darkness. Exact spot/custom-color and composite-source parity remain open, and resulting CMYK ink values follow the application color pipeline. CSS export leaves the shadow out and marks the object unsupported. When a `.ai`, EPS or PDF opens from its editing data, a Drop Shadow with Darkness in an object's art style is read as one with Color is, with the shadow's Darkness percentage (100% when the style gives none). Behavior reference: Illustrator CC Help (2014, [PDF](https://help.adobe.com/archive/en/illustrator/cc/2014/illustrator_reference.pdf)), page 428 (PDF page 434). @@ -1275,6 +1275,7 @@ spot colours, carry a colour adjustment, or are RGB, CMYK or grayscale images | Date | Change | Summary | |---|---|---| +| 2026-10-30 | minor | Effects: Color Halftone's Max Radius is 4–127 px of the Document Raster Effects resolution, shown in px whatever the units; older documents open converted, and files saved for older app versions hold points (#3260); scores unchanged. | | 2026-10-30 | minor | Path Precision Tools add-on: the Parametric Shape Tool; evidence added; scores unchanged. | | 2026-10-30 | minor | Presentation Mode fits the active artboard and hides selections, guides, grids and artboard edges; scores and estimates unchanged | | 2026-10-30 | minor | Color Effects add-on: Select by Color Kind; scores and estimates unchanged | From 4a8b40ac8b01c0f6710a9a3e40deb6aefe059da7 Mon Sep 17 00:00:00 2001 From: datatimp <12644819+datatimp@users.noreply.github.com> Date: Sun, 1 Nov 2026 13:57:22 -0500 Subject: [PATCH 003/513] Color Halftone: test older files at 72 and 300 ppi (#3260) --- crates/format/src/lib.rs | 60 +++++++++++++++++++++------------------- 1 file changed, 31 insertions(+), 29 deletions(-) diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 4cc07c4044..8a01955de2 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -789,38 +789,40 @@ mod tests { /// Color Halftone's Max Radius is in pixels of the raster effects resolution since document /// version 2 (#3260): a file from before opens with its radius in points converted, one saved - /// since opens as it was. + /// since opens as it was. At 72 ppi a point is a pixel, so the number stays. #[test] fn halftone_radii_of_older_documents_open_in_pixels() { - let mut d = Document::new(100.0, 100.0); - d.raster_effects_ppi = 300.0; - let (l, id) = (d.layers[0].id, d.alloc_id()); - let mut look = Appearance::default_art(); - look.effects.push(vectorcraft_doc::Effect { - id: "pixelate.colorHalftone".into(), - params: serde_json::json!({"maxRadius": 8.0}), - visible: true, - }); - d.insert(Some(l), 0, Node::path(id, shapes::ellipse(Rect::new(0.0, 0.0, 10.0, 10.0)), look)).unwrap(); - let radius = |d: &Document| d.node(id).unwrap().appearance.effects[0].params["maxRadius"].as_f64().unwrap(); - assert_eq!(radius(&load(&save(&d, false)).unwrap()), 8.0, "saved in pixels, opened in pixels"); - d.version = 1; - let old = load(&save(&d, false)).unwrap(); - assert_eq!(old.version, vectorcraft_doc::FORMAT_VERSION); - assert!((radius(&old) - 8.0 * 300.0 / 72.0).abs() < 1e-9, "8 pt at 300 ppi: {}", radius(&old)); - // Saved for an older app, in every older version: the radius in points, which opens here - // in pixels again. - let px = radius(&old); - for version in MIN_VERSION..VERSION { - let bytes = save_with(&old, &SaveOptions { version, ..SaveOptions::default() }).unwrap(); - let json = String::from_utf8(unpack::Unpacked::new(&bytes).unwrap().json().to_vec()).unwrap(); - let at = json.find("\"maxRadius\":").unwrap() + "\"maxRadius\":".len(); - let saved: f64 = json[at..].split([',', '}']).next().unwrap().trim().parse().unwrap(); - assert!((saved - 8.0).abs() < 1e-9, "version {version} holds 8 pt: {saved}"); - let back = load(&bytes).unwrap(); - assert!((radius(&back) - px).abs() < 1e-9, "version {version}: {}", radius(&back)); + for ppi in [72.0, 300.0] { + let mut d = Document::new(100.0, 100.0); + d.raster_effects_ppi = ppi; + let (l, id) = (d.layers[0].id, d.alloc_id()); + let mut look = Appearance::default_art(); + look.effects.push(vectorcraft_doc::Effect { + id: "pixelate.colorHalftone".into(), + params: serde_json::json!({"maxRadius": 8.0}), + visible: true, + }); + d.insert(Some(l), 0, Node::path(id, shapes::ellipse(Rect::new(0.0, 0.0, 10.0, 10.0)), look)).unwrap(); + let radius = |d: &Document| d.node(id).unwrap().appearance.effects[0].params["maxRadius"].as_f64().unwrap(); + assert_eq!(radius(&load(&save(&d, false)).unwrap()), 8.0, "{ppi} ppi: saved in pixels, opened in pixels"); + d.version = 1; + let old = load(&save(&d, false)).unwrap(); + assert_eq!(old.version, vectorcraft_doc::FORMAT_VERSION); + assert!((radius(&old) - 8.0 * ppi / 72.0).abs() < 1e-9, "8 pt at {ppi} ppi: {}", radius(&old)); + // Saved for an older app, in every older version: the radius in points, which opens + // here in pixels again. + let px = radius(&old); + for version in MIN_VERSION..VERSION { + let bytes = save_with(&old, &SaveOptions { version, ..SaveOptions::default() }).unwrap(); + let json = String::from_utf8(unpack::Unpacked::new(&bytes).unwrap().json().to_vec()).unwrap(); + let at = json.find("\"maxRadius\":").unwrap() + "\"maxRadius\":".len(); + let saved: f64 = json[at..].split([',', '}']).next().unwrap().trim().parse().unwrap(); + assert!((saved - 8.0).abs() < 1e-9, "{ppi} ppi, version {version} holds 8 pt: {saved}"); + let back = load(&bytes).unwrap(); + assert!((radius(&back) - px).abs() < 1e-9, "{ppi} ppi, version {version}: {}", radius(&back)); + } + assert_eq!(radius(&old), px, "{ppi} ppi: saving leaves the open document as it is"); } - assert_eq!(radius(&old), px, "saving leaves the open document as it is"); } #[test] From b5301ca74d0d926e6750ebc23e3bb287fedee872 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 18:24:56 -0800 Subject: [PATCH 004/513] Fix range text stroke weight defaults and scaling --- crates/engine/src/cmd/textedit.rs | 33 ++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 8ce750a5e1..df19ec0023 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -351,6 +351,8 @@ pub(crate) struct CharChange { stroke: Option, /// Weight (`strokeWidth`), cap, join, miter limit and dashes of the character stroke. stroke_opts: StrokeChange, + /// Document points per text-space point for a stroke edit. + stroke_scale: Option, underline: Option, strikethrough: Option, all_caps: Option, @@ -641,6 +643,7 @@ impl CharChange { fill: paint_param(p, "fill", cmd)?, stroke: paint_param(p, "stroke", cmd)?, stroke_opts, + stroke_scale: None, underline: flag("underline"), strikethrough: flag("strikethrough"), all_caps: flag("allCaps"), @@ -723,6 +726,7 @@ impl CharChange { self.tcy_up_down = self.tcy_up_down.map(|v| local_type_value(t, v, (-1296.0, 1296.0), false, cmd)).transpose()?; self.tcy_left_right = self.tcy_left_right.map(|v| local_type_value(t, v, (-1296.0, 1296.0), false, cmd)).transpose()?; self.h_scale = self.h_scale.map(|v| local_type_value(t, v, (1.0, 10000.0), true, cmd)).transpose()?; + self.stroke_scale = Some(vectorcraft_doc::Scaling::factor(t.xf).filter(|k| k.is_finite() && *k > 1e-12).unwrap_or(1.0)); Ok(()) } @@ -809,10 +813,13 @@ impl CharChange { st.fill = v.clone(); } if let Some(v) = &self.stroke { + if !v.is_none() { + super::gradient::run_stroke_weight(st); + } st.stroke = v.clone(); } if !self.stroke_opts.is_empty() { - self.stroke_opts.apply_char(st); + self.stroke_opts.apply_char_scaled(st, self.stroke_scale.unwrap_or(1.0)); } if let Some(v) = self.underline { st.underline = v; @@ -1609,3 +1616,27 @@ fn discard_empty(s: &mut Session, p: &Value) -> Result { s.edit("Discard Empty Type", |d, _| d.remove(id).map(|_| ()).map_err(|_| EngineError::NoNode(id)))?; Ok(json!({"removed": true})) } + +#[cfg(test)] +mod range_stroke_tests { + use super::*; + + #[test] + fn range_stroke_gains_a_default_weight_and_scales_explicit_weight() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "ABCD"})).unwrap()["id"].as_u64().unwrap(); + let weights = |s: &Session| { + let NodeKind::Text(t) = &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind else { panic!("text missing") }; + t.runs.iter().map(|r| r.style.stroke_width).collect::>() + }; + s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 2, "stroke": "#ff0000"})).unwrap(); + assert_eq!(weights(&s), [1.0, 0.0], "a newly painted range has a visible default stroke"); + + s.execute("object.scale", &json!({"ids": [id], "sx": 200, "sy": 200})).unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 2, "strokeWidth": 2.0})).unwrap(); + assert_eq!(weights(&s), [1.0, 0.0], "two document points become one text-space point at 200% scale"); + s.execute("text.setRangeStyle", &json!({"id": id, "start": 2, "end": 4, "stroke": "#0000ff", "strokeWidth": 4.0})).unwrap(); + assert_eq!(weights(&s), [1.0, 2.0], "a different range receives its scaled weight"); + } +} From 79102f61043108a8ecfd82b21887402600adb3bf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 20:52:01 -0800 Subject: [PATCH 005/513] Tests: range stroke weight test joins the character stroke tests The test moves from an inline module in cmd/textedit.rs to tests/charstroke.rs and uses that file's helpers. docs/mcp.md says that text.setRangeStyle gives a range's stroke a 1 pt weight as text.setStyle does, and that its strokeWidth and strokeOptions lengths are in document points. --- crates/engine/src/cmd/textedit.rs | 24 ------------------------ crates/engine/src/tests/charstroke.rs | 15 +++++++++++++++ docs/mcp.md | 2 ++ 3 files changed, 17 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index df19ec0023..ac0af58671 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -1616,27 +1616,3 @@ fn discard_empty(s: &mut Session, p: &Value) -> Result { s.edit("Discard Empty Type", |d, _| d.remove(id).map(|_| ()).map_err(|_| EngineError::NoNode(id)))?; Ok(json!({"removed": true})) } - -#[cfg(test)] -mod range_stroke_tests { - use super::*; - - #[test] - fn range_stroke_gains_a_default_weight_and_scales_explicit_weight() { - let mut s = Session::new(); - s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); - let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "ABCD"})).unwrap()["id"].as_u64().unwrap(); - let weights = |s: &Session| { - let NodeKind::Text(t) = &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind else { panic!("text missing") }; - t.runs.iter().map(|r| r.style.stroke_width).collect::>() - }; - s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 2, "stroke": "#ff0000"})).unwrap(); - assert_eq!(weights(&s), [1.0, 0.0], "a newly painted range has a visible default stroke"); - - s.execute("object.scale", &json!({"ids": [id], "sx": 200, "sy": 200})).unwrap(); - s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 2, "strokeWidth": 2.0})).unwrap(); - assert_eq!(weights(&s), [1.0, 0.0], "two document points become one text-space point at 200% scale"); - s.execute("text.setRangeStyle", &json!({"id": id, "start": 2, "end": 4, "stroke": "#0000ff", "strokeWidth": 4.0})).unwrap(); - assert_eq!(weights(&s), [1.0, 2.0], "a different range receives its scaled weight"); - } -} diff --git a/crates/engine/src/tests/charstroke.rs b/crates/engine/src/tests/charstroke.rs index ba948cb664..2c34e697ea 100644 --- a/crates/engine/src/tests/charstroke.rs +++ b/crates/engine/src/tests/charstroke.rs @@ -91,6 +91,21 @@ fn range_stroke_options_split_runs() { assert!(s.execute("text.setRangeStyle", &json!({"id": id.0, "strokeOptions": 3})).is_err()); } +#[test] +fn range_stroke_gains_a_default_weight_and_scales_explicit_weight() { + let mut s = session(); + let id = NodeId(run(&mut s, "text.create", json!({"x": 10, "y": 50, "text": "ABCD"}))["id"].as_u64().unwrap()); + let weights = |s: &Session| text(s, id).runs.iter().map(|r| r.style.stroke_width).collect::>(); + run(&mut s, "text.setRangeStyle", json!({"id": id.0, "start": 0, "end": 2, "stroke": "#ff0000"})); + assert_eq!(weights(&s), [1.0, 0.0], "a newly painted range has a visible default stroke"); + + run(&mut s, "object.scale", json!({"ids": [id.0], "sx": 200, "sy": 200})); + run(&mut s, "text.setRangeStyle", json!({"id": id.0, "start": 0, "end": 2, "strokeWidth": 2.0})); + assert_eq!(weights(&s), [1.0, 0.0], "two document points become one text-space point at 200% scale"); + run(&mut s, "text.setRangeStyle", json!({"id": id.0, "start": 2, "end": 4, "stroke": "#0000ff", "strokeWidth": 4.0})); + assert_eq!(weights(&s), [1.0, 2.0], "a different range receives its scaled weight"); +} + #[test] fn eyedropper_and_outlines_carry_the_character_stroke() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index 8a2551ffc6..864a1af921 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2404,6 +2404,8 @@ dash?, dashOffset?, alignDashes?}}`. `text.setStyle {ids?, stroke?, strokeWidth? and weight of the characters of each object given (without `start` and `end`: all of its text), with its other keys in one undo step; `strokeWidth` is in document points, as `stroke.set` gives the weight of scaled type. A `stroke` color without `strokeWidth` gives characters that have no stroke weight 1 pt, as `paint.setStroke` does. +`text.setRangeStyle` does the same for its range, and its `strokeWidth` and `strokeOptions` lengths are in document +points too. `align: "inside"|"outside"` keeps the characters' stroke on that side of the glyph outlines, drawn at twice the weight and clipped, while the type stays editable (beyond Illustrator); SVG export writes the text live and that stroke as glyph outlines over it. `inspect_document` reports each object's stroke as `strokeOptions` (type: its first From 0dba3afea9a371bc34c957654cca464a78f6402c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 21:38:46 -0800 Subject: [PATCH 006/513] Docs: the 1 pt default stroke weight on type is in the type's own units docs/mcp.md says that the default weight text.setStyle and text.setRangeStyle give an unweighted stroke is in the type's own units, so scaled type draws it wider, while strokeWidth and strokeOptions lengths are in document points. --- docs/mcp.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mcp.md b/docs/mcp.md index 864a1af921..5fab5134a2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2405,7 +2405,7 @@ and weight of the characters of each object given (without `start` and `end`: al one undo step; `strokeWidth` is in document points, as `stroke.set` gives the weight of scaled type. A `stroke` color without `strokeWidth` gives characters that have no stroke weight 1 pt, as `paint.setStroke` does. `text.setRangeStyle` does the same for its range, and its `strokeWidth` and `strokeOptions` lengths are in document -points too. +points too. The 1 pt default of both commands is in the type's own units, so on type scaled to 200% it draws 2 pt wide. `align: "inside"|"outside"` keeps the characters' stroke on that side of the glyph outlines, drawn at twice the weight and clipped, while the type stays editable (beyond Illustrator); SVG export writes the text live and that stroke as glyph outlines over it. `inspect_document` reports each object's stroke as `strokeOptions` (type: its first From bf58f605fe5fda2411ea9ced539af81384b5d840 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Tue, 3 Nov 2026 19:53:50 +0530 Subject: [PATCH 007/513] Text Tweaker: refuse ranges that aren't whole bytes, make no step when nothing changes (#4924) A `start` or `end` such as -1 or 1.5 was read as absent and changed text before the range; it is now refused. Characters that already have the value are left out, so a run that changes nothing returns count 0 and makes no undo step. docs/mcp.md cites the public formatting-type page. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/addons/typetools.rs | 35 +++++++++++++++++-- .../engine/src/cmd/addons/typetools/tests.rs | 22 ++++++++++-- docs/mcp.md | 3 +- 3 files changed, 54 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/addons/typetools.rs b/crates/engine/src/cmd/addons/typetools.rs index 0cd8e21ea1..29ca6f6bfd 100644 --- a/crates/engine/src/cmd/addons/typetools.rs +++ b/crates/engine/src/cmd/addons/typetools.rs @@ -89,29 +89,58 @@ fn text_tweaker(s: &mut Session, p: &Value) -> Result { let mut rng = Rng::new(whole_or(p, "seed", 0, C)?); let skip = switch_or(p, "skipSpaces", true, C)?; let setup = s.doc()?.doc.setup.clone(); + // A range given as anything but whole bytes is refused, not read as all of the text. + for k in ["start", "end"] { + if p.get(k).is_some_and(|v| !v.is_null() && v.as_u64().is_none()) { + return Err(bad(C, format!("`{k}` must be a whole number of bytes"))); + } + } // At a caret, all of the object's text. let ranges = type_ranges(s, p, C, |text, _| Some((0, text.len())))?; // Each object's changed characters: (byte, its change), worked out before the edit. let mut plans: Vec<(NodeId, Vec<(usize, CharChange)>)> = vec![]; - let mut count = 0; + let (mut seen, mut count) = (0, 0); for (id, a, b, _) in ranges { let t = text_ref(s, id)?; let text = t.plain_text(); let chars: Vec = text.char_indices().filter(|&(i, c)| (a..b).contains(&i) && !(skip && (c.is_whitespace() || c.is_control()))).map(|(i, _)| i).collect(); - count += chars.len(); - if count > MAX_CHARS { + seen += chars.len(); + if seen > MAX_CHARS { return Err(bad(C, format!("too many characters: at most {MAX_CHARS}"))); } + // Each run's end byte, to find the style a character has now. + let ends: Vec = t + .runs + .iter() + .scan(0, |off, r| { + *off += r.text.len(); + Some(*off) + }) + .collect(); let n = chars.len(); let mut changes = Vec::with_capacity(n); + let mut run = 0; for (i, at) in chars.into_iter().enumerate() { let random = if shape == "random" { unit(&mut rng) } else { 0.0 }; let value = from + (to - from) * amount(shape, i, n, random); let mut change = CharChange::parse(&json!({ key: value }), C, &setup)?; change.localize(&t, C)?; + while ends.get(run).is_some_and(|&e| e <= at) { + run += 1; + } + // A character that already has the value is left out, so a run that changes nothing + // makes no step. + if let Some(r) = t.runs.get(run) { + let mut style = r.style.clone(); + change.apply(&mut style); + if style == r.style { + continue; + } + } changes.push((at, change)); } + count += changes.len(); if !changes.is_empty() { plans.push((id, changes)); } diff --git a/crates/engine/src/cmd/addons/typetools/tests.rs b/crates/engine/src/cmd/addons/typetools/tests.rs index 47a1b92b9d..fec04f9c63 100644 --- a/crates/engine/src/cmd/addons/typetools/tests.rs +++ b/crates/engine/src/cmd/addons/typetools/tests.rs @@ -62,7 +62,8 @@ fn a_straight_ramp_sizes_each_letter_and_skips_spaces() { select(&mut s, &[id]); let n = steps(&s); let out = s.execute(C, &json!({"attribute": "size", "from": 10, "to": 40})).unwrap(); - assert_eq!(out, json!({"count": 4, "ids": [id.0]})); + // `b` is 20 pt already: three characters change. + assert_eq!(out, json!({"count": 3, "ids": [id.0]})); assert_eq!(steps(&s), n + 1, "one undo step"); let sizes: Vec<(char, f64)> = styles(&s, id).into_iter().map(|(c, st)| (c, st.size)).collect(); assert_eq!(sizes, [('a', 10.0), ('b', 20.0), (' ', 20.0), ('c', 30.0), ('d', 40.0)], "the space keeps its size"); @@ -108,7 +109,8 @@ fn each_object_gets_its_own_ramp() { let (a, b) = (text(&mut s, "abc"), text(&mut s, "de")); select(&mut s, &[a, b]); let out = s.execute(C, &json!({"attribute": "rotation", "from": 0, "to": 30})).unwrap(); - assert_eq!(out["count"], json!(5)); + // Each first character is upright already. + assert_eq!(out["count"], json!(3)); let turns = |id| styles(&s, id).iter().map(|(_, st)| st.rotation).collect::>(); assert_eq!((turns(a), turns(b)), (vec![0.0, 15.0, 30.0], vec![0.0, 30.0])); } @@ -161,6 +163,19 @@ fn empty_text_and_only_spaces_change_nothing() { assert_eq!(steps(&s), n, "no step"); } +#[test] +fn characters_that_already_have_the_value_are_left_out() { + let mut s = session(); + let id = text(&mut s, "abc"); + select(&mut s, &[id]); + let p = json!({"attribute": "rotation", "from": 0, "to": 30}); + // The first character already has 0°. + assert_eq!(s.execute(C, &p).unwrap(), json!({"count": 2, "ids": [id.0]})); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + assert_eq!(s.execute(C, &p).unwrap(), json!({"count": 0, "ids": []}), "again: nothing to change"); + assert_eq!((s.doc().unwrap().doc.clone(), steps(&s)), (before, n), "no step"); +} + #[test] fn bad_params_are_refused_without_a_change() { let mut s = session(); @@ -179,6 +194,9 @@ fn bad_params_are_refused_without_a_change() { json!({"seed": -1}), json!({"skipSpaces": "yes"}), json!({"ids": [999_999]}), + json!({"id": id.0, "start": -1}), + json!({"id": id.0, "start": 1, "end": 1.5}), + json!({"end": "2"}), ] { assert!(s.execute(C, &p).is_err(), "{p}"); assert_eq!(s.doc().unwrap().doc, before, "{p}"); diff --git a/docs/mcp.md b/docs/mcp.md index 5fab5134a2..4036c1c1bc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6838,7 +6838,8 @@ there is no step. → `{symbols: [name…], ids: [instance id…], skipped: [{la Type Tools is a built-in add-on for type: its command is `addon.type.textTweaker`, and in the desktop app it lives in Object › Plug-ins › Type Tools (#4924). Text Tweaker gives one character attribute to the characters letter by letter, from a start value to an end value along a shape, as one undo step; the text stays live and editable. Each value is set -as `text.setRangeStyle` sets it (the Character panel), in its units and ranges, so on scaled type it is the size shown. +as `text.setRangeStyle` sets it (the Character panel), in its units and ranges ([formatting type](https://helpx.adobe.com/illustrator/using/formatting-type.html)), so on scaled +type it is the size shown. It changes the range of `id` (`start`/`end` bytes), else all the text of the type objects in `ids`, else the text the Type tool has selected (at a caret: all of that object's text), else all the text of every selected type object; each object gets its own ramp, and at most 100000 characters change in one run. A run that changes nothing makes no step. From 5c224a0d0810c4786638d09da4901bfb708c4380 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 21:01:27 -0800 Subject: [PATCH 008/513] Symbols: Break Link keeps the instance's opacity mask Break Link to Symbol dropped the instance's opacity mask. The art now keeps it, or a group around the art holds it when the symbol's art has a mask of its own. The objects in the instance's mask art count against Break Link's limit of 1,000,000 objects. --- crates/engine/src/cmd/brushsym.rs | 2 +- crates/engine/src/cmd/brushsym/symbols.rs | 16 +++++-- crates/engine/src/tests/brushsym.rs | 53 +++++++++++++++++++++++ docs/mcp.md | 2 +- 4 files changed, 68 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index adfb221ef7..f34ae619d6 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -201,7 +201,7 @@ pub fn specs() -> Vec { "Break Link to Symbol", [], None, - "{ids?|id?} expand selected instances into plain art (with their appearance changes to a dynamic symbol), placed through the symbol's 9-slice guides when it has them → {ids}", + "{ids?|id?} expand selected instances into plain art (with their appearance changes to a dynamic symbol), placed through the symbol's 9-slice guides when it has them, with the instance's opacity mask → {ids}", has_selection, symbol_break_link ), diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 9a3606311a..534b51506e 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -341,7 +341,8 @@ pub(super) fn symbol_place(s: &mut Session, p: &Value) -> Result { /// The plain art of instance `inst` in document space (fresh ids), with the instance's own /// appearance changes to a dynamic symbol's art when `own`, placed through its symbol's 9-slice -/// guides when it has them. +/// guides when it has them. The instance's opacity mask goes on the art, or on a group around it +/// when the art has a mask of its own. fn expanded_instance(d: &mut Document, inst: &Node, own: bool) -> Option { let NodeKind::SymbolInstance { symbol, xf } = &inst.kind else { return None }; let sym = d.symbols.iter().find(|s| &s.name == symbol)?; @@ -361,13 +362,21 @@ fn expanded_instance(d: &mut Document, inst: &Node, own: bool) -> Option { art.opacity *= inst.opacity; art.blend = inst.blend; } + if let Some(mask) = &inst.extras().mask { + if art.extras().mask.is_some() { + let id = d.alloc_id(); + art = Node::group(id, vec![Arc::new(art)]); + } + art.extras_mut().mask = Some(mask.clone()); + } Some(art) } /// The most objects [`expanded_instance`] makes of instance `inst` in `d` (`own` as there): its /// symbol's object count with the art of its opacity masks, or /// [`vectorcraft_doc::NineSliceMap::most_placed`] when it is placed through 9-slice guides, plus -/// the group that opacity or a blending mode adds. 0 for any other object. +/// the group that opacity, a blending mode or the instance's opacity mask adds, plus the art of +/// the instance's opacity mask. 0 for any other object. fn expanded_bound(d: &Document, inst: &Node, own: bool) -> u64 { let NodeKind::SymbolInstance { symbol, xf } = &inst.kind else { return 0 }; let Some(sym) = d.symbols.iter().find(|s| &s.name == symbol) else { return 0 }; @@ -378,7 +387,8 @@ fn expanded_bound(d: &Document, inst: &Node, own: bool) -> u64 { None if dynamic => vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, inst).count_with_masks() as u64, None => sym.art.count_with_masks() as u64, }; - most.saturating_add(1) + let mask = inst.extras().mask.as_ref().map_or(0, |m| m.art.count_with_masks() as u64); + most.saturating_add(1).saturating_add(mask) } /// Replace instances `ids` with their art ([`expanded_instance`], `own` as there). Returns the diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index f14ba2b6a8..c1f33ac974 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -1242,6 +1242,59 @@ fn break_link_then_update_redefines_all_instances() { assert!((bounds(&s, other).center().x - 300.0).abs() < 1e-6); } +/// A linked opacity mask of a 10 × 10 square at (100, 50). +fn square_mask(s: &mut Session) -> Box { + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let art = Node::path(doc.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(100.0, 50.0, 110.0, 60.0)), Default::default()); + Box::new(vectorcraft_doc::OpacityMask::new(art, true)) +} + +/// Break Link to Symbol keeps the instance's opacity mask on the art. +#[test] +fn break_link_keeps_the_instances_opacity_mask() { + let mut s = session(); + let (inst, _, _) = make_symbol(&mut s); + let m = square_mask(&mut s); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(inst).unwrap().extras_mut().mask = Some(m.clone()); + let r = s.execute("symbol.breakLink", &json!({"ids": [inst.0]})).unwrap(); + let art = node(&s, NodeId(r["ids"][0].as_u64().unwrap())); + assert!(matches!(art.kind, NodeKind::Path { .. }), "{}", art.kind_label()); + assert_eq!(art.extras().mask, Some(m), "the art keeps the mask"); +} + +/// When the symbol's art has an opacity mask of its own, Break Link puts the instance's mask on a +/// group around the art, and the art keeps its own. +#[test] +fn break_link_puts_the_instances_mask_on_a_group_around_masked_art() { + let mut s = session(); + let (inst, name, _) = make_symbol(&mut s); + let (own, m) = (square_mask(&mut s), square_mask(&mut s)); + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let sym = doc.symbols.iter_mut().find(|s| s.name == name).unwrap(); + std::sync::Arc::make_mut(&mut sym.art).extras_mut().mask = Some(own); + doc.node_mut(inst).unwrap().extras_mut().mask = Some(m.clone()); + let r = s.execute("symbol.breakLink", &json!({"ids": [inst.0]})).unwrap(); + let art = node(&s, NodeId(r["ids"][0].as_u64().unwrap())); + let NodeKind::Group { children, .. } = &art.kind else { panic!("a group around the art: {}", art.kind_label()) }; + assert_eq!(art.extras().mask, Some(m), "the group holds the instance's mask"); + assert!(children.len() == 1 && children[0].extras().mask.is_some(), "the art keeps its own mask"); +} + +/// The art of the instance's opacity mask counts against Break Link's object limit: an instance +/// whose mask holds more than a million objects stays an instance. +#[test] +fn break_link_counts_the_instances_mask_art() { + let mut s = session(); + let (inst, _, _) = make_symbol(&mut s); + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let square = + std::sync::Arc::new(Node::path(doc.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(100.0, 50.0, 110.0, 60.0)), Default::default())); + let art = Node::group(doc.alloc_id(), vec![square; 1_000_000]); + doc.node_mut(inst).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(art, true))); + assert!(s.execute("symbol.breakLink", &json!({"ids": [inst.0]})).is_err(), "too many objects"); + assert!(matches!(node(&s, inst).kind, NodeKind::SymbolInstance { .. }), "it stays an instance"); +} + #[test] fn delete_duplicate_and_replace_symbols() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index 4036c1c1bc..131acd9be1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1603,7 +1603,7 @@ already walks Image Trace. Short agent entry points: a symbol with guides keeps its corners at their size, and `symbol.breakLink` gives its art as it draws; dragging a guide on the canvas in symbol editing mode sends `nineSliceGuides` in one undo step; `type` is Symbol Type, `static` by default for the command and `dynamic` by default in the Symbol Options dialog), - `symbol.place {name?, x?, y?}`, `symbol.breakLink {ids?}`, `symbol.replace`, + `symbol.place {name?, x?, y?}`, `symbol.breakLink {ids?}` (the art keeps the instance's opacity mask), `symbol.replace`, `symbol.edit {id?, ids?, name?, x?, y?, artboard?, viewCenter?}` (symbol editing mode: the symbol's art on a temporary isolated layer, where the instance `id` shows it or centered on (x, y), by default on the center of artboard `artboard`, the active one the app passes, or in a document without artboards on `viewCenter`, the view's center the From f581aa8a569ba6726b563bfa0f96da5a8973b439 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 21:07:02 -0800 Subject: [PATCH 009/513] Select: the font Same commands take their reference from the type on a selected layer A layer that was selected (for example with select.set) gave no reference to Select > Same > Font Family, Font Family & Style, Font Family, Style & Size, Font Size and the text fill and stroke color commands: the layer itself is not selectable, so the type on it was never reached and the command returned "select a text object". A selected layer or sublayer now gives the type on it that can be selected. A hidden, locked or template layer gives none. --- crates/engine/src/cmd/docmenu.rs | 17 +++++++++++----- crates/engine/src/tests/menucmds.rs | 30 +++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index 413e8c401a..40f528d55b 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -328,8 +328,9 @@ fn same_text(s: &mut Session, cmd: &str, eq: fn(&CharStyle, &CharStyle) -> bool) /// Call `f` with each type object among the selected objects and inside them, in selection order, /// keeping only those [`walk_selectable`] visits: none that is hidden, locked, on a hidden, locked -/// or template layer, or outside the isolated group. A type object inside two selected objects is -/// given twice. The walk stops when `f` returns false. +/// or template layer, or outside the isolated group. A selected layer or sublayer gives the type +/// on it that passes the same test. A type object inside two selected objects is given twice. The +/// walk stops when `f` returns false. fn each_selected_text(s: &Session, mut f: impl FnMut(NodeId) -> bool) { fn inside(n: &Node, f: &mut impl FnMut(NodeId) -> bool) -> bool { if !n.visible || n.locked { @@ -340,12 +341,18 @@ fn each_selected_text(s: &Session, mut f: impl FnMut(NodeId) -> bool) { } n.children().into_iter().flatten().all(|c| inside(c, f)) } + fn from(n: &Node, selectable: &impl Fn(NodeId) -> bool, f: &mut impl FnMut(NodeId) -> bool) -> bool { + if n.is_layer() { + return n.children().into_iter().flatten().all(|c| from(c, selectable, f)); + } + !selectable(n.id) || inside(n, f) + } let Some(st) = s.active() else { return }; let locks = st.doc.locked_artboards(); + let selectable = |id| is_selectable(&st.doc, st.isolation, &locks, id); for id in &st.selection.objects { - if is_selectable(&st.doc, st.isolation, &locks, *id) - && let Some(n) = st.doc.node(*id) - && !inside(n, &mut f) + if let Some(n) = st.doc.node(*id) + && !from(n, &selectable, &mut f) { return; } diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index 18ffe69cb9..bdcbc28e2a 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -1995,6 +1995,36 @@ fn select_same_font_skips_type_that_cannot_be_selected() { assert_eq!(selected(&s), vec![g]); } +/// A selected layer gives the type on it that can be selected as the reference of the font Same +/// commands: a hidden or locked layer gives none. +#[test] +fn select_same_font_takes_its_reference_from_the_type_on_a_selected_layer() { + let mut s = session(); + let typed = + |s: &mut Session, y: f64, font: &str| id_of(&s.execute("text.create", &json!({"x": 0, "y": y, "text": "type", "font": font})).unwrap()); + let arial = typed(&mut s, 20.0, "Arial"); + let courier = typed(&mut s, 60.0, "Courier"); + let l2 = id_of(&s.execute("layer.new", &json!({"top": true})).unwrap()); + let on_layer = typed(&mut s, 100.0, "Courier"); + sel(&mut s, &[l2]); + assert_eq!(s.execute("select.same.fontFamily", &json!({})).unwrap()["count"], 2); + let mut got = selected(&s); + got.sort(); + let mut want = vec![courier, on_layer]; + want.sort(); + assert_eq!(got, want); + assert!(!selected(&s).contains(&arial)); + for (off, on) in [ + (json!({"id": l2.0, "visible": false}), json!({"id": l2.0, "visible": true})), + (json!({"id": l2.0, "locked": true}), json!({"id": l2.0, "locked": false})), + ] { + s.execute("layer.setProps", &off).unwrap(); + sel(&mut s, &[l2]); + assert!(s.execute("select.same.fontFamily", &json!({})).is_err(), "{off}"); + s.execute("layer.setProps", &on).unwrap(); + } +} + /// Select › Same › Text Fill & Stroke Color selects the type with characters whose fill and stroke /// both match the first character of the selected type: the same fill with another stroke, or the /// same stroke with another fill, is left out, and in type with several runs one run has to match From c54c4567c77500704266d3e2ff784554fab02679 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 20:22:42 -0800 Subject: [PATCH 010/513] Color controls: preserve working RGB components in numeric edits Read RGB and HSB numbers in the active working RGB space in the Color panel and Color Picker. Keep native values through hex and web-safe controls and cache live components by native color and color settings. --- crates/ui-egui/src/dialogs/color_picker.rs | 18 +- crates/ui-egui/src/menus/ui_commands.rs | 4 +- crates/ui-egui/src/panels/color.rs | 45 +++-- .../ui-egui/tests/color_working_components.rs | 155 ++++++++++++++++++ docs/mcp.md | 5 + docs/target-app-parity.md | 1 + 6 files changed, 206 insertions(+), 22 deletions(-) create mode 100644 crates/ui-egui/tests/color_working_components.rs diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index 60c037597b..8d58f21b41 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -23,7 +23,9 @@ use vectorcraft_engine::cmd::color_value; use super::form::PREVIEWED; use super::{DialogAction, DialogSpec}; -use crate::panels::color::{GAMUT_WARNING, WEB_WARNING, gamut_fix, hex_digits, is_web_safe, parse_hex, warning_chip, web_safe}; +use crate::panels::color::{ + GAMUT_WARNING, WEB_WARNING, gamut_fix, hex_digits, is_web_safe, parse_hex, warning_chip, web_safe, working_hsb, working_rgb, +}; use crate::panels::{c32, color_json}; use crate::state::Dialog; use crate::theme::Tokens; @@ -123,8 +125,9 @@ pub struct Picked { } impl Picked { + /// Read HSB from the color's native working RGB components. pub fn of(color: Color) -> Self { - Self { color, hsb: color.to_hsb() } + Self { color, hsb: working_hsb(&color) } } fn from_hsb(hsb: [f32; 3]) -> Self { Self { color: Color::from_hsb(hsb[0], hsb[1], hsb[2]), hsb } @@ -137,7 +140,7 @@ impl Picked { /// The slider value and the field point (x right, y down; 0..1 each) of a colour. pub fn field_pos(ch: Channel, p: &Picked) -> (f32, f32, f32) { - let v = if ch.is_hsb() { [p.hsb[0] / 360.0, p.hsb[1], p.hsb[2]] } else { p.color.to_rgb() }; + let v = if ch.is_hsb() { [p.hsb[0] / 360.0, p.hsb[1], p.hsb[2]] } else { working_rgb(&p.color) }; let (z, x, y) = ch.axes(); (v[z], v[x], 1.0 - v[y]) } @@ -162,7 +165,7 @@ pub fn slider_color(ch: Channel, z: f32, x: f32, y: f32) -> Color { /// The number and suffix that [`value_fields`] shows in the field of `ch` for `p`, and the field's /// largest number: H in degrees (to 360), S and B in percent (to 100), and R, G and B from 0 to 255. fn channel_value(ch: Channel, p: &Picked) -> (f32, &'static str, f32) { - let [r, g, b] = p.color.to_rgb(); + let [r, g, b] = working_rgb(&p.color); match ch { Channel::Hue => (p.hsb[0], "°", 360.0), Channel::Saturation => (p.hsb[1] * 100.0, "%", 100.0), @@ -174,6 +177,7 @@ fn channel_value(ch: Channel, p: &Picked) -> (f32, &'static str, f32) { } /// The colour the dialog holds: an edited `hex` wins over `color` (agents set either one). +/// Cached HSB is reused when it reconstructs working RGB within 1e-6 per channel. fn picked(d: &Dialog) -> Picked { let hex = d.str("hex"); let color = match parse_hex(&hex) { @@ -182,7 +186,9 @@ fn picked(d: &Dialog) -> Picked { }; let hsb = d.fields.get("__hsb").and_then(|v| serde_json::from_value::<[f32; 3]>(v.clone()).ok()); let p = match hsb { - Some(h) if Picked::from_hsb(h).color.to_hex() == color.to_hex() => Picked { color, hsb: h }, + Some(h) if working_rgb(&Picked::from_hsb(h).color).into_iter().zip(working_rgb(&color)).all(|(a, b)| (a - b).abs() <= 1e-6) => { + Picked { color, hsb: h } + } _ => Picked::of(color), }; p.snapped(d.bool("webOnly")) @@ -493,7 +499,7 @@ fn new_original_chips(ui: &mut Ui, new: &Color, original: &Color) -> bool { /// K, with a stop at each channel's radio button before its field. fn value_fields(ui: &mut Ui, p: &Picked, channel: Channel) -> (Option, Option) { let t = Tokens::get(ui.ctx()); - let rgb = p.color.to_rgb(); + let rgb = working_rgb(&p.color); let lab = p.color.to_lab(); let cms = cms::active(); let cmyk = p.color.to_cmyk_managed(cms.settings().intent); diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 92bd0ed742..a3b12f4b96 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -717,7 +717,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorPicker", "Color Picker…", "", - "{stroke?: bool (default: the active proxy), artboard?: index (the picker is for that artboard's background color instead), color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray} (default: the proxy's color, or the artboard's color, white when it has none)} open the Color Picker (fields: hex or color, channel, webOnly, swatches); OK runs paint.setFill / paint.setStroke, or artboard.setProps {index, color} for an artboard", + "{stroke?: bool (default: the active proxy), artboard?: index (the picker is for that artboard's background color instead), color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray} (default: the proxy's color, or the artboard's color, white when it has none)} open the Color Picker (fields: hex or color, channel, webOnly, swatches); RGB, HSB and hex values use the working RGB space; OK runs paint.setFill / paint.setStroke, or artboard.setProps {index, color} for an artboard", ), ( "ui.sampleScreenColor", @@ -1092,7 +1092,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorPanel", "Color Panel Options", "", - "{mode?: grayscale|rgb|hsb|cmyk|websafe, options?: bool} pick the Color panel's mode as its panel menu does (the active color converts to the mode's model as one undo step), and Show Options (true) or Hide Options (false); both are kept with the preferences (ui.inspect: ui.color_mode, ui.color_hide_options) → {mode (null: none picked yet), options, shown: the mode the panel shows the color in, or tint for a tint of a global or spot swatch}", + "{mode?: grayscale|rgb|hsb|cmyk|websafe, options?: bool} pick the Color panel's mode as its panel menu does (the active color converts to the mode's model as one undo step), and Show Options (true) or Hide Options (false); both are kept with the preferences; RGB, HSB, Web Safe RGB and hex values use the working RGB space (ui.inspect: ui.color_mode, ui.color_hide_options) → {mode (null: none picked yet), options, shown: the mode the panel shows the color in, or tint for a tint of a global or spot swatch}", ), ( "ui.savePdfDialog", diff --git a/crates/ui-egui/src/panels/color.rs b/crates/ui-egui/src/panels/color.rs index 00e32808a5..643a7ff661 100644 --- a/crates/ui-egui/src/panels/color.rs +++ b/crates/ui-egui/src/panels/color.rs @@ -16,6 +16,7 @@ use egui::{Color32, Rect, Sense, Stroke, StrokeKind, Ui, vec2}; use serde_json::{Value, json}; +use vectorcraft_color::cms; use vectorcraft_color::{Color, GradientKind, Paint}; use super::{active_paint, color_json, live_run, pstate, set_pstate}; @@ -102,7 +103,19 @@ impl Mode { } } -/// Displayed component values of `c` in `mode` (RGB 0–255, HSB °/%/%, CMYK %, K %, Lab L*a*b*). +/// The color's numeric components in the active working RGB space. +pub(crate) fn working_rgb(c: &Color) -> [f32; 3] { + let cms = cms::active(); + cms.convert(c, cms::Model::Rgb, cms.settings().intent).to_rgb_uncalibrated() +} + +/// HSB of the working RGB components, with hue in degrees. +pub(crate) fn working_hsb(c: &Color) -> [f32; 3] { + let hsb = egui::ecolor::Hsva::from_rgb(working_rgb(c)); + [hsb.h * 360.0, hsb.s, hsb.v] +} + +/// Numeric component values of `c` in `mode` (working RGB 0 to 255, HSB °/%/%, CMYK %, K %, Lab L*a*b*). pub fn components(mode: Mode, c: &Color) -> Vec { match mode { Mode::Grayscale => { @@ -115,9 +128,9 @@ pub fn components(mode: Mode, c: &Color) -> Vec { }; vec![k * 100.0] } - Mode::Rgb | Mode::WebSafe => c.to_rgb().iter().map(|v| (v * 255.0).clamp(0.0, 255.0)).collect(), + Mode::Rgb | Mode::WebSafe => working_rgb(c).iter().map(|v| (v * 255.0).clamp(0.0, 255.0)).collect(), Mode::Hsb => { - let [h, s, b] = c.to_hsb(); + let [h, s, b] = working_hsb(c); vec![h, s * 100.0, b * 100.0] } Mode::Cmyk => c.to_cmyk().iter().map(|v| v * 100.0).collect(), @@ -146,15 +159,16 @@ pub fn from_components(mode: Mode, v: &[f32]) -> Color { } } -/// The nearest web-safe colour (each channel a multiple of 0x33). +/// The nearest web-safe color (each working RGB channel a multiple of 0x33). pub fn web_safe(c: &Color) -> Color { let q = |v: f32| (v.clamp(0.0, 1.0) * 5.0).round() / 5.0; - let [r, g, b] = c.to_rgb(); + let [r, g, b] = working_rgb(c); Color::rgb(q(r), q(g), q(b)) } +/// Whether the working RGB hex value uses only web-safe channel levels. pub fn is_web_safe(c: &Color) -> bool { - web_safe(c).to_hex() == c.to_hex() + hex_digits(&web_safe(c)) == hex_digits(c) } /// Track colour of slider `i` at position `t` (0..1) with the other components fixed (dynamic @@ -190,9 +204,10 @@ pub fn spectrum_at(mode: Mode, x: f32, y: f32) -> Color { } } -/// The hex field text of a colour (`E67828`). +/// The hex field text of a color's working RGB components (`E67828`). pub fn hex_digits(c: &Color) -> String { - c.to_hex().trim_start_matches('#').to_uppercase() + let [r, g, b] = working_rgb(c).map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8); + format!("{r:02X}{g:02X}{b:02X}") } /// Parse a hex field (`E67828`, `#e67828`, `fff`). @@ -220,7 +235,7 @@ pub(crate) fn warning_chip(ui: &mut Ui, (icon, warning): (&str, &str), fix: &Col widgets::swatch_tile(ui, r, &Paint::solid(*fix), false, resp.hovered()); resp.on_hover_text(crate::i18n::fmt( tl!("{warning}: click to correct to the closest color ({hex})"), - &[("warning", tl!(warning)), ("hex", &fix.to_hex())], + &[("warning", tl!(warning)), ("hex", &format!("#{}", hex_digits(fix).to_ascii_lowercase()))], )) .clicked() }) @@ -575,6 +590,7 @@ fn spectrum(ui: &mut Ui, mode: Mode, size: egui::Vec2) -> Option { Some(SpectrumHit::Pick(spectrum_at(mode, (p.x - r.left()) / r.width(), (p.y - r.top()) / r.height()), phase)) } +/// Draw numeric paint controls, retaining live components while the color and settings match. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); let tgt = target(app, ui); @@ -597,9 +613,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } return; } - // Keep the displayed components while the colour is unchanged (hue survives S = 0 etc.). - let key = color.map(|c| (c.to_hex(), mode as u8)); - let comps: Vec = match (color, pstate::)>>(ui.ctx(), "color-comps")) { + // Keep the components while the native color and settings are unchanged (hue survives S = 0). + let settings = cms::active_settings(); + let key = color.map(|c| (c, mode as u8, settings.clone())); + let comps: Vec = match (color, pstate::)>>(ui.ctx(), "color-comps")) { (Some(_), Some((k, v))) if Some(&k) == key.as_ref() => v, (Some(c), _) => components(mode, &c), (None, _) => vec![0.0; mode.labels().len()], @@ -737,7 +754,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { apply_tint(app, &tgt, tint, t, phase); } if let Some((c, phase, comps2)) = new { - let key = (c.to_hex(), mode as u8); + let key = (c, mode as u8, settings); set_pstate(ui.ctx(), "color-comps", Some((key, comps2))); choose(app, &tgt, c, phase, false); } @@ -779,7 +796,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { if menu_item(ui, tl!("Copy Color Value (Hex)"), color.is_some(), false) && let Some(c) = color { - ui.ctx().copy_text(c.to_hex()); + ui.ctx().copy_text(format!("#{}", hex_digits(&c).to_ascii_lowercase())); } } diff --git a/crates/ui-egui/tests/color_working_components.rs b/crates/ui-egui/tests/color_working_components.rs new file mode 100644 index 0000000000..85f392416b --- /dev/null +++ b/crates/ui-egui/tests/color_working_components.rs @@ -0,0 +1,155 @@ +//! Numeric color controls edit the working RGB channels, including colors outside display sRGB. +// Integration tests may unwrap and panic (AGENTS.md, Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::sync::{Mutex, MutexGuard}; + +use serde_json::json; +use vectorcraft_color::Color; +use vectorcraft_color::cms::{self, ColorSettings, DISPLAY_P3, PROPHOTO_RGB, SRGB, WIDE_GAMUT_RGB}; +use vectorcraft_engine::Session; +use vectorcraft_ui_egui::VectorcraftApp; +use vectorcraft_ui_egui::panels::color::{Mode, components, from_components, hex_digits, parse_hex, web_safe}; + +// This integration binary contains only these tests; its app-wide CMS is independent of other +// test binaries. Serialize its cases and restore settings even when an assertion fails. +static CMS: Mutex<()> = Mutex::new(()); + +struct WorkingSpace { + previous: ColorSettings, + _lock: MutexGuard<'static, ()>, +} + +impl WorkingSpace { + /// Select a working profile for one case without retaining it after a panic. + fn new(rgb: &str) -> Self { + let lock = CMS.lock().unwrap_or_else(|e| e.into_inner()); + let previous = cms::active_settings(); + cms::set_active(&ColorSettings { rgb: rgb.into(), ..ColorSettings::default() }).unwrap(); + Self { previous, _lock: lock } + } +} + +impl Drop for WorkingSpace { + fn drop(&mut self) { + cms::set_active(&self.previous).unwrap(); + } +} + +/// Compare native channel values without converting them through the display profile. +fn native(color: Color, expected: [f32; 3]) { + let Color::Rgb { r, g, b } = color else { panic!("expected RGB, got {color:?}") }; + for (actual, expected) in [r, g, b].into_iter().zip(expected) { + assert!((actual - expected).abs() < 1e-6, "{color:?}: expected {expected}, got {actual}"); + } +} + +/// Editing R preserves the stored G and B components. +#[test] +fn rgb_edits_preserve_untouched_working_channels() { + for profile in [SRGB, DISPLAY_P3, WIDE_GAMUT_RGB, PROPHOTO_RGB] { + let _space = WorkingSpace::new(profile); + let color = Color::rgb(0.5, 0.3, 0.2); + let mut values = components(Mode::Rgb, &color); + for (actual, expected) in values.iter().zip([127.5, 76.5, 51.0]) { + assert!((actual - expected).abs() < 1e-4, "{profile}: {values:?}"); + } + values[0] = 153.0; + native(from_components(Mode::Rgb, &values), [0.6, 0.3, 0.2]); + } +} + +/// HSB describes the native RGB triplet; changing hue preserves its saturation and brightness. +#[test] +fn hsb_edits_preserve_native_saturation_and_brightness() { + for profile in [SRGB, DISPLAY_P3, WIDE_GAMUT_RGB, PROPHOTO_RGB] { + let _space = WorkingSpace::new(profile); + let mut values = components(Mode::Hsb, &Color::rgb(0.5, 0.3, 0.2)); + for (actual, expected) in values.iter().zip([20.0, 60.0, 50.0]) { + assert!((actual - expected).abs() < 1e-4, "{profile}: {values:?}"); + } + values[0] = 140.0; + native(from_components(Mode::Hsb, &values), [0.2, 0.5, 0.3]); + } +} + +/// Native primaries survive numeric round trips even when display conversion clips their gamut. +#[test] +fn numeric_roundtrips_preserve_out_of_display_gamut_colors() { + { + let _space = WorkingSpace::new(DISPLAY_P3); + let red = Color::rgb(1.0, 0.0, 0.0); + let red_with_green = Color::rgb(1.0, 0.05, 0.0); + assert_eq!(red.to_rgb(), red_with_green.to_rgb(), "display clipping loses their native distinction"); + native(from_components(Mode::Rgb, &components(Mode::Rgb, &red_with_green)), [1.0, 0.05, 0.0]); + } + for profile in [DISPLAY_P3, WIDE_GAMUT_RGB, PROPHOTO_RGB] { + let _space = WorkingSpace::new(profile); + for rgb in [[1.0, 0.2, 0.0], [0.0, 1.0, 0.2], [0.2, 0.0, 1.0]] { + let color = Color::rgb(rgb[0], rgb[1], rgb[2]); + for mode in [Mode::Rgb, Mode::Hsb] { + native(from_components(mode, &components(mode, &color)), rgb); + } + } + } +} + +/// Opening the picker reads HSB from the stored RGB components. +#[test] +fn picker_initialization_preserves_working_values() { + for profile in [SRGB, DISPLAY_P3, WIDE_GAMUT_RGB, PROPHOTO_RGB] { + let _space = WorkingSpace::new(profile); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("ui.colorPicker", json!({"color": [0.5, 0.3, 0.2]})).unwrap(); + let dialog = app.ui.dialog.as_ref().unwrap(); + let hsb = dialog.fields.get("__hsb").unwrap().as_array().unwrap(); + for (actual, expected) in hsb.iter().zip([20.0, 0.6, 0.5]) { + assert!((actual.as_f64().unwrap() - expected).abs() < 1e-4, "{profile}: {hsb:?}"); + } + } +} + +/// Shared hex and web-safe numeric controls round the native working RGB components. +#[test] +fn shared_hex_and_websafe_preserve_working_values() { + for profile in [SRGB, DISPLAY_P3, WIDE_GAMUT_RGB, PROPHOTO_RGB] { + let _space = WorkingSpace::new(profile); + let color = Color::rgb(0.5, 0.3, 0.2); + assert_eq!(hex_digits(&color), "804D33", "{profile}"); + native(parse_hex("804D33").unwrap(), [128.0 / 255.0, 77.0 / 255.0, 0.2]); + native(web_safe(&color), [0.6, 0.4, 0.2]); + } +} + +/// A panel slider click changes one native component and makes one undo step. +#[test] +fn color_panel_slider_preserves_native_channels_and_undo() { + use egui_kittest::kittest::Queryable; + + let _space = WorkingSpace::new(DISPLAY_P3); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + app.run("paint.setFill", json!({"color": [0.5, 0.3, 0.2]})).unwrap(); + let mut fonts = false; + let mut harness = egui_kittest::Harness::builder().with_size(egui::vec2(320.0, 400.0)).with_accessibility_check(false).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + vectorcraft_ui_egui::theme::install_fonts(ui.ctx()); + return; + } + vectorcraft_ui_egui::panels::color::show(app, ui); + }, + app, + ); + harness.run_steps(3); + harness.get_by_role_and_label(egui::accesskit::Role::Slider, "R").click(); + harness.run_steps(3); + let color = harness.state().session.proxy_paints().0.color().unwrap(); + let Color::Rgb { r, .. } = color else { panic!("expected RGB") }; + assert_ne!(r, 0.5, "the slider was edited"); + native(color, [r, 0.3, 0.2]); + harness.state_mut().run("edit.undo", json!({})).unwrap(); + native(harness.state().session.proxy_paints().0.color().unwrap(), [0.5, 0.3, 0.2]); +} diff --git a/docs/mcp.md b/docs/mcp.md index 131acd9be1..f8f38ede3a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -410,6 +410,11 @@ paint command (and the eyedropper) feeds. `paint.proxies` returns what the proxies show: the fill and stroke, which one is active, and whether the selected objects' fills or strokes differ (`fillMixed` / `strokeMixed`, drawn as a "?" proxy). +In the app's Color panel and Color Picker, RGB, HSB, hex and Web Safe RGB values describe the active working RGB +space. RGB edits preserve the other native channels; HSB uses those same working RGB components. Colors outside +display sRGB retain their native numeric values. `ui.colorPanel` selects the panel mode and `ui.colorPicker` +opens the picker through `run_command` with the remote backend. + | Tool | Arguments | Notes | |---|---|---| | `list_commands` | `{filter?, query?, menu?, enabledOnly?, brief?}` | The command catalogue: id, label, menu, shortcut, params doc (left out with `brief`), enablement. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6b564d9fad..4dd2258510 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1022,6 +1022,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Recolor Artwork layout (#3416):** the Edit chip list uses the modal scroll helper and its actual remaining height; the tab's minimum-height space scrolls with the chips. `tests_recolor` covers 5/20/200/400 colors, window resizing, 100/125/150/200% UI scaling, scrolling to and editing the final chip, Preview, Cancel, Confirm and Undo, alongside the existing #1733 drag regressions. Scores and estimates unchanged. - **Recolor Artwork Edit displays:** buttons beside the Edit tab's wheel show the colors on a smooth color wheel, a segmented color wheel or as color bars ([Edit colors using Recolor Artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/edit-colors-using-edit-colors-dialog.html)). The segmented wheel draws 24 hues by 5 saturations as solid patches, and its markers move freely as on the smooth wheel. The bars show one solid bar per recolored color in row order: a click selects a bar for the color sliders, and a drag moves its row without changing a color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). The dialog opens on the smooth wheel; `display` (`smooth`, `segmented`, `bars`) is the dialog field. `tests_recolor` covers switching, the dialog height, segmented dragging and Brightness, and bar selection, editing, reordering, scrolling, Preview, Cancel and OK. Scores and estimates unchanged. - **Edit Colors parameters:** `edit.colors.saturate` needs a number `intensity`, the value from -100% to 100% that Saturate takes ([Adjusting colors](https://web.archive.org/web/20230128232631/https://helpx.adobe.com/illustrator/using/adjusting-colors.html)), and answers "missing number `intensity`" without one; a number outside the range counts as its nearest end. `edit.colors.adjustBalance` refuses a channel and `color.harmony` refuses `steps` or `amount` that is not a number; both read `null` as a value left out. `tests::editcolors` and `tests::colorguide` cover them. + - **Working RGB numeric controls:** the Color panel and Color Picker read RGB, HSB, hex and Web Safe RGB values in the active working RGB space. Editing one RGB channel preserves the other native channels, including colors outside display sRGB. Regressions cover sRGB, Display P3, Wide Gamut RGB and ProPhoto RGB, picker initialization, native numeric round trips, and a slider click with one Undo step. Scores and estimates unchanged. - **Color Picker layout (#2008):** a centered draggable header, equal-width actions above aligned HSB/RGB/Hex and Lab/CMYK fields, compact field and slider, and warnings below the preview. No horizontal scrolling; narrow windows stack the sections with vertical scrolling. Tests in `dialogs/color_picker.rs` cover actual pointer/key input, typed values before OK/Enter, Cancel/Escape rollback, one Undo step, mode-size stability, warnings and layout at two UI scales. The screen sampler sits above the field and the upstream two-grid Tab order is retained. AccessKit regressions check the action names and each channel slider's displayed value, units and range. German and enlarged English UI renders were reviewed locally; no reference images are shipped. This is a layout improvement, with no change to scores or remaining-hour estimates. - **Eyedropper sources (#1251):** ordinary and Shift clicks, Shift+Alt appearance append, raster pixels and gradient-stop sampling can read visible locked/template art and sources outside isolation. Sampling leaves the source and selection intact; Alt reverse still uses editable hits, and hidden art stays excluded. Engine/tool/hit regressions cover the editing boundary, color models and one-step Undo/Redo. The general object/image workflow is described in [public HelpX](https://helpx.adobe.com/illustrator/using/tool-techniques/eyedropper-tool.html); the lock/isolation expectations come from the user report and these regressions, without a new full-parity measurement. - **Eyedropper colors in a CMYK document (#2276):** a CMYK image (a four-component JPEG, or an 8- or 16-bit chunky CMYK TIFF) gives its ink amounts as they are, and an RGB image's pixel or an RGB color given to `paint.setFill`, `paint.setStroke`, `paint.sampleColor` or `swatch.new {color}` (hex input and gradient stops included) is separated through the color settings' CMYK working space and intent, as Document Color Mode converts it. With the default Generic CMYK, RGB 83/170/223 separates to C59 M12 Y3 K0, where the profile-free formula gave C63 M24 Y0 K13. From d9cfaf9041d628950bb574eccd1b0f7fc3ff26fa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 21:32:18 -0800 Subject: [PATCH 011/513] MCP docs: vertical text uses vert alternates, and duplicate defaults to the current set add_text's vertical option turns on the OpenType vert feature, so the docs no longer say it leaves glyph orientation unchanged. ui.actionSet.duplicate uses the current set when set is omitted, with or without action. --- docs/mcp.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index f8f38ede3a..fb898da5f9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -450,8 +450,9 @@ For example, create editable Japanese area type with the engine's vertical writi ``` `vertical` also applies to point type and to `path` + `mode` (`area` or `onPath`). Omit it or pass `false` -for horizontal writing. This is the same option as `text.create` / `text.createInPath`; it does not change -the engine's existing glyph orientation or CJK composition. +for horizontal writing. This is the same option as `text.create` / `text.createInPath`. Vertical text turns +on the OpenType `vert` feature, so a font's vertical glyph alternates are used; it does not change the engine's +CJK composition. For SVG/SVGZ, `export`'s top-level `outlineText: true` writes text as paths; DXF takes it too (its type is outlined anyway unless `preserve: editability`). PDF instead uses `options: {"advanced": {"outlineText": true}}`; its default is false (live text). @@ -1810,8 +1811,8 @@ already walks Image Trace. Short agent entry points: not restore a deleted set. `ui.actionSet.duplicate {set?: index, action?: index}` copies the action at `action` in set `set` to right after it in the same set, and returns `{set, action}`; without `action` it copies the set with all its actions to right after - it, by default the current set, and returns `{set}`. The copy is named after the original with " copy" added, a - copied set gets an id of its own, and the copy is selected. An index past the last set or action is an error. The + it, and returns `{set}`. In both cases `set` defaults to the current set. The copy is named after the original with + " copy" added, a copied set gets an id of its own, and the copy is selected. An index past the last set or action is an error. The panel menu's Duplicate runs this for the selected action, else the current set. - Image Trace: `imageTrace.presets`, `imageTrace.make {id?, preset?, params?, view?}` (or `imageTrace.makeAndExpand`), `imageTrace.setView`, `imageTrace.expand`, `imageTrace.release`. A key inside `params` that is not one of the trace From 6a8e381dfac0f486ed5038d791e7570b9f41cbfb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 21:26:28 -0800 Subject: [PATCH 012/513] Actions: New Action leaves its set as the only selected set New Action in the current set of a Shift-selected range kept the whole range selected. After the new action was deleted, Delete Selection asked about every set of the range. The set recorded into is now the only selected set, as it is when Record starts a recording. --- crates/ui-egui/src/panels/actions.rs | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 8948fbef2e..bb3293a203 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -211,7 +211,7 @@ pub const NEW_ACTION: &str = "ui.action.new"; /// recording into it; Stop Playing/Recording ends the recording. `key` (1 to 15, F1 to F15; 0 or /// null for none) with `cmd` (Ctrl, Command on macOS) and `shift` is the function key that plays /// it, and `color` (one of [`COLORS`]; null or `""` for none) its Button Mode color. The action's -/// function key takes priority over command shortcuts. The set becomes current and the new action is selected. While an +/// function key takes priority over command shortcuts. The set becomes current and the only selected set, and the new action is selected. While an /// action is recording, and for an index past the last set, an empty name, a key or color that is /// not one of them, nothing is added. The New Action dialog's Record runs this. → {set, action} pub fn new_action(app: &mut VectorcraftApp, p: &Value) -> Result { @@ -235,10 +235,8 @@ pub fn new_action(app: &mut VectorcraftApp, p: &Value) -> Result s.actions.push(action); let index = s.actions.len() - 1; start_recording(app, set, name, Some(id)); - if app.ui.action_set != Some(set) { - app.ui.action_set = Some(set); - app.ui.action_sets_selected = vec![set]; - } + app.ui.action_set = Some(set); + app.ui.action_sets_selected = vec![set]; if let Some(ctx) = app.ui_ctx.clone() { set_pstate::>(&ctx, "actions-selected", Some((set, index))); } @@ -1406,6 +1404,21 @@ mod tests { assert_eq!(pstate::>(&ctx, "actions-selected"), None, "the action is no longer selected"); } + /// New Action in the current set of a Shift-selected range leaves that set as the only selected + /// one, so Delete Selection does not ask about the rest of the range afterwards. + #[test] + fn new_action_in_the_current_set_clears_the_selected_range() { + let mut app = app_with_sets(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let ctx = egui::Context::default(); + click_set(&ctx, &mut app, "Mine", egui::Modifiers::NONE); + click_set(&ctx, &mut app, "Other", egui::Modifiers::SHIFT); + assert_eq!((app.ui.action_set, app.ui.action_sets_selected.clone()), (Some(1), vec![1, 2])); + app.run(NEW_ACTION, json!({"set": 1, "name": "Fresh"})).unwrap(); + assert_eq!((app.ui.action_set, app.ui.action_sets_selected.clone()), (Some(1), vec![1])); + assert_eq!(selected_sets(&app), [1]); + } + /// The default set can be deleted, and so can the last set: the panel is then empty, no set is /// current, and New Set makes a set again. #[test] From 6cbfb83c65491efab02c327c826932c1cd8487c2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 21:10:12 -0800 Subject: [PATCH 013/513] Select: Same commands take their reference from an object that can be selected Select > Same > Fill Color, Stroke Color, Fill & Stroke, Stroke Weight, Opacity, Blending Mode, Appearance, Shape, Graphic Style and Appearance Attribute compared the other objects with the first selected object, even when select.set had put a hidden or locked object, one on a template layer or one outside the isolated group first. They now take the first selected object that the Select commands could select, in selection order, and keep the compound path and isolation rules for it. A selection that holds no such object returns "nothing selected". --- crates/engine/src/cmd/select.rs | 17 +++++++--- crates/engine/src/tests/menucmds.rs | 52 +++++++++++++++++++++++++++++ crates/engine/src/tests/styles.rs | 26 +++++++++++++++ docs/mcp.md | 6 ++++ docs/target-app-parity.md | 1 + 5 files changed, 98 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index 86e9960682..2f04b95c69 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -107,7 +107,7 @@ pub fn specs() -> Vec { "Fill Color", ["Select", "Same"], None, - "{} the objects filled with the first selected object's fill colour (any tint of its global or spot swatch, the same tint with prefs selectSameTintPercent); a member path of a compound path selected first compares as its compound path, except in isolation mode inside that compound path; from a Live Paint face, the faces of its Live Paint group only, and from any other object, no Live Paint face", + "{} the objects filled with the first selected object's fill colour (any tint of its global or spot swatch, the same tint with prefs selectSameTintPercent); a member path of a compound path selected first compares as its compound path, except in isolation mode inside that compound path; from a Live Paint face, the faces of its Live Paint group only, and from any other object, no Live Paint face; every select.same command that compares with the first selected object passes over a selected object that is hidden or locked, on a template layer or outside the isolated group", has_selection, |s, _| { let tint = s.prefs.select_same_tint_percent; @@ -686,12 +686,21 @@ fn paint_reported(d: &Document, n: &Node) -> bool { } /// The object Select > Same compares the others with, and whether isolation mode is inside a -/// compound path. The object is the first selected one, or its compound path when it is a member -/// of one; in isolation mode inside a compound path it is the member path itself. +/// compound path. The object is the first selected one that [`is_selectable`] accepts (none that is +/// hidden, locked, on a hidden, locked or template layer, or outside the isolated group), or its +/// compound path when it is a member of one; in isolation mode inside a compound path it is the +/// member path itself. fn same_reference<'a>(st: &'a DocState, cmd: &str) -> Result<(&'a Node, bool)> { let compound = |n: &Node| matches!(n.kind, NodeKind::Compound { .. }); let members = st.isolation.and_then(|i| st.doc.ancestry(i)).is_some_and(|a| a.iter().any(|i| st.doc.node(*i).is_some_and(compound))); - let first = st.selection.objects.first().and_then(|id| st.doc.node(*id)).ok_or_else(|| bad(cmd, "nothing selected"))?; + let locks = st.doc.locked_artboards(); + let first = st + .selection + .objects + .iter() + .find(|id| is_selectable(&st.doc, st.isolation, &locks, **id)) + .and_then(|id| st.doc.node(*id)) + .ok_or_else(|| bad(cmd, "nothing selected"))?; let refn = match st.doc.parent_of(first.id).and_then(|p| st.doc.node(p)) { Some(p) if !members && compound(p) => p, _ => first, diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index bdcbc28e2a..823d706532 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -2215,6 +2215,58 @@ fn select_same_matches_compound_paths_on_their_own_paint() { assert_eq!(same(&mut s, outer, "select.same.shapeType"), vec![outer, inner]); } +/// Select > Same compares the other objects with the first selected object that can be selected: +/// one that is hidden or locked, on a template layer, or outside the isolated group is passed +/// over. A selection that holds no such object has nothing to compare with. +#[test] +fn select_same_skips_a_reference_that_cannot_be_selected() { + let mut s = session(); + let [red, blue, other_blue, other_red, grouped_red] = [0.0, 20.0, 40.0, 60.0, 80.0].map(|x| rect(&mut s, x, 0.0, 10.0, 10.0)); + for id in [red, other_red, grouped_red] { + fill(&mut s, id, "#ff0000"); + } + for id in [blue, other_blue] { + fill(&mut s, id, "#0000ff"); + } + let same = |s: &mut Session, from: &[NodeId], cmd: &str| { + sel(s, from); + assert_eq!(selected(s), from, "select.set keeps {from:?}"); + s.execute(cmd, &json!({})).unwrap(); + let mut v = selected(s); + v.sort(); + v + }; + // A hidden or locked red path selected first is not the reference. + for (on, off) in [ + (json!({"id": red.0, "visible": false}), json!({"id": red.0, "visible": true})), + (json!({"id": red.0, "locked": true}), json!({"id": red.0, "locked": false})), + ] { + s.execute("layer.setProps", &on).unwrap(); + for cmd in ["select.same.fillColor", "select.same.fillAndStroke"] { + assert_eq!(same(&mut s, &[red, blue], cmd), vec![blue, other_blue], "{cmd} {on}"); + } + s.execute("layer.setProps", &off).unwrap(); + } + // A red path on a template layer is not the reference. + let l2 = id_of(&s.execute("layer.new", &json!({"top": true})).unwrap()); + let on_template = rect(&mut s, 100.0, 0.0, 10.0, 10.0); + fill(&mut s, on_template, "#ff0000"); + s.execute("layer.setProps", &json!({"id": l2.0, "template": true})).unwrap(); + assert_eq!(same(&mut s, &[on_template, blue], "select.same.fillColor"), vec![blue, other_blue]); + // A red path outside the isolated group is not the reference. + sel(&mut s, &[blue, grouped_red]); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + assert_eq!(same(&mut s, &[other_red, blue], "select.same.fillColor"), vec![blue]); + s.execute("object.exitIsolation", &json!({})).unwrap(); + // With no object that can be selected, there is nothing to compare with, and the selection stays. + s.execute("layer.setProps", &json!({"id": red.0, "visible": false})).unwrap(); + sel(&mut s, &[red, on_template]); + let r = s.execute("select.same.fillColor", &json!({})); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if *msg == "nothing selected"), "{r:?}"); + assert_eq!(selected(&s), vec![red, on_template]); +} + /// Select > Same > Fill Color and Fill & Stroke from a Live Paint face select the faces of that /// Live Paint group with the same fill, and nothing outside it. From an object outside every Live /// Paint group, they select no face. diff --git a/crates/engine/src/tests/styles.rs b/crates/engine/src/tests/styles.rs index 679186332d..3ffb2ed615 100644 --- a/crates/engine/src/tests/styles.rs +++ b/crates/engine/src/tests/styles.rs @@ -286,6 +286,32 @@ fn select_same_style_and_attribute_from_a_compound_path_member() { assert!(s.execute("select.same.graphicStyle", &json!({})).is_err()); } +/// Select > Same > Graphic Style and Appearance Attribute pass over a hidden object selected first +/// and compare the other objects with the next one. +#[test] +fn select_same_style_and_attribute_skip_a_hidden_reference() { + let mut s = session(); + let a = rect(&mut s, 10.0); + set_fill(&mut s, a, "#ff0000"); + run(&mut s, "effect.apply", json!({"effect": "distort.roughen"})); + run(&mut s, "graphicStyle.new", json!({"name": "Rough"})); + run(&mut s, "graphicStyle.apply", json!({"name": "Rough"})); + let b = rect(&mut s, 100.0); + run(&mut s, "graphicStyle.apply", json!({"name": "Rough"})); + let hidden = rect(&mut s, 200.0); + set_fill(&mut s, hidden, "#0000ff"); + run(&mut s, "graphicStyle.new", json!({"name": "Blue"})); + run(&mut s, "graphicStyle.apply", json!({"name": "Blue"})); + rect(&mut s, 300.0); + run(&mut s, "graphicStyle.apply", json!({"name": "Blue"})); + run(&mut s, "layer.setProps", json!({"id": hidden.0, "visible": false})); + for cmd in ["select.same.graphicStyle", "select.same.appearanceAttribute"] { + run(&mut s, "select.set", json!({"ids": [hidden.0, a.0]})); + run(&mut s, cmd, json!({})); + assert_eq!(s.doc().unwrap().selection.objects, vec![a, b], "{cmd}"); + } +} + #[test] fn document_info_lists_style_names() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index fb898da5f9..540dc85533 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1459,6 +1459,12 @@ selected objects and the objects inside them, in selection order, as the one to inside a hidden or locked group or layer, on a template layer, or outside the isolated group is passed over. When the selection holds no other type, they return the error "select a text object". +`select.same.fillColor`, `strokeColor`, `fillAndStroke`, `strokeWeight`, `opacity`, `blendingMode`, `appearance`, +`shapeType`, `graphicStyle` and `appearanceAttribute` compare the other objects with the first selected object, in +selection order, that these commands could select. A selected object that is hidden or locked, inside a hidden or +locked group or layer, on a template layer, or outside the isolated group is passed over. When the selection holds no other +object, they return the error "nothing selected". + ## Shaper Groups `shaper.releaseSource {source, group?}` takes the original shape `source` out of its Shaper Group: the shape becomes a diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4dd2258510..2de0db9a42 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -924,6 +924,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Select › Same › Link Block Series selects every frame of the threads of the selected type; type in no thread selects itself (`select.same.linkBlockSeries`). The menu entry is listed in [Select objects by characteristics](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects-by-characteristics.html); selecting several threads at once and type in no thread selecting itself are VectorCraft's own behavior. Select › Same › Text Fill & Stroke Color selects the type whose characters match both the fill and the stroke of the selected type (`select.same.textFillAndStrokeColor`). The menu entry is listed in [Select objects by characteristics](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects-by-characteristics.html); requiring one run of characters to match both is VectorCraft's own behavior. The Select › Same font and text color commands take the type to match from the selected type that can be selected: type that is hidden or locked, on a template layer, or outside the isolated group is passed over. This is VectorCraft's own behavior. + Select › Same › Fill Color, Stroke Color, Fill & Stroke, Stroke Weight, Opacity, Blending Mode, Appearance, Shape, Graphic Style and Appearance Attribute compare the other objects with the first selected object that can be selected: an object that is hidden or locked, on a template layer, or outside the isolated group is passed over. This is VectorCraft's own behavior. Object › Flatten Transparency takes a frame of threaded text out of the thread in the same way when Convert All Text to Outlines outlines it or when the frame becomes flat regions or an image, and the other frames keep the text they hold. New Symbol and Redefine Symbol on a frame of threaded text take it out of the thread with the text it shows, which the symbol's art holds, and the other frames keep the text they hold. When the last frame goes into the symbol, the text it has no room for goes after the text of the last frame that stays. When every frame of a thread goes into the symbol, the copy of the last frame keeps all its text. With Optical Margin Alignment on, or Roman Hanging Punctuation on in the first paragraph, the glyphs at the ends of left-to-right type on a path hang outside its brackets, measured along the path. The type hangs at the start bracket when its line is placed there, hangs at the end bracket when the line is placed there, and hangs at both when it is centered. Glyphs that hang past the end bracket do not make the type overflow, and a hang stops at an open path's end. SVG export writes such type as outlines. From a35f3a0fee547365cc10403d37e35bae14ac0f12 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 21:52:33 -0800 Subject: [PATCH 014/513] Docs: cite where a group's or layer's effect comes from in the .ai look copies entry The evidence entry for type in copies that a layer's or group's drawn look draws now cites the help page that describes effects on a group or a layer, and says that matching the page's type with a copy is VectorCraft's own rule. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2de0db9a42..8bc8372b7e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1135,7 +1135,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Legacy `.ai` saves (version 7) write type with rotated characters (Character Rotation, Touch Type turns) as its outlines, with a warning that it is no longer editable text (unless `outlineText` already asks for every type object as outlines): a version 7 text object has no character rotation ([Adobe Illustrator File Format Specification 7.0](https://www.nationalarchives.gov.uk/PRONOM/fmt/423), §15), and the outlines keep each character's rotation, baseline shift and scale (`legacy_ai::tests::type_with_rotated_characters_is_outlines_that_keep_the_rotation`). A PDF saved with Illustrator's editing data opens through it as a PDF-compatible `.ai` does, with its layers and groups and with art reaching past its page unclipped; such a PDF holds the data in `AIPDFPrivateData` streams (part of #868). A shape a PDF or `.ai` paints with a gradient (a clip path round a shading) opens as one path filled with the gradient, not a clip group round a rectangle, so Shape Builder, Live Paint and Pathfinder work on its outline (#1304). In a `.ai` opened from its editing data, a text object on a layer that shows and doesn't print stays on that layer, made from the file's text document, even where the page doesn't draw it (`crates/eps/src/import/tests_native.rs`). Such a `.ai` opens without the PDF part's warnings that text was kept as outlines when no outlined glyphs come in, and a warning counts the text objects that hold the page's type next to glyphs the page has only as outlines, which don't come in (`crates/engine/src/cmd/fileio/tests_aiimport.rs`). Where the art of a `.ai` or EPS opened from its editing data differs a little from the file's page, the warning gives the share of the page that differs away from type. When that share is 0.2% or less, the warning names the type and gives the share of the page that differs where the type is; when all the type is made from the text document, the type's share has a warning of its own beside the art's (`crates/eps/src/import/tests_native.rs`). - In a `.ai` or EPS opened from its editing data, where a layer's or group's drawn look draws a copy of art with type, the import puts the page's type that lies over the copy's other art into the copy's group, instead of giving it to other text objects by painting order. Type beside the copy's art, and every copy's type in a file past the import's text-object limits, still goes by painting order. Without a page, such a copy has no type, and no warning counts it as left out (`crates/eps/src/import/tests_native.rs`). + In a `.ai` or EPS opened from its editing data, where a layer's or group's drawn look (an effect can be attached to a group or a layer, [Vector and raster effects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/vector-and-raster-effects.html)) draws a copy of art with type, the import puts the page's type that lies over the copy's other art into the copy's group, instead of giving it to other text objects by painting order. Type beside the copy's art, and every copy's type in a file past the import's text-object limits, still goes by painting order. Without a page, such a copy has no type, and no warning counts it as left out. How the page's type is matched with a copy is VectorCraft's own rule (`crates/eps/src/import/tests_native.rs`). A `.ai` opened from its editing data keeps Effect › Pathfinder on a group with no fills or strokes of its own as a live effect, with the group's members editable: Add, shown or hidden, in its order among the group's effects. The other operations, Pathfinder Options values other than the ones the reader accepts, and the effect on a path, on type, or on a fill or stroke open as the drawn look (`crates/eps/src/import/ai/style.rs`, `pathfinder_effect`). PDF text opens with every glyph where the file draws it (#722): the font's kerning or none, whichever the file followed, word and character spacing, `TJ` adjustments and horizontal scaling kept per character as tracking, text rise as baseline shift within its line, vertical glyphs narrower than an em centred on their column (`/W2`, `/W`, `/DW`), justified text boxes with word spacing back as justified area type (`tests_text_placement`, fixtures written from ISO 32000-1 §9). A `.ai` or PDF whose editing data holds a readable variable library opens with its variable definitions, data-set rows, text, visibility and linked-file values, active row and lock in the Variables panel, whether its layers are read or it comes in as its PDF part; graph values and malformed entries are skipped with a note, and objects aren't bound yet (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). From d18499613ce38fc57f46b463409ac6a458aa0950 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 21:25:12 -0800 Subject: [PATCH 015/513] .ai save: an artboard the document does not have is refused, as an export refuses it A save as .ai or .ait (file.saveCopy, file.saveAs, document.save and file.saveAsTemplate) set range to "all" before the file was written. The one exception was a legacy .ai of version 7 given a range, which its encoder checks. Every other save accepted an artboard, artboards or range that names an artboard the document does not have (artboards: [5] on a document of three artboards) and wrote every artboard. document.export refuses the same value. The save now refuses such a value with the export's error, under the name of the command that was run, and writes no file. A range that is not text, such as range: 42, was also replaced by "all". The save now leaves it for the encoder, which refuses it as an export does. An artboard the document has, or an empty artboards list, is still saved with every artboard, and a legacy .ai still writes the artboards of its range. --- crates/engine/src/cmd/fileio/save.rs | 29 +++++++++++++- crates/engine/src/tests/legacy_ai.rs | 36 +++++++++++++++++ crates/engine/src/tests/saveoptions.rs | 53 ++++++++++++++++++++++++++ 3 files changed, 117 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index cb513e3166..b594c51b80 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -608,6 +608,28 @@ fn named_for_save(cmd: &str, e: crate::EngineError) -> crate::EngineError { } } +/// Refuse the artboards a `.ai` or `.ait` save is given (`artboard`, `artboards`, or a `range` +/// that isn't empty) when one of them is not in `doc`, with the error an export gives. The save +/// then writes every artboard, or a legacy `.ai` file's `range`, whatever `artboard` and +/// `artboards` name. An empty `artboards` list is not refused: the save writes every artboard. +fn named_artboards_exist(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result<()> { + let n = doc.artboards.len(); + // The encoders refuse a document without artboards themselves. + if n == 0 { + return Ok(()); + } + // The encoders refuse a value of the wrong type themselves, each with its own label. + let Ok(mut picked) = super::encode::options::(&written_as(cmd, f, p), p) else { + return Ok(()); + }; + picked.range = picked.range.filter(|r| !r.trim().is_empty()); + if picked.range.is_none() && picked.artboards.as_ref().is_some_and(Vec::is_empty) { + return Ok(()); + } + picked.resolve(n).map_err(|e| bad(cmd, e))?; + Ok(()) +} + /// The `.ai` option `editingData`: whether the file also carries the editing copy of the art that /// other apps read (default on). #[derive(Default, serde::Deserialize)] @@ -736,11 +758,16 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option String { + match s.execute(cmd, p) { + Err(EngineError::BadParams { cmd: c, msg }) if c == cmd => msg, + other => panic!("{cmd} {p}: {:?}", other.map(|r| r["files"].as_array().map(Vec::len))), + } +} + +#[test] +fn an_artboard_the_document_does_not_have_is_refused_as_an_export_refuses_it() { + let dir = Folder::new("ai7-no-artboard"); + let mut s = three_boards(); + let path = dir.file("Poster.ai"); + for pick in [json!({"artboards": [5]}), json!({"artboards": [0, 3]}), json!({"artboard": 3}), json!({"range": "4"})] { + let mut p = json!({"format": "ai", "aiVersion": "7"}); + p.as_object_mut().unwrap().extend(pick.as_object().unwrap().clone()); + let export = refusal(&mut s, "document.export", &p); + assert!(export.starts_with("no artboard") || export.starts_with("range `4`"), "{p}: {export}"); + assert_eq!(refusal(&mut s, "file.saveCopy", &p), export, "{p}"); + p["path"] = json!(path); + assert_eq!(refusal(&mut s, "file.saveAs", &p), export, "{p}"); + assert_eq!(refusal(&mut s, "document.save", &p), export, "{p}"); + } + // A `range` that isn't text is refused as an export refuses it. + let p = json!({"format": "ai", "aiVersion": "7", "range": 42}); + assert_eq!(refusal(&mut s, "file.saveCopy", &p), refusal(&mut s, "document.export", &p)); + assert_eq!(std::fs::read_dir(&dir.0).unwrap().count(), 0, "nothing is written"); + // An artboard the document has is saved with the artboards of the range: every one. + let r = s.execute("file.saveAs", &json!({"path": path, "format": "ai", "aiVersion": "7", "artboards": [2]})).unwrap(); + assert_eq!(r["files"].as_array().map(Vec::len), Some(3), "{r}"); + // Once that artboard is deleted, Save is not refused for it. + s.execute("artboard.delete", &json!({"index": 2})).unwrap(); + let r = s.execute("document.save", &json!({})).unwrap(); + assert_eq!(r["files"].as_array().map(Vec::len), Some(2), "{r}"); +} + /// A 32×32 PNG checkerboard of 16-pixel squares: `a` top left and bottom right, `b` elsewhere. fn checker(a: [u8; 4], b: [u8; 4]) -> Vec { let img = image::RgbaImage::from_fn(32, 32, |x, y| image::Rgba(if (x < 16) == (y < 16) { a } else { b })); diff --git a/crates/engine/src/tests/saveoptions.rs b/crates/engine/src/tests/saveoptions.rs index 130a7da18d..9324b1f4b5 100644 --- a/crates/engine/src/tests/saveoptions.rs +++ b/crates/engine/src/tests/saveoptions.rs @@ -244,6 +244,59 @@ fn ai_option_errors_name_a_file_saved_without_pdf_content() { assert!(r["warnings"].to_string().contains("`version` was not used: PDF-compatible .ai files don't read it"), "{r}"); } +/// The message of a refused command's error. +fn refusal(s: &mut Session, cmd: &str, p: &Value) -> String { + match s.execute(cmd, p) { + Err(EngineError::BadParams { cmd: c, msg }) if c == cmd => msg, + other => panic!("{cmd} {p}: {:?}", other.map(|r| r["bytes"].clone())), + } +} + +#[test] +fn an_ai_save_refuses_an_artboard_the_document_does_not_have_as_an_export_does() { + let dir = Folder::new("ai-no-artboard"); + let mut s = three_boards(); + let path = dir.file("x.ai"); + let missing = [ + json!({"artboards": [5]}), + json!({"artboards": [0, 3]}), + json!({"artboard": 3}), + json!({"range": "4"}), + json!({"separateArtboards": true, "artboards": [5]}), + ]; + let wrong_type = [json!({"artboard": "x"}), json!({"artboards": ["x"]}), json!({"range": 42})]; + for pdf in [true, false] { + for pick in missing.iter().chain(&wrong_type) { + let mut p = json!({"format": "ai", "pdfCompatible": pdf}); + p.as_object_mut().unwrap().extend(pick.as_object().unwrap().clone()); + let export = refusal(&mut s, "document.export", &p); + p["path"] = json!(path); + for cmd in ["file.saveCopy", "file.saveAs", "document.save"] { + assert_eq!(refusal(&mut s, cmd, &p), export, "{cmd} {p}"); + } + // A template is not exported: its errors name the template where they name the format. + p["format"] = json!("ait"); + let template = refusal(&mut s, "file.saveAsTemplate", &p); + if missing.contains(pick) { + assert_eq!(template, export, "{p}"); + } else { + assert!(template.contains("invalid type"), "{p}: {template}"); + } + } + } + assert_eq!(std::fs::read_dir(&dir.0).unwrap().count(), 0, "nothing is written"); + // An artboard the document has, an empty `artboards` list, or `artboards` that a `range` + // overrides is saved with every artboard, as before. + for pick in [json!({"artboards": [1]}), json!({"artboards": []}), json!({"range": "1", "artboards": [5]})] { + let mut p = json!({"format": "ai"}); + p.as_object_mut().unwrap().extend(pick.as_object().unwrap().clone()); + let r = s.execute("file.saveCopy", &p).unwrap(); + let mut o = Session::new(); + o.execute("document.open", &json!({"name": "x.ai", "dataBase64": r["dataBase64"]})).unwrap(); + assert_eq!(o.doc().unwrap().doc.artboards.len(), 3, "{p}"); + } +} + #[test] fn a_remembered_artboard_the_document_no_longer_has_is_dropped() { let dir = Folder::new("remembered-artboards"); From 8733f3c65de9777e12ecf3138a6618a28dd01abb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 22:13:33 -0800 Subject: [PATCH 016/513] Tests: the Color Picker's R, G and B fields show the working RGB values The new test opens the Color Picker in each working RGB profile and reads the R, G and B fields the dialog draws. It fails when the fields show the display sRGB values instead. --- .../ui-egui/tests/color_working_components.rs | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/crates/ui-egui/tests/color_working_components.rs b/crates/ui-egui/tests/color_working_components.rs index 85f392416b..83b0e01267 100644 --- a/crates/ui-egui/tests/color_working_components.rs +++ b/crates/ui-egui/tests/color_working_components.rs @@ -110,6 +110,39 @@ fn picker_initialization_preserves_working_values() { } } +/// The picker's R, G and B fields show the stored RGB components in every working profile. +#[test] +fn picker_rgb_fields_show_working_values() { + use egui_kittest::kittest::Queryable; + + for profile in [SRGB, DISPLAY_P3, WIDE_GAMUT_RGB, PROPHOTO_RGB] { + let _space = WorkingSpace::new(profile); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("ui.colorPicker", json!({"color": [0.6, 0.4, 0.2]})).unwrap(); + let mut fonts = false; + let mut harness = egui_kittest::Harness::builder().with_size(egui::vec2(1280.0, 900.0)).with_accessibility_check(false).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + vectorcraft_ui_egui::theme::install_fonts(ui.ctx()); + return; + } + vectorcraft_ui_egui::dialogs::show(app, ui.ctx()); + }, + app, + ); + harness.run_steps(3); + // HSB's Brightness field is also labelled B, so the fields labelled B are read together. + for (label, expected) in [("R", "153"), ("G", "102"), ("B", "51")] { + let values: Vec = harness + .query_all_by_role_and_label(egui::accesskit::Role::TextInput, label) + .filter_map(|field| field.value().map(|v| v.to_string())) + .collect(); + assert!(values.iter().any(|v| v == expected), "{profile}: {label} shows {values:?}"); + } + } +} + /// Shared hex and web-safe numeric controls round the native working RGB components. #[test] fn shared_hex_and_websafe_preserve_working_values() { From a9a2c4dee8e2b22e7b658994045795e14672e9b5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 22:03:24 -0800 Subject: [PATCH 017/513] Select: the font Same commands look through a selected group that holds the isolated group With a group isolated, a selected layer or group that holds the isolated group is not selectable itself, so the type inside the isolated group was never reached and the font Same commands returned "select a text object". The walk now goes through such a layer or group to the type inside the isolated group that can be selected. --- crates/engine/src/cmd/docmenu.rs | 21 +++++++++++++-------- crates/engine/src/tests/menucmds.rs | 24 ++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index 40f528d55b..c34c3d35bd 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -328,9 +328,9 @@ fn same_text(s: &mut Session, cmd: &str, eq: fn(&CharStyle, &CharStyle) -> bool) /// Call `f` with each type object among the selected objects and inside them, in selection order, /// keeping only those [`walk_selectable`] visits: none that is hidden, locked, on a hidden, locked -/// or template layer, or outside the isolated group. A selected layer or sublayer gives the type -/// on it that passes the same test. A type object inside two selected objects is given twice. The -/// walk stops when `f` returns false. +/// or template layer, or outside the isolated group. A selected layer or sublayer, or a selected +/// group that holds the isolated group, gives the type in it that passes the same test. A type +/// object inside two selected objects is given twice. The walk stops when `f` returns false. fn each_selected_text(s: &Session, mut f: impl FnMut(NodeId) -> bool) { fn inside(n: &Node, f: &mut impl FnMut(NodeId) -> bool) -> bool { if !n.visible || n.locked { @@ -341,18 +341,23 @@ fn each_selected_text(s: &Session, mut f: impl FnMut(NodeId) -> bool) { } n.children().into_iter().flatten().all(|c| inside(c, f)) } - fn from(n: &Node, selectable: &impl Fn(NodeId) -> bool, f: &mut impl FnMut(NodeId) -> bool) -> bool { - if n.is_layer() { - return n.children().into_iter().flatten().all(|c| from(c, selectable, f)); + fn from(n: &Node, selectable: &impl Fn(NodeId) -> bool, holds_isolated: &[NodeId], f: &mut impl FnMut(NodeId) -> bool) -> bool { + if selectable(n.id) { + return inside(n, f); } - !selectable(n.id) || inside(n, f) + if n.is_layer() || holds_isolated.contains(&n.id) { + return n.children().into_iter().flatten().all(|c| from(c, selectable, holds_isolated, f)); + } + true } let Some(st) = s.active() else { return }; let locks = st.doc.locked_artboards(); let selectable = |id| is_selectable(&st.doc, st.isolation, &locks, id); + // The isolated group and the groups and layers that hold it. + let holds_isolated = st.isolation.and_then(|i| st.doc.ancestry(i)).unwrap_or_default(); for id in &st.selection.objects { if let Some(n) = st.doc.node(*id) - && !from(n, &selectable, &mut f) + && !from(n, &selectable, &holds_isolated, &mut f) { return; } diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index 823d706532..e7750c058c 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -2025,6 +2025,30 @@ fn select_same_font_takes_its_reference_from_the_type_on_a_selected_layer() { } } +/// A selected layer that holds the isolated group gives the type inside that group as the +/// reference of the font Same commands, and not the type on the layer outside it. +#[test] +fn select_same_font_takes_its_reference_from_the_isolated_group_on_a_selected_layer() { + let mut s = session(); + let typed = + |s: &mut Session, y: f64, font: &str| id_of(&s.execute("text.create", &json!({"x": 0, "y": y, "text": "type", "font": font})).unwrap()); + let l2 = id_of(&s.execute("layer.new", &json!({"top": true})).unwrap()); + let outside = typed(&mut s, 20.0, "Arial"); + let courier = typed(&mut s, 60.0, "Courier"); + let other_courier = typed(&mut s, 100.0, "Courier"); + sel(&mut s, &[courier, other_courier]); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + sel(&mut s, &[l2]); + assert_eq!(s.execute("select.same.fontFamily", &json!({})).unwrap()["count"], 2); + let mut got = selected(&s); + got.sort(); + let mut want = vec![courier, other_courier]; + want.sort(); + assert_eq!(got, want); + assert!(!got.contains(&outside)); +} + /// Select › Same › Text Fill & Stroke Color selects the type with characters whose fill and stroke /// both match the first character of the selected type: the same fill with another stroke, or the /// same stroke with another fill, is left out, and in type with several runs one run has to match From 251cc964a5d81333236315256442ea6a14af2382 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 13:42:11 +0700 Subject: [PATCH 018/513] Actions: exclude recorded steps from playback Squashed from #5422 onto main. --- crates/ui-egui/src/dialogs/action_batch.rs | 8 +- crates/ui-egui/src/i18n/bg.tsv | 7 + crates/ui-egui/src/i18n/bs.tsv | 7 + crates/ui-egui/src/i18n/ca.tsv | 7 + crates/ui-egui/src/i18n/cs.tsv | 7 + crates/ui-egui/src/i18n/da.tsv | 7 + crates/ui-egui/src/i18n/de.tsv | 7 + crates/ui-egui/src/i18n/el.tsv | 7 + crates/ui-egui/src/i18n/es.tsv | 7 + crates/ui-egui/src/i18n/fi.tsv | 7 + crates/ui-egui/src/i18n/fr.tsv | 7 + crates/ui-egui/src/i18n/hu.tsv | 7 + crates/ui-egui/src/i18n/id.tsv | 7 + crates/ui-egui/src/i18n/it.tsv | 7 + crates/ui-egui/src/i18n/ja.tsv | 7 + crates/ui-egui/src/i18n/ka.tsv | 7 + crates/ui-egui/src/i18n/ko.tsv | 7 + crates/ui-egui/src/i18n/nl.tsv | 7 + crates/ui-egui/src/i18n/pl.tsv | 7 + crates/ui-egui/src/i18n/pt-br.tsv | 7 + crates/ui-egui/src/i18n/ru.tsv | 7 + crates/ui-egui/src/i18n/sv.tsv | 7 + crates/ui-egui/src/i18n/tr.tsv | 7 + crates/ui-egui/src/i18n/uk.tsv | 7 + crates/ui-egui/src/i18n/vi.tsv | 7 + crates/ui-egui/src/i18n/zh-hans.tsv | 7 + crates/ui-egui/src/i18n/zh-hant.tsv | 7 + crates/ui-egui/src/menus/run.rs | 1 + crates/ui-egui/src/menus/ui_commands.rs | 6 + crates/ui-egui/src/panels/actions.rs | 302 ++++++++++++++++++++- crates/ui-egui/src/panels/actions/files.rs | 31 ++- docs/mcp.md | 18 +- docs/target-app-parity.md | 4 +- 33 files changed, 530 insertions(+), 22 deletions(-) diff --git a/crates/ui-egui/src/dialogs/action_batch.rs b/crates/ui-egui/src/dialogs/action_batch.rs index aa640ade1f..3d8bfd4ace 100644 --- a/crates/ui-egui/src/dialogs/action_batch.rs +++ b/crates/ui-egui/src/dialogs/action_batch.rs @@ -20,6 +20,9 @@ pub fn open(app: &mut VectorcraftApp, set: usize, action: usize) -> Result Result { let set = d.fields.get("set").and_then(Value::as_u64).unwrap_or(0) as usize; let action = d.fields.get("action").and_then(Value::as_u64).unwrap_or(0) as usize; let a = app.ui.action_sets.get(set).and_then(|s| s.actions.get(action)).ok_or("no such action")?.clone(); - let commands: Vec = a.steps.iter().map(|(c, p)| json!({"command": c, "params": p})).collect(); + let commands = a.included_commands(); + if commands.is_empty() { + return Err("the action has no included steps".into()); + } let source = d.str("source"); if source == "folder" && d.str("folder").trim().is_empty() { return Err("choose a source folder".into()); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 4977e2599f..b37a00f29d 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -282,6 +282,9 @@ font-technology Variable Променливи Basic Latin Основни латински Batch Пакет Begin Recording Начало на запис + Exclude from playback Изключване от изпълнението + Include in playback Включване в изпълнението + Include Action Steps Включване на стъпки от действие Bend: Извиване: Bevel Join Заоблено съединение Bitmap Битова мащабна графика @@ -5444,6 +5447,10 @@ theme Appearance Външен вид @msg choose a source folder изберете изходна папка @msg open a document with data sets отворете документ с набори от данни @msg the action has no steps действието няма стъпки +@msg the action has no included steps действието няма включени стъпки +@msg no such action step няма такава стъпка от действие +@msg included must be true or false included трябва да бъде true или false +@msg others must be true or false others трябва да бъде true или false Registration: Регистрация: # Layers panel filters (Filter Layers Panel Rows) and Color Panel Options By Layer По слой diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index e11ef427db..80241a31af 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1325,6 +1325,9 @@ lighting Light Svjetlo Zoom Tool Alat za zumiranje Action {n} Akcija {n} Begin Recording Započni snimanje + Exclude from playback Isključi iz reprodukcije + Include in playback Uključi u reprodukciju + Include Action Steps Uključi korake akcije Center on Artboard Centriraj na radnoj ploči Default Actions Zadane akcije ▾ Default Actions ▾ Zadane akcije @@ -5469,6 +5472,10 @@ mark-style Japanese Japanski @msg open a document with data sets otvorite dokument sa skupovima podataka @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for ništa iz skupa podataka {name} nije primijenjeno: nijedan objekat nije vezan za varijablu za koju ima vrijednost @msg the action has no steps akcija nema koraka +@msg the action has no included steps akcija nema uključenih koraka +@msg no such action step nema takvog koraka akcije +@msg included must be true or false included mora biti true ili false +@msg others must be true or false others mora biti true ili false Accent Color Boja naglaska Amber Jantar Coral Koralna diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 1fc553a28b..95e790242c 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -437,6 +437,9 @@ Bearing Orientació Before Last: Abans de l’últim: Begin Recording Comença a enregistrar + Exclude from playback Exclou de la reproducció + Include in playback Inclou a la reproducció + Include Action Steps Inclou passos de l’acció Begin Undo Group Inicia el grup de desfets Bend: Corba: Best Millor @@ -5513,6 +5516,10 @@ digits Malayalam Malaiàlam @msg that document is no longer open aquest document ja no està obert @msg The 3D surface is too complex; simplify the shape La superfície 3D és massa complexa; simplifica la forma @msg the action has no steps l’acció no té cap pas +@msg the action has no included steps l’acció no té cap pas inclòs +@msg no such action step no existeix aquest pas d’acció +@msg included must be true or false included ha de ser true o false +@msg others must be true or false others ha de ser true o false @msg the art could not be sampled no s’ha pogut mostrejar la il·lustració @msg the art has no bounds la il·lustració no té límits @msg the art is too light for any dots la il·lustració és massa clara per a cap punt diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 6443103746..358d560600 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1348,6 +1348,9 @@ lighting Light Světlo # Panels Action {n} Akce {n} Begin Recording Zahájit záznam + Exclude from playback Vyloučit z přehrávání + Include in playback Zahrnout do přehrávání + Include Action Steps Zahrnout kroky akce Center on Artboard Vystředit na pracovní ploše Default Actions Výchozí akce ▾ Default Actions ▾ Výchozí akce @@ -5551,6 +5554,10 @@ mark-style Japanese Japonské @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for ze sady dat {name} se nic nepoužilo: žádný objekt není svázán s proměnnou, pro kterou má hodnotu @msg no bound object reports a value (locked objects and embedded images report none) žádný svázaný objekt nevrací hodnotu (zamčené objekty a vložené obrazy žádnou nevracejí) @msg the action has no steps akce nemá žádné kroky +@msg the action has no included steps akce nemá žádné zahrnuté kroky +@msg no such action step takový krok akce neexistuje +@msg included must be true or false included musí být true nebo false +@msg others must be true or false others musí být true nebo false # User Interface › Accent Color Accent Color Barva zvýraznění diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 5f4a70ae4a..8c8b830238 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1259,6 +1259,9 @@ lighting Light Lys Zoom Tool Zoomværktøj Action {n} Handling {n} Begin Recording Start optagelse + Exclude from playback Udelad fra afspilning + Include in playback Medtag i afspilning + Include Action Steps Medtag handlingstrin Center on Artboard Centrér på tegnebræt Default Actions Standardhandlinger ▾ Default Actions ▾ Standardhandlinger @@ -5206,6 +5209,10 @@ mark-style Japanese Japansk @msg choose a source folder vælg en kildemappe @msg open a document with data sets åbn et dokument med datasæt @msg the action has no steps handlingen har ingen trin +@msg the action has no included steps handlingen har ingen medtagne trin +@msg no such action step intet sådant handlingstrin +@msg included must be true or false included skal være true eller false +@msg others must be true or false others skal være true eller false Registration: Passning: By Layer Efter lag By Object Efter objekt diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 2038450a25..ffdcec8b70 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -270,6 +270,9 @@ font-technology Variable Variabel Basic Latin Lateinisch (Basis) Batch Stapelverarbeitung Begin Recording Aufzeichnung beginnen + Exclude from playback Von der Wiedergabe ausschließen + Include in playback In die Wiedergabe einbeziehen + Include Action Steps Aktionsschritte einbeziehen Bend: Biegung: Bevel Join Abgeflachte Ecke Bitmap Bitmap @@ -5128,6 +5131,10 @@ effect Soft Weich @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for aus dem Datensatz {name} wurde nichts angewendet: kein Objekt ist an eine Variable gebunden, für die er einen Wert hat @msg no bound object reports a value (locked objects and embedded images report none) kein gebundenes Objekt liefert einen Wert (gesperrte Objekte und eingebettete Bilder liefern keinen) @msg the action has no steps die Aktion hat keine Schritte +@msg the action has no included steps die Aktion hat keine einbezogenen Schritte +@msg no such action step kein solcher Aktionsschritt +@msg included must be true or false included muss true oder false sein +@msg others must be true or false others muss true oder false sein # User Interface › Accent Color Accent Color Akzentfarbe diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 807866d6e5..8fc68ba0fc 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -273,6 +273,9 @@ font-technology Variable Μεταβλητές Basic Latin Βασικά λατινικά Batch Μαζική επεξεργασία Begin Recording Έναρξη καταγραφής + Exclude from playback Εξαίρεση από την αναπαραγωγή + Include in playback Συμπερίληψη στην αναπαραγωγή + Include Action Steps Συμπερίληψη βημάτων ενέργειας Bend: Καμπυλότητα: Bevel Join Λοξότμητη ένωση Bitmap Ασπρόμαυρο bitmap @@ -5496,6 +5499,10 @@ effect Points Σημεία @msg the Simplify slider is not open ο ρυθμιστής Απλοποίησης δεν είναι ανοιχτός @msg the Smooth slider is not open ο ρυθμιστής Εξομάλυνσης δεν είναι ανοιχτός @msg the action has no steps η ενέργεια δεν έχει βήματα +@msg the action has no included steps η ενέργεια δεν έχει βήματα που συμπεριλαμβάνονται +@msg no such action step δεν υπάρχει τέτοιο βήμα ενέργειας +@msg included must be true or false Το included πρέπει να είναι true ή false +@msg others must be true or false Το others πρέπει να είναι true ή false @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer τα επίπεδα του αρχείου δεν διαβάστηκαν ({_1}): εισάγεται ως η σελίδα του, σε ένα επίπεδο @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part τα επίπεδα του αρχείου δεν διαβάστηκαν από τα δεδομένα επεξεργασίας του ({_1}): προέρχονται από το τμήμα PDF του @msg the screen color sampler is already open η δειγματοληψία χρώματος από την οθόνη είναι ήδη ανοιχτή diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index cc2f82edc7..ff63ecb215 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -295,6 +295,9 @@ font-technology Variable Variables Basic Latin Latín básico Batch Lote Begin Recording Iniciar grabación + Exclude from playback Excluir de la reproducción + Include in playback Incluir en la reproducción + Include Action Steps Incluir pasos de acción Bend: Curvatura: Bevel Join Unión biselada Bitmap Mapa de bits @@ -5492,6 +5495,10 @@ mark-style Japanese Japonesas @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for no se aplicó nada del conjunto de datos {name}: ningún objeto está vinculado a una variable para la que tenga un valor @msg no bound object reports a value (locked objects and embedded images report none) ningún objeto vinculado informa de un valor (los objetos bloqueados y las imágenes incrustadas no informan de ninguno) @msg the action has no steps la acción no tiene pasos +@msg the action has no included steps la acción no tiene pasos incluidos +@msg no such action step no existe ese paso de acción +@msg included must be true or false included debe ser true o false +@msg others must be true or false others debe ser true o false # User Interface › Accent Color Accent Color Color de acento diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index b03abbcd0c..76aa0990b8 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1322,6 +1322,9 @@ lighting Light Valo Zoom Tool Zoomaustyökalu Action {n} Toiminto {n} Begin Recording Aloita tallennus + Exclude from playback Jätä pois toistosta + Include in playback Sisällytä toistoon + Include Action Steps Sisällytä toiminnon vaiheet Center on Artboard Keskitä piirtoalustalle Default Actions Oletustoiminnot ▾ Default Actions ▾ Oletustoiminnot @@ -5508,6 +5511,10 @@ mark-style Japanese Japanilainen @msg the Simplify slider is not open Yksinkertaista-liukusäädin ei ole auki @msg the Smooth slider is not open Tasoita-liukusäädin ei ole auki @msg the action has no steps toiminnossa ei ole vaiheita +@msg the action has no included steps toiminnossa ei ole sisällytettyjä vaiheita +@msg no such action step toiminnon vaihetta ei ole +@msg included must be true or false included on oltava true tai false +@msg others must be true or false others on oltava true tai false @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer tiedoston tasoja ei luettu ({_1}): se tuodaan sivunaan yhdelle tasolle @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part tiedoston tasoja ei luettu sen muokkaustiedoista ({_1}): ne tulevat sen PDF-osasta @msg the screen color sampler is already open värin poiminta näytöltä on jo auki diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 935dc6f070..22365ad64b 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -296,6 +296,9 @@ font-technology Variable Variables Basic Latin Latin de base Batch Traitement par lots Begin Recording Démarrer l’enregistrement + Exclude from playback Exclure de l’exécution + Include in playback Inclure dans l’exécution + Include Action Steps Inclure les étapes du script Bend: Courbure : Bevel Join Sommet en biseau Bitmap Bitmap @@ -5546,6 +5549,10 @@ theme Appearance Apparence @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for rien du jeu de données {name} n’a été appliqué, car aucun objet n’est lié à une variable pour laquelle il a une valeur @msg no bound object reports a value (locked objects and embedded images report none) aucun objet lié ne fournit de valeur (les objets verrouillés et les images incorporées n’en fournissent aucune) @msg the action has no steps l'action n'a aucune étape +@msg the action has no included steps le script n’a aucune étape incluse +@msg no such action step étape de script inexistante +@msg included must be true or false included doit valoir true ou false +@msg others must be true or false others doit valoir true ou false # User Interface › Accent Color Accent Color Couleur d’accent diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 363db7e265..9523bca336 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -398,6 +398,9 @@ font-technology Variable Változó Batch Kötegelt feldolgozás Bearing Irány Begin Recording Felvétel indítása + Exclude from playback Kizárás a lejátszásból + Include in playback Bevonás a lejátszásba + Include Action Steps Műveletlépések bevonása Begin Undo Group Visszavonási csoport kezdete Bend: Hajlítás mértéke: Best Legjobb @@ -5534,6 +5537,10 @@ imageTrace Outline Körvonal @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for ebből az adatkészletből semmi sem lett alkalmazva: {name}; egyetlen objektum sincs olyan változóhoz kötve, amelynek értéke van benne @msg no bound object reports a value (locked objects and embedded images report none) egyetlen kötött objektum sem ad értéket (a zárolt objektumok és a beágyazott képek nem adnak értéket) @msg the action has no steps a műveletnek nincsenek lépései +@msg the action has no included steps a műveletnek nincsenek bevont lépései +@msg no such action step nincs ilyen műveletlépés +@msg included must be true or false included: true vagy false kell +@msg others must be true or false others: true vagy false kell # User Interface › Accent Color Accent Color Kiemelőszín diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 7faf03f43a..15969f1da1 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1259,6 +1259,9 @@ lighting Light Cahaya Zoom Tool Alat zoom Action {n} Aksi {n} Begin Recording Mulai merekam + Exclude from playback Kecualikan dari pemutaran + Include in playback Sertakan dalam pemutaran + Include Action Steps Sertakan langkah aksi Center on Artboard Pusatkan di artboard Default Actions Aksi default ▾ Default Actions ▾ Aksi default @@ -5206,6 +5209,10 @@ mark-style Japanese Jepang @msg choose a source folder pilih folder sumber @msg open a document with data sets buka dokumen dengan himpunan data @msg the action has no steps action tidak memiliki langkah +@msg the action has no included steps aksi tidak memiliki langkah yang disertakan +@msg no such action step tidak ada langkah aksi seperti itu +@msg included must be true or false included harus true atau false +@msg others must be true or false others harus true atau false Registration: Registrasi: By Layer Per lapisan By Object Per objek diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 1c34cd4dfb..93ac2c95d2 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -295,6 +295,9 @@ font-technology Variable Variabili Basic Latin Latino di base Batch Elaborazione batch Begin Recording Avvia registrazione + Exclude from playback Escludi dall'esecuzione + Include in playback Includi nell'esecuzione + Include Action Steps Includi passaggi azione Bend: Curvatura: Bevel Join Unione smussata Bitmap Bitmap @@ -5163,6 +5166,10 @@ lighting Light Luce @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for non è stato applicato nulla del set di dati {name}: nessun oggetto è associato a una variabile per cui ha un valore @msg no bound object reports a value (locked objects and embedded images report none) nessun oggetto associato restituisce un valore (gli oggetti bloccati e le immagini incorporate non ne restituiscono) @msg the action has no steps l'azione non ha passaggi +@msg the action has no included steps l'azione non ha passaggi inclusi +@msg no such action step passaggio dell'azione inesistente +@msg included must be true or false included deve essere true o false +@msg others must be true or false others deve essere true o false # User Interface › Accent Color Accent Color Colore di risalto diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index f1cf9a5378..4fa88c824e 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1035,6 +1035,9 @@ digits Malayalam マラヤーラム数字 Baseline Shift ベースラインシフト Batch バッチ Begin Recording 記録を開始 + Exclude from playback 再生から除外 + Include in playback 再生に含める + Include Action Steps アクションステップを含める Bend: カーブ: Bevel Join ベベル結合 Bitmap ビットマップ @@ -5206,6 +5209,10 @@ lighting Light ライト @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for データセット {name} から何も適用されませんでした: 値のある変数にバインドされたオブジェクトがありません @msg no bound object reports a value (locked objects and embedded images report none) 値を返すバインドされたオブジェクトがありません (ロックされたオブジェクトと埋め込み画像は値を返しません) @msg the action has no steps アクションにステップがありません +@msg the action has no included steps アクションに含まれるステップがありません +@msg no such action step 指定されたアクションステップが見つかりません +@msg included must be true or false included には true または false を指定してください +@msg others must be true or false others には true または false を指定してください # User Interface › Accent Color Accent Color アクセントカラー diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 87e32accb8..d3556f4434 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1187,6 +1187,9 @@ lighting Light სინათლე Zoom Tool მასშტაბის ხელსაწყო Action {n} მოქმედება {n} Begin Recording ჩაწერის დაწყება + Exclude from playback შესრულებიდან გამორიცხვა + Include in playback შესრულებაში ჩართვა + Include Action Steps მოქმედების ნაბიჯების ჩართვა Center on Artboard სამუშაო დაფის ცენტრში მოთავსება Default Actions ნაგულისხმევი მოქმედებები Duplicate and Offset 10 pt დუბლირება და 10 pt-ით წანაცვლება @@ -5193,6 +5196,10 @@ imageTrace Outline კონტური @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for მონაცემთა ნაკრები {name}: არაფერი გამოყენებულა; არცერთი ობიექტი არ არის მიბმული ცვლადზე, რომელსაც მასში მნიშვნელობა აქვს @msg no bound object reports a value (locked objects and embedded images report none) არცერთი მიბმული ობიექტი არ აბრუნებს მნიშვნელობას (ჩაკეტილი ობიექტები და ჩაშენებული გამოსახულებები მნიშვნელობას არ აბრუნებს) @msg the action has no steps მოქმედებას ნაბიჯები არ აქვს +@msg the action has no included steps მოქმედებას ჩართული ნაბიჯები არ აქვს +@msg no such action step მოქმედების ასეთი ნაბიჯი არ არის +@msg included must be true or false included უნდა იყოს true ან false +@msg others must be true or false others უნდა იყოს true ან false Convert to Straight Lines სწორ ხაზებად გარდაქმნა Corner Point Angle Threshold: კუთხოვანი წერტილის კუთხის ზღვარი: Decrease Font Size by Five Steps შრიფტის შემცირება ხუთი საფეხურით diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index bc96cb4478..b6e935e2ef 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1025,6 +1025,9 @@ digits Malayalam 말라얄람어 Baseline Shift 기준선 이동 Batch 일괄 처리 Begin Recording 기록 시작 + Exclude from playback 재생에서 제외 + Include in playback 재생에 포함 + Include Action Steps 액션 단계 포함 Bend: 구부리기: Bevel Join 베벨 조인 Bitmap 비트맵 @@ -5124,6 +5127,10 @@ lighting Light 광원 @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for 데이터 세트 {name}에서 적용된 항목이 없습니다: 값이 있는 변수에 연결된 개체가 없습니다 @msg no bound object reports a value (locked objects and embedded images report none) 값을 보고하는 연결된 개체가 없습니다(잠긴 개체와 포함된 이미지는 값을 보고하지 않습니다) @msg the action has no steps 액션에 단계가 없습니다 +@msg the action has no included steps 액션에 포함된 단계가 없습니다 +@msg no such action step 해당 액션 단계가 없습니다 +@msg included must be true or false included의 값은 true 또는 false여야 합니다 +@msg others must be true or false others의 값은 true 또는 false여야 합니다 # User Interface › Accent Color Accent Color 강조 색상 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index ddaa5df323..2d2dcccf19 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1273,6 +1273,9 @@ lighting Light Licht Zoom Tool Zoom-gereedschap Action {n} Actie {n} Begin Recording Opname starten + Exclude from playback Uitsluiten van afspelen + Include in playback Insluiten bij afspelen + Include Action Steps Actiestappen insluiten Center on Artboard Centreren op tekengebied Default Actions Standaardacties ▾ Default Actions ▾ Standaardacties @@ -5214,6 +5217,10 @@ mark-style Japanese Japans @msg choose a source folder kies een bronmap @msg open a document with data sets open een document met gegevenssets @msg the action has no steps de actie heeft geen stappen +@msg the action has no included steps de actie heeft geen ingesloten stappen +@msg no such action step actiestap bestaat niet +@msg included must be true or false included moet true of false zijn +@msg others must be true or false others moet true of false zijn Registration: Passermarkering: By Layer Per laag By Object Per object diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 8dd10bf76b..d30c71807d 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1263,6 +1263,9 @@ lighting Light Światło Zoom Tool Narzędzie Lupka Action {n} Operacja {n} Begin Recording Rozpocznij nagrywanie + Exclude from playback Wyklucz z odtwarzania + Include in playback Uwzględnij w odtwarzaniu + Include Action Steps Uwzględnij kroki operacji Center on Artboard Wyśrodkuj na obszarze kompozycji Default Actions Operacje domyślne Duplicate and Offset 10 pt Powiel i odsuń o 10 pt @@ -5403,6 +5406,10 @@ mark-style Japanese Japońskie @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for z zestawu danych {name} nic nie zastosowano: żaden obiekt nie jest powiązany ze zmienną, dla której ma on wartość @msg no bound object reports a value (locked objects and embedded images report none) żaden powiązany obiekt nie zwraca wartości (zablokowane obiekty i osadzone obrazy nie zwracają żadnej) @msg the action has no steps operacja nie ma kroków +@msg the action has no included steps operacja nie ma uwzględnionych kroków +@msg no such action step brak takiego kroku operacji +@msg included must be true or false included musi mieć wartość true lub false +@msg others must be true or false others musi mieć wartość true lub false # User Interface › Accent Color Accent Color Kolor akcentu diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 33a3f312fc..9bde60f446 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -278,6 +278,9 @@ Baseline Shift Deslocamento da Linha de Base Batch Lote Begin Recording Começar a Gravar + Exclude from playback Excluir da reprodução + Include in playback Incluir na reprodução + Include Action Steps Incluir Etapas da Ação Bend: Curvar: Bevel Join Junção em Bisel Bitmap Bitmap @@ -5424,6 +5427,10 @@ mark-style Japanese Japonesas @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for nada do conjunto de dados {name} foi aplicado: nenhum objeto está vinculado a uma variável para a qual ele tem um valor @msg no bound object reports a value (locked objects and embedded images report none) nenhum objeto vinculado informa um valor (objetos bloqueados e imagens incorporadas não informam nenhum) @msg the action has no steps a ação não tem etapas +@msg the action has no included steps a ação não tem etapas incluídas +@msg no such action step etapa de ação inexistente +@msg included must be true or false included deve ser true ou false +@msg others must be true or false others deve ser true ou false @msg Angles require two straight segments Ângulos exigem dois segmentos retos @msg Choose a circle or a perfect arc Escolha um círculo ou um arco perfeito @msg Choose a precision from 0 to 6 Escolha uma precisão de 0 a 6 diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 08c587c209..0e55857a6b 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -293,6 +293,9 @@ font-technology Variable Вариативные Basic Latin Основная латиница Batch Пакет Begin Recording Начать запись + Exclude from playback Исключить из воспроизведения + Include in playback Включить в воспроизведение + Include Action Steps Включить шаги действия Bend: Изгиб: Bevel Join Скос соединения Bitmap Растровое изображение @@ -5158,6 +5161,10 @@ lighting Light Свет @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for из набора данных {name} ничего не применено: ни один объект не привязан к переменной, для которой в нём есть значение @msg no bound object reports a value (locked objects and embedded images report none) ни один привязанный объект не сообщает значение (заблокированные объекты и внедрённые изображения не сообщают значений) @msg the action has no steps в действии нет шагов +@msg the action has no included steps в действии нет включённых шагов +@msg no such action step такого шага действия нет +@msg included must be true or false included должно быть true или false +@msg others must be true or false others должно быть true или false # User Interface › Accent Color Accent Color Цвет акцента diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index b9112257c2..49c81d06b7 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -284,6 +284,9 @@ font-technology Variable Variabla Basic Latin Grundläggande latin Batch Batch Begin Recording Börja spela in + Exclude from playback Uteslut från uppspelning + Include in playback Ta med i uppspelning + Include Action Steps Ta med åtgärdssteg Bend: Böjning: Bevel Join Fasad fog Bitmap Bitmapp @@ -5500,6 +5503,10 @@ theme Appearance Utseende @msg the Simplify slider is not open Förenkla-reglaget är inte öppet @msg the Smooth slider is not open Jämna ut-reglaget är inte öppet @msg the action has no steps åtgärden har inga steg +@msg the action has no included steps åtgärden har inga medtagna steg +@msg no such action step åtgärdssteget finns inte +@msg included must be true or false included måste vara true eller false +@msg others must be true or false others måste vara true eller false @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer filens lager lästes inte ({_1}): den hämtas in som en sida, i ett enda lager @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part filens lager lästes inte från dess redigeringsdata ({_1}): de kommer från dess PDF-del @msg the screen color sampler is already open färghämtningen från skärmen är redan öppen diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index df46c7f2ba..3dfae8af33 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -280,6 +280,9 @@ font-technology Variable Değişken Basic Latin Temel Latince Batch Toplu Begin Recording Kaydı Başlat + Exclude from playback Oynatmadan hariç tut + Include in playback Oynatmaya dahil et + Include Action Steps Eylem Adımlarını Dahil Et Bend: Bükülme: Bevel Join Eğimli Birleştirme Bitmap Bit eşlem @@ -5226,6 +5229,10 @@ theme Appearance Görünüm @msg choose a source folder bir kaynak klasör seçin @msg open a document with data sets veri kümeleri içeren bir belge açın @msg the action has no steps eylemin hiçbir adımı yok +@msg the action has no included steps eylemin dahil edilmiş adımı yok +@msg no such action step öyle bir eylem adımı yok +@msg included must be true or false "included" true veya false olmalıdır +@msg others must be true or false "others" true veya false olmalıdır Accent Color Vurgu Rengi Amber kehribar Coral Mercan diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 7d0aed742d..5d37cd09c3 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -289,6 +289,9 @@ font-technology Variable Варіативні Basic Latin Основна латиниця Batch Пакет Begin Recording Почати запис + Exclude from playback Виключити з відтворення + Include in playback Включити до відтворення + Include Action Steps Включити кроки дії Bend: Вигин: Bevel Join Скошене з’єднання Bitmap Растрове зображення @@ -5143,6 +5146,10 @@ lighting Light Світло @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for з набору даних {name} нічого не застосовано: жоден об’єкт не прив’язано до змінної, для якої в ньому є значення @msg no bound object reports a value (locked objects and embedded images report none) жоден прив’язаний об’єкт не повідомляє значення (заблоковані об’єкти та вбудовані зображення не повідомляють значень) @msg the action has no steps у дії немає кроків +@msg the action has no included steps у дії немає включених кроків +@msg no such action step такого кроку дії немає +@msg included must be true or false included має бути true або false +@msg others must be true or false others має бути true або false # User Interface › Accent Color Accent Color Колір акценту diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index eddc7d5293..12fe935929 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -320,6 +320,9 @@ font-technology Variable Biến thiên Batch Hàng loạt Bearing Hướng Begin Recording Bắt đầu ghi + Exclude from playback Loại khỏi phát lại + Include in playback Đưa vào phát lại + Include Action Steps Đưa các bước hành động vào Begin Undo Group Bắt đầu nhóm hoàn tác Bend: Uốn cong: Best Tốt nhất @@ -5144,6 +5147,10 @@ theme Appearance Giao diện @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for không có gì trong tập dữ liệu {name} được áp dụng: không có đối tượng nào được gắn với biến số mà tập dữ liệu có giá trị @msg no bound object reports a value (locked objects and embedded images report none) không có đối tượng được gắn nào báo cáo giá trị (đối tượng bị khóa và hình ảnh nhúng không báo cáo giá trị nào) @msg the action has no steps hành động không có bước nào +@msg the action has no included steps hành động không có bước nào được đưa vào +@msg no such action step không có bước hành động như vậy +@msg included must be true or false included phải là true hoặc false +@msg others must be true or false others phải là true hoặc false # User Interface › Accent Color Accent Color Màu nhấn diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 72c26ec252..d9e5f84b42 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -241,6 +241,9 @@ Basic Latin 基本拉丁文 Batch 批处理 Begin Recording 开始记录 + Exclude from playback 从播放中排除 + Include in playback 包含在播放中 + Include Action Steps 包含动作步骤 Bend: 弯曲: Bevel Join 斜角连接 Bitmap 位图 @@ -4602,6 +4605,10 @@ imageTrace Outline 轮廓 @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for 数据集 {name} 未应用任何内容:没有对象绑定到该数据集中有值的变量 @msg no bound object reports a value (locked objects and embedded images report none) 没有绑定的对象报告值 (锁定的对象和嵌入的图像不报告值) @msg the action has no steps 该动作没有步骤 +@msg the action has no included steps 该动作没有包含的步骤 +@msg no such action step 没有此动作步骤 +@msg included must be true or false included 必须是 true 或 false +@msg others must be true or false others 必须是 true 或 false # Import Shortcut Set (Keyboard Shortcuts › Import…, File › Open of a .kys file) and its commands. Import Shortcut Set 导入快捷键组 Import Shortcut Set… 导入快捷键组… diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 4b9a52bf0b..b387b0a810 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -254,6 +254,9 @@ font-technology Variable 可變 Basic Latin 基本拉丁文 Batch 批次 Begin Recording 開始錄製 + Exclude from playback 從播放中排除 + Include in playback 包含在播放中 + Include Action Steps 包含動作步驟 Bend: 彎曲: Bevel Join 斜角 Bitmap 點陣圖 @@ -2494,6 +2497,10 @@ file-filter Templates 範本 @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for 資料集 {name} 未套用任何內容:沒有物件綁定到該資料集中有值的變數 @msg no bound object reports a value (locked objects and embedded images report none) 沒有綁定的物件回報值 (鎖定的物件和內嵌的影像不回報值) @msg the action has no steps 動作沒有步驟 +@msg the action has no included steps 動作沒有包含的步驟 +@msg no such action step 沒有這個動作步驟 +@msg included must be true or false included 必須是 true 或 false +@msg others must be true or false others 必須是 true 或 false @msg cancelled; nothing was changed 已取消;未做任何變更 @msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it 「儲存」會寫入 {_1},而非 {_2}:若要寫入該格式,請使用 file.saveAsTemplate @msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 會寫入舊版 .ai 檔案,不會寫入 .ait 範本 diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 1666e147ec..f54153cbdf 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -820,6 +820,7 @@ fn run_ui_part11(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::dialogs::package::open(app), crate::panels::actions::RENAME_ACTION => crate::panels::actions::rename_action(app, p), + crate::panels::actions::INCLUDE_STEPS => crate::panels::actions::include_steps(app, p), crate::panels::actions::NEW_ACTION => crate::panels::actions::new_action(app, p), crate::panels::actions::ACTION_OPTIONS => crate::panels::actions::action_options(app, p), crate::panels::actions::PLAY_ACTION => crate::panels::actions::play_action(app, p), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index a3b12f4b96..1356a2cef2 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1211,6 +1211,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{set: index, action: index, name} rename the Actions panel's action at action in set (0 is the top set) to name, with spaces trimmed from both ends; its steps, function key and color stay. An index past the last set or action, or an empty name, is an error and renames nothing → {name}", ), + ( + crate::panels::actions::INCLUDE_STEPS, + "Include Action Steps", + "", + "{set: index, action?: index, step?: index, included: bool, others?: bool} include or exclude the playback of every step in a set, every step in one action, or one step. With a step and others: true, leave that step unchanged and apply included to every other step in its action (Alt/Option-click). Invalid indexes change nothing → {set, action?, step?, included}", + ), ( crate::panels::actions::NEW_ACTION, "New Action", diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index bb3293a203..7c9edc6a55 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -4,6 +4,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; +use std::collections::BTreeSet; use super::{pstate, set_pstate}; use crate::theme::Tokens; @@ -23,6 +24,10 @@ pub struct Action { pub id: u64, pub name: String, pub steps: Vec<(String, Value)>, + /// Step indexes omitted from playback. A sidecar keeps existing recorded command pairs and + /// their params unchanged; newly recorded steps are included by default. + #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] + pub excluded_steps: BTreeSet, /// The function key that plays the action when shortcuts are read, if one is assigned. A /// saved value that is not a function key loads as none. #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_key")] @@ -36,7 +41,7 @@ pub struct Action { impl Action { /// An action with a new [`Action::id`], no function key and no color. pub fn new(name: impl Into, steps: Vec<(String, Value)>) -> Self { - Self { id: next_action_id(), name: name.into(), steps, key: None, color: None } + Self { id: next_action_id(), name: name.into(), steps, excluded_steps: BTreeSet::new(), key: None, color: None } } /// A copy of the action with a new [`Action::id`] and no function key, so the key still plays @@ -44,6 +49,26 @@ impl Action { pub fn copy(&self) -> Self { Self { id: next_action_id(), key: None, ..self.clone() } } + + fn all_steps_included(&self) -> bool { + (0..self.steps.len()).all(|i| !self.excluded_steps.contains(&i)) + } + + fn set_steps_included(&mut self, included: bool) { + self.excluded_steps.clear(); + if !included { + self.excluded_steps.extend(0..self.steps.len()); + } + } + + pub(crate) fn included_commands(&self) -> Vec { + self.steps + .iter() + .enumerate() + .filter(|(i, _)| !self.excluded_steps.contains(i)) + .map(|(_, (command, params))| json!({"command": command, "params": params})) + .collect() + } } /// An action id no other action in this run has. @@ -181,10 +206,65 @@ pub fn default_sets() -> Vec { /// Run an action as a single undoable batch. pub fn play(app: &mut VectorcraftApp, set: usize, idx: usize) -> Result { let Some(a) = app.ui.action_sets.get(set).and_then(|s| s.actions.get(idx)).cloned() else { return Err("no such action".into()) }; - let commands: Vec = a.steps.iter().map(|(c, p)| json!({"command": c, "params": p})).collect(); + let commands = a.included_commands(); + if commands.is_empty() { + return Err("the action has no included steps".into()); + } app.run("command.batch", json!({"label": a.name, "commands": commands})) } +/// The command behind the Actions panel's set, action and step checkmarks. +pub const INCLUDE_STEPS: &str = "ui.action.stepsIncluded"; + +/// `{set, action?, step?, included, others?}` includes or excludes all steps of a set, all steps +/// of one action, or one step. With `step` and `others: true`, leaves that step as it was and +/// applies `included` to the other steps of its action. Invalid indexes change nothing. +pub fn include_steps(app: &mut VectorcraftApp, p: &Value) -> Result { + let index = |key: &str| p.get(key).and_then(Value::as_u64).and_then(|n| usize::try_from(n).ok()); + let set = index("set").ok_or("no such action set")?; + let included = p.get("included").and_then(Value::as_bool).ok_or("included must be true or false")?; + let others = match p.get("others") { + None => false, + Some(Value::Bool(value)) => *value, + _ => return Err("others must be true or false".into()), + }; + let action = if p.get("action").is_some() { Some(index("action").ok_or("no such action")?) } else { None }; + let step = if p.get("step").is_some() { Some(index("step").ok_or("no such action step")?) } else { None }; + if (step.is_some() && action.is_none()) || (others && step.is_none()) { + return Err("no such action step".into()); + } + let set_ref = app.ui.action_sets.get_mut(set).ok_or("no such action set")?; + match (action, step) { + (None, None) => { + for action in &mut set_ref.actions { + action.set_steps_included(included); + } + } + (Some(ai), None) => set_ref.actions.get_mut(ai).ok_or("no such action")?.set_steps_included(included), + (Some(ai), Some(si)) => { + let action = set_ref.actions.get_mut(ai).ok_or("no such action")?; + if si >= action.steps.len() { + return Err("no such action step".into()); + } + if others { + let was_excluded = action.excluded_steps.contains(&si); + action.set_steps_included(included); + if was_excluded { + action.excluded_steps.insert(si); + } else { + action.excluded_steps.remove(&si); + } + } else if included { + action.excluded_steps.remove(&si); + } else { + action.excluded_steps.insert(si); + } + } + (None, Some(_)) => return Err("no such action step".into()), + } + Ok(json!({"set": set, "action": action, "step": step, "included": included})) +} + /// The command that renames an action ([`rename_action`]). pub const RENAME_ACTION: &str = "ui.action.rename"; @@ -737,6 +817,42 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut egui::Ui) { } } +fn inclusion_box( + ui: &mut egui::Ui, + row: egui::Rect, + x: f32, + id: impl std::hash::Hash + std::fmt::Debug, + included: bool, + mixed: bool, +) -> (bool, egui::Rect) { + let t = Tokens::get(ui.ctx()); + let hit = egui::Rect::from_center_size(egui::pos2(row.left() + x, row.center().y), egui::vec2(18.0, 18.0)); + let response = ui.interact(hit, ui.scope_id().with(id), egui::Sense::click()); + let box_rect = egui::Rect::from_center_size(hit.center(), egui::vec2(11.0, 11.0)); + ui.painter().rect_stroke( + box_rect, + 1.0, + egui::Stroke::new(1.0, if response.hovered() { t.text_strong } else { t.icon }), + egui::StrokeKind::Inside, + ); + if included || mixed { + ui.painter().text( + box_rect.center(), + egui::Align2::CENTER_CENTER, + if mixed { "−" } else { "✓" }, + egui::FontId::proportional(12.0), + t.text_strong, + ); + } + (response.on_hover_text(if included { tl!("Exclude from playback") } else { tl!("Include in playback") }).clicked(), hit) +} + +enum InclusionChange { + Set(usize), + Action(usize, usize), + Step(usize, usize, usize, bool), +} + pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); // The selected action as (set, action). Read as the type it is stored as: egui keeps a @@ -751,6 +867,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { let mut current = app.ui.action_set; let mut sets_selected = selected_sets(app); let shift = ui.input(|i| i.modifiers.shift); + let alt = ui.input(|i| i.modifiers.alt); + let mut expanded: BTreeSet = pstate(ui.ctx(), "actions-expanded"); + let mut inclusion_changes = Vec::new(); let mut play_req = None; egui::ScrollArea::vertical().max_height(260.0).show(ui, |ui| { for (si, set) in app.ui.action_sets.iter().enumerate() { @@ -760,8 +879,21 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { } else if resp.hovered() { ui.painter().rect_filled(r, 0.0, t.hover); } - ui.painter().text(r.left_center(), egui::Align2::LEFT_CENTER, format!("▾ {}", set.name), egui::FontId::proportional(12.5), t.text); - if resp.clicked() { + let step_count: usize = set.actions.iter().map(|a| a.steps.len()).sum(); + let excluded_count: usize = set.actions.iter().map(|a| (0..a.steps.len()).filter(|i| a.excluded_steps.contains(i)).count()).sum(); + let (check_clicked, check_rect) = + inclusion_box(ui, r, 10.0, ("set-inclusion", set.id), excluded_count == 0, excluded_count > 0 && excluded_count < step_count); + if check_clicked && step_count > 0 { + inclusion_changes.push(InclusionChange::Set(si)); + } + ui.painter().text( + r.left_center() + egui::vec2(22.0, 0.0), + egui::Align2::LEFT_CENTER, + format!("▾ {}", set.name), + egui::FontId::proportional(12.5), + t.text, + ); + if resp.clicked() && !resp.interact_pointer_pos().is_some_and(|p| check_rect.contains(p)) { // Shift-click selects the sets from the current one to the one clicked; the current // set stays as it was. match current { @@ -781,8 +913,26 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { } else if resp.hovered() { ui.painter().rect_filled(r, 0.0, t.hover); } + let excluded = (0..a.steps.len()).filter(|i| a.excluded_steps.contains(i)).count(); + let (check_clicked, check_rect) = + inclusion_box(ui, r, 10.0, ("action-inclusion", a.id), excluded == 0, excluded > 0 && excluded < a.steps.len()); + if check_clicked && !a.steps.is_empty() { + inclusion_changes.push(InclusionChange::Action(si, ai)); + } + let disclosure = egui::Rect::from_center_size(egui::pos2(r.left() + 29.0, r.center().y), egui::vec2(18.0, 18.0)); + let disclosure_resp = ui.interact(disclosure, ui.scope_id().with(("action-disclosure", a.id)), egui::Sense::click()); + let open = expanded.contains(&a.id); + icons::paint( + ui, + if open { "chevron-down" } else { "chevron-right" }, + disclosure, + if disclosure_resp.hovered() { t.text_strong } else { t.icon }, + ); + if disclosure_resp.clicked() && !expanded.insert(a.id) { + expanded.remove(&a.id); + } ui.painter().text( - r.left_center() + egui::vec2(18.0, 0.0), + r.left_center() + egui::vec2(42.0, 0.0), egui::Align2::LEFT_CENTER, &a.name, egui::FontId::proportional(12.5), @@ -795,17 +945,60 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { egui::FontId::proportional(11.0), t.text_dim, ); - if resp.clicked() { + if resp.clicked() && !resp.interact_pointer_pos().is_some_and(|p| check_rect.contains(p) || disclosure.contains(p)) { selected = Some((si, ai)); current = Some(si); sets_selected = vec![si]; } - if resp.double_clicked() { + if resp.double_clicked() && !resp.interact_pointer_pos().is_some_and(|p| check_rect.contains(p) || disclosure.contains(p)) { play_req = Some((si, ai)); } + if open { + for (step, (command, params)) in a.steps.iter().enumerate() { + let (r, resp) = ui.allocate_exact_size(egui::vec2(ui.available_width(), 20.0), egui::Sense::hover()); + if resp.hovered() { + ui.painter().rect_filled(r, 0.0, t.hover); + } + let (clicked, _) = inclusion_box(ui, r, 55.0, ("step-inclusion", a.id, step), !a.excluded_steps.contains(&step), false); + if clicked { + inclusion_changes.push(InclusionChange::Step(si, ai, step, alt)); + } + ui.painter().text( + r.left_center() + egui::vec2(70.0, 0.0), + egui::Align2::LEFT_CENTER, + command, + egui::FontId::proportional(11.0), + t.text_dim, + ); + resp.on_hover_ui(|ui| { + ui.label(format!("{command}\n{params}")); + }); + } + } } } }); + for change in inclusion_changes { + let params = match change { + InclusionChange::Set(si) => { + json!({"set": si, "included": app.ui.action_sets.get(si).is_some_and(|s| s.actions.iter().any(|a| !a.all_steps_included()))}) + } + InclusionChange::Action(si, ai) => { + json!({"set": si, "action": ai, "included": app.ui.action_sets.get(si).and_then(|s| s.actions.get(ai)).is_some_and(|a| !a.all_steps_included())}) + } + InclusionChange::Step(si, ai, step, alt) => json!({ + "set": si, + "action": ai, + "step": step, + "others": alt, + "included": app.ui.action_sets.get(si).and_then(|s| s.actions.get(ai)).is_some_and(|a| a.excluded_steps.contains(&step)), + }), + }; + if let Err(error) = app.run(INCLUDE_STEPS, params) { + app.status(error); + } + } + set_pstate(ui.ctx(), "actions-expanded", expanded); set_pstate(ui.ctx(), SELECTED, selected); app.ui.action_set = current; app.ui.action_sets_selected = sets_selected; @@ -873,6 +1066,99 @@ mod tests { } } + #[test] + fn excluded_steps_do_not_play_and_survive_saved_sets() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let id = vectorcraft_doc::NodeId( + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(), + ); + app.run("select.set", json!({"ids": [id.0]})).unwrap(); + let mut action = + Action::new("Move twice", vec![("object.move".into(), json!({"dx": 5, "dy": 0})), ("object.move".into(), json!({"dx": 20, "dy": 0}))]); + action.excluded_steps.insert(1); + assert_eq!( + action.included_commands(), + [json!({"command": "object.move", "params": {"dx": 5, "dy": 0}})], + "normal and Batch playback use the same included commands" + ); + app.ui.action_sets = vec![ActionSet::new("Test", vec![action])]; + let x = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap().x0; + let before = x(&app); + play(&mut app, 0, 0).unwrap(); + assert!((x(&app) - before - 5.0).abs() < 1e-9, "the excluded second move did not run"); + let saved = files::write_set(&app.ui.action_sets[0]); + assert!(saved.contains("\"excluded\": true"), "the set file keeps the exclusion"); + assert_eq!(serde_json::from_str::(&saved).unwrap()["version"], json!(2), "older builds must refuse excluded steps"); + let loaded = files::read_set(&saved, "Test").unwrap(); + assert_eq!(loaded.actions[0].excluded_steps, BTreeSet::from([1])); + assert_eq!(loaded.actions[0].copy().excluded_steps, BTreeSet::from([1])); + assert_eq!(serde_json::from_value::(serde_json::to_value(&loaded.actions[0]).unwrap()).unwrap().excluded_steps, BTreeSet::from([1])); + app.run(INCLUDE_STEPS, json!({"set": 0, "action": 0, "included": false})).unwrap(); + assert_eq!(play(&mut app, 0, 0).unwrap_err(), "the action has no included steps"); + assert_eq!(crate::dialogs::action_batch::open(&mut app, 0, 0).unwrap_err(), "the action has no included steps"); + } + + #[test] + fn inclusion_controls_expand_and_toggle_steps_without_selecting_the_action() { + use super::super::tests_appearance::{click, frame_events, text_rect}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let action = Action::new( + "Mixed", + vec![ + ("object.move".into(), json!({"dx": 1})), + ("object.rotate".into(), json!({"angle": 1})), + ("object.reflect".into(), json!({"axis": "vertical"})), + ], + ); + app.ui.action_sets = vec![ActionSet::new("Example", vec![action])]; + app.ui.action_set = Some(0); + let ctx = egui::Context::default(); + let texts = frame_events(&ctx, &mut app, vec![], show); + assert!(!texts.iter().any(|(s, _)| s == "object.rotate"), "steps start collapsed"); + let label = text_rect(&texts, "Mixed"); + click(&ctx, &mut app, egui::pos2(label.left() - 13.0, label.center().y), show); + let texts = frame_events(&ctx, &mut app, vec![], show); + let step = text_rect(&texts, "object.rotate"); + click(&ctx, &mut app, egui::pos2(step.left() - 15.0, step.center().y), show); + assert_eq!(app.ui.action_sets[0].actions[0].excluded_steps, BTreeSet::from([1])); + assert_eq!(pstate::>(&ctx, "actions-selected"), None, "the checkbox does not select the action"); + let texts = frame_events(&ctx, &mut app, vec![], show); + let label = text_rect(&texts, "Mixed"); + click(&ctx, &mut app, egui::pos2(label.left() - 32.0, label.center().y), show); + assert!(app.ui.action_sets[0].actions[0].excluded_steps.is_empty(), "mixed action check includes all steps"); + let texts = frame_events(&ctx, &mut app, vec![], show); + let label = text_rect(&texts, "▾ Example"); + click(&ctx, &mut app, egui::pos2(label.left() - 12.0, label.center().y), show); + assert_eq!(app.ui.action_sets[0].actions[0].excluded_steps, BTreeSet::from([0, 1, 2]), "set check excludes all steps"); + } + + #[test] + fn alt_click_keeps_the_chosen_step_and_toggles_the_others() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let action = Action::new("Three", vec![("a".into(), json!({})), ("b".into(), json!({})), ("c".into(), json!({}))]); + app.ui.action_sets = vec![ActionSet::new("Example", vec![action])]; + app.run(INCLUDE_STEPS, json!({"set": 0, "action": 0, "step": 1, "included": false, "others": true})).unwrap(); + assert_eq!(app.ui.action_sets[0].actions[0].excluded_steps, BTreeSet::from([0, 2])); + app.run(INCLUDE_STEPS, json!({"set": 0, "action": 0, "step": 0, "included": true, "others": true})).unwrap(); + assert_eq!(app.ui.action_sets[0].actions[0].excluded_steps, BTreeSet::from([0])); + app.run(INCLUDE_STEPS, json!({"set": 0, "action": 0, "step": 0, "included": true})).unwrap(); + assert!(app.ui.action_sets[0].actions[0].excluded_steps.is_empty()); + app.run(INCLUDE_STEPS, json!({"set": 0, "action": 0, "step": 0, "included": true, "others": true})).unwrap(); + assert!(app.ui.action_sets[0].actions[0].excluded_steps.is_empty(), "including the other steps preserves the clicked included step"); + for invalid in [ + json!({"set": 0, "action": 0, "step": 3, "included": false}), + json!({"set": 0, "action": 3, "included": false}), + json!({"set": 2, "included": false}), + json!({"set": 0, "step": 1, "included": false}), + json!({"set": 0, "included": false, "others": true}), + json!({"set": 0, "included": "false"}), + ] { + assert!(app.run(INCLUDE_STEPS, invalid.clone()).is_err(), "{invalid}"); + assert!(app.ui.action_sets[0].actions[0].excluded_steps.is_empty(), "invalid params changed playback: {invalid}"); + } + } + #[test] fn begin_recording_command_matches_the_panel_button() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); @@ -1783,7 +2069,7 @@ mod tests { (json!(long.to_string()), "an action in the action set file has more than 10,000 steps"), (json!(" ".repeat(files::MAX_SET_FILE + 1)), "the action set file is larger than 8 MiB"), ( - json!("{\"format\": \"vcactions\", \"version\": 2, \"name\": \"S\", \"actions\": []}"), + json!("{\"format\": \"vcactions\", \"version\": 3, \"name\": \"S\", \"actions\": []}"), "the action set file needs a later version of VectorCraft", ), ] { diff --git a/crates/ui-egui/src/panels/actions/files.rs b/crates/ui-egui/src/panels/actions/files.rs index 252d4c8e7d..ef00fccceb 100644 --- a/crates/ui-egui/src/panels/actions/files.rs +++ b/crates/ui-egui/src/panels/actions/files.rs @@ -1,10 +1,12 @@ //! Action set files: the Actions panel menu's Save Actions… and Load Actions…. //! -//! An action set file (`.vcactions`) is JSON: `{"format": "vcactions", "version": 1, "name", -//! "actions": [{"name", "steps": [{"command", "params"}], "key"?, "color"?}]}`. Each step is a +//! An action set file (`.vcactions`) is JSON: `{"format": "vcactions", "version": 1 or 2, "name", +//! "actions": [{"name", "steps": [{"command", "params", "excluded"?}], "key"?, "color"?}]}`. Each step is a //! command id and its params, as `command.batch` takes them. `key` is the action's function key //! (`{"key": 1 to 15, "cmd", "shift"}`) and `color` its Button Mode color; an action without them, -//! or with a value that is not one, has none. +//! or with a value that is not one, has none. `excluded: true` keeps a step but skips it during +//! playback. Sets with exclusions use version 2 so older builds refuse them rather than replay +//! excluded steps. Sets without exclusions use version 1, and earlier version 1 files still work. use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -57,6 +59,12 @@ struct FileStep { command: String, #[serde(default)] params: Value, + #[serde(default, skip_serializing_if = "is_false")] + excluded: bool, +} + +fn is_false(value: &bool) -> bool { + !value } /// `set` as the text of an action set file. @@ -66,12 +74,18 @@ pub fn write_set(set: &ActionSet) -> String { .iter() .map(|a| FileAction { name: a.name.clone(), - steps: a.steps.iter().map(|(command, params)| FileStep { command: command.clone(), params: params.clone() }).collect(), + steps: a + .steps + .iter() + .enumerate() + .map(|(i, (command, params))| FileStep { command: command.clone(), params: params.clone(), excluded: a.excluded_steps.contains(&i) }) + .collect(), key: a.key, color: a.color.clone(), }) .collect(); - let file = SetFile { format: ACTIONS_EXT.into(), version: 1, name: set.name.clone(), actions }; + let version = if set.actions.iter().any(|a| !a.excluded_steps.is_empty()) { 2 } else { 1 }; + let file = SetFile { format: ACTIONS_EXT.into(), version, name: set.name.clone(), actions }; serde_json::to_string_pretty(&file).unwrap_or_default() } @@ -84,7 +98,7 @@ pub fn read_set(text: &str, name: &str) -> Result { if f.format != ACTIONS_EXT { return Err("not an action set file".into()); } - if f.version != 1 { + if !matches!(f.version, 1 | 2) { return Err("the action set file needs a later version of VectorCraft".into()); } if f.actions.len() > MAX_SET_ACTIONS { @@ -96,7 +110,10 @@ pub fn read_set(text: &str, name: &str) -> Result { let actions = f .actions .into_iter() - .map(|a| Action { key: a.key, color: a.color, ..Action::new(a.name, a.steps.into_iter().map(|s| (s.command, s.params)).collect()) }) + .map(|a| { + let excluded_steps = a.steps.iter().enumerate().filter_map(|(i, step)| step.excluded.then_some(i)).collect(); + Action { key: a.key, color: a.color, excluded_steps, ..Action::new(a.name, a.steps.into_iter().map(|s| (s.command, s.params)).collect()) } + }) .collect(); let set_name = if f.name.trim().is_empty() { name.to_string() } else { f.name }; Ok(ActionSet::new(set_name, actions)) diff --git a/docs/mcp.md b/docs/mcp.md index 540dc85533..57abddff1f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1771,14 +1771,20 @@ already walks Image Trace. Short agent entry points: the file at `path`, else a picked one, or the file's text `data`, adds its set after the other sets and returns `{set, name, actions}`. A set named like one already in the panel gets the next free number (`Print 2`), and the other sets and the current set stay as they are. An action set file (`.vcactions`) is JSON: - `{"format": "vcactions", "version": 1, "name", "actions": [{"name", "steps": [{"command", "params"}]}]}`, each step - a command id and its params as `command.batch` takes them. A file with another `format` or a `version` other than - 1, a file larger than 8 MiB, one with more than 1,000 actions and one with an action of more than 10,000 steps are + `{"format": "vcactions", "version": 1 or 2, "name", "actions": [{"name", "steps": [{"command", "params", "excluded"?}]}]}`, each step + a command id and its params as `command.batch` takes them. `excluded: true` preserves a step but omits it from playback; + an absent or false flag includes the step. Files with excluded steps use version 2, so older builds refuse them + instead of playing the excluded steps; files without exclusions use version 1. A file with another `format` or a `version` other than + 1 or 2, a file larger than 8 MiB, one with more than 1,000 actions and one with an action of more than 10,000 steps are refused, and no set is added. The Actions panel menu's Save Actions… and Load Actions… run these; Load Actions… is disabled where there is no open dialog (the web). - Actions: `ui.action.rename {set, action, name}` renames the Actions panel's action at `action` in set `set` (0 is the top set) to `name` with spaces trimmed from both ends, keeps its steps, function key and color, and returns `{name}`. An index past the last set or action, or an empty name, is an error, and then nothing is renamed. +- Actions: `ui.action.stepsIncluded {set, action?, step?, included, others?}` includes or excludes all steps of a set, + one action, or one step. With `step` and `others: true`, it leaves that step as it was and applies `included` to the + other steps of its action (the panel's Alt/Option-click). An invalid set, action or step changes nothing. The panel's + checkmarks run this command; normal playback and Batch… skip excluded steps. - Actions: `ui.action.new {set, name, key?, cmd?, shift?, color?}` adds an action named `name` (spaces trimmed) after the last action of set `set` (0 is the top set), starts recording into it and returns `{set, action}`; Stop Playing/Recording (`ui.action.stop`) ends the recording. `key` 1 to 15 is the function key F1 to F15 that plays the @@ -1803,7 +1809,7 @@ already walks Image Trace. Short agent entry points: plays. A stored key reserved on the current platform does not play an action. - Actions: `ui.action.play {action, set?}` plays the action named `action` as one undoable batch; `set` names the set to look in (default: every set), and a `set` that is not a string is an error. A name that no action has, or that - more than one action in the sets looked in has, is an error, and then nothing plays. + more than one action in the sets looked in has, or whose every step is excluded, is an error, and then nothing plays. - Actions: `ui.action.stop {}` ends the recording in progress and keeps its steps, in the action `ui.action.new` made for it, else in a new action after the last action of its set, and returns `{stopped}`. With nothing recording it changes nothing. The panel's Stop Playing/Recording button runs this. @@ -3236,7 +3242,9 @@ for `edit.pasteInPlace`, `edit.pasteInFront` and `edit.pasteInBack`, and to each none, when the step runs. When the document a step runs in has no artboard at that index (for example, after an earlier step deleted the active artboard when it was the last one), the step gets that document's last artboard. In remote mode, MCP's `run_command` calls and each step of the `command_batch` tool get the active artboard too. The -Actions panel plays an action as a `command.batch`. The Actions panel menu's Batch… runs +Actions panel plays an action as a `command.batch`, omitting steps whose playback checkmarks are +cleared. An action set saved as `.vcactions` keeps each excluded step with `excluded: true`; loading +an earlier version 1 set without that flag includes every step. The Actions panel menu's Batch… runs `action.batch`: the same steps on every readable file in a folder (or every data set of the open document), with destination `none` | `saveAndClose` | `folder` and Override Open / Save / Export. For a Data Sets source, `datasetFileNaming?: fileNumber | fileDataSetName | dataSetName` chooses File + Number (`source001`), diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8bc8372b7e..f7cc40f693 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (Type core options status and Kashidas feature revision corrected; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (Actions panel steps excluded from playback; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -23,6 +23,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | Actions panel: an expanded action's steps can be excluded from playback and Batch… by clearing their checkmarks; action and set checkmarks include or exclude all their steps, and exclusions survive restart, duplication and `.vcactions` save/load. Scores and estimates unchanged. | | 2026-11-03 | minor | Correct the Type core missing list and remove duplicate target and Type core entries: Hyphenation and Justification options are complete; the remaining Every-line Composer fidelity limits stay listed. Record the Kashidas paragraph lengths and per-character switch in the feature history (#5404). Scores and estimates unchanged. | | 2026-11-03 | minor | Correct the Type core missing list: Hyphenation and Justification options are complete; the remaining Every-line Composer fidelity limits stay listed. Record the Kashidas paragraph lengths and per-character switch in the feature history (#5404). Scores and estimates unchanged. | | 2026-11-03 | minor | Ligature caret stops use GDEF contour-point positions in horizontal and vertical type at the font's default variation location; invalid point indices keep the evenly divided fallback. Scores and estimates unchanged. | @@ -574,6 +575,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Actions panel: Create New Action (bottom bar) and the panel menu's New Action… ask for the new action's name, set, function key and color, and Record adds the action and starts recording into it ([Create new actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/record-actions.html): the New Action dialog takes the action's name and the set it goes in; `ui.action.new`, `ui.action.play`). The function key (F1 to F15, with Ctrl or Command and Shift) plays the action. An action's function key plays the action even when a command has the same shortcut, and the command keeps it. VectorCraft's own rules, which the page does not cover: when several actions have the same key the first in panel order plays; a copied action has no key; New Action does not open while an action is recording. The color is kept with the action for Button Mode, which VectorCraft does not have yet. - Actions panel (record/playback, persisted), generic parameter dialogs for every "…" command. - Actions panel: the current set is kept with the UI preferences, so after a restart a recording goes into the set that was current, not into the first set. With no set current, Begin Recording records into the first set and makes it current. + - Actions panel: expand an action to show its recorded steps, then clear a step's checkmark to keep it in the action but skip it during playback. The action and set checkmarks include or exclude all their steps; a mixed checkmark includes all. Alt/Option-clicking a step checkmark keeps that step as it was and applies the opposite inclusion state to the other steps in its action. This follows the public [Exclude commands from an action](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/exclude-commands-from-actions.html) guide; the scope of the mixed-state and Alt-click behavior is VectorCraft's design. The exclusion survives UI restart, action duplication, and `.vcactions` save/load. Existing version 1 action set files load with every step included. - Actions panel: Delete Selection deletes the selected action set with its actions and keeps the other sets ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html); `ui.actionSet.delete`). VectorCraft's own rules, which the overview does not cover: deleting a set asks first, Shift-click on a set's name selects a range of sets to delete together, the panel menu's Delete does the same, and Default Actions and the last set can be deleted. Undo does not bring a deleted set back. - Actions panel: the panel menu's Duplicate copies the selected action, else the current action set with all its actions ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html); `ui.actionSet.duplicate`). VectorCraft's own rules, which the overview does not cover: the copy goes right after the original, is named after it with " copy" added and is selected. - Batch… over data sets names each file after the document and the data set (`action.batch`). It writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds `-2`, `-3`… to a name an earlier data set used. From ccf4252a738ccfeb91be871800c9c132c49fa528 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 22:10:14 -0800 Subject: [PATCH 019/513] Type: typing a list's start in a continued paragraph starts no list In a threaded frame whose first paragraph continues from the frame before, the text at the frame's start is not the start of a paragraph, and the frame draws no list marker for it. Typing "* " or "1. " there removed the characters and set a list that never showed. typed_list_at now returns None for that paragraph. --- crates/doc/src/text/object.rs | 6 ++++-- crates/doc/src/text/tests.rs | 13 +++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index c6a22a29c4..70e9539222 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -200,14 +200,16 @@ impl TextObject { } /// The list that the characters before byte `at` start ([`ParaList::typed`]) with the byte /// where their paragraph starts: when the plain text from the start of the paragraph up to - /// `at` is a list's start followed by a space, and the paragraph is in no list. None otherwise. + /// `at` is a list's start followed by a space, and the paragraph is in no list. None otherwise, + /// and for a first paragraph that continues from the frame before + /// ([`TextObject::first_para_continues`]). pub fn typed_list_at(&self, at: usize) -> Option<(usize, ParaList)> { let text = self.plain_text(); let before = text.get(..at)?; let start = before.rfind('\n').map_or(0, |i| i + 1); let list = ParaList::typed(before[start..].strip_suffix(' ')?)?; let index = before.bytes().filter(|&b| b == b'\n').count(); - self.para_at(index).list.is_none().then_some((start, list)) + (!(index == 0 && self.first_para_continues) && self.para_at(index).list.is_none()).then_some((start, list)) } /// Apply `f` to the attributes of paragraphs `range` (indices; None = every paragraph). pub fn edit_paras(&mut self, range: Option>, mut f: impl FnMut(&mut ParaStyle)) { diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index 04deae8ee3..2a47ee453e 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -239,6 +239,19 @@ fn typed_list_starts_are_found_at_a_paragraphs_start() { assert_eq!(t.typed_list_at(19), Some((16, letters))); } +/// In a threaded frame whose first paragraph continues from the frame before, the text at the +/// frame's start is not the start of a paragraph, so typing a list's start there starts nothing. +/// The paragraphs after it still start lists. +#[test] +fn typed_list_starts_skip_a_continued_paragraph() { + let dot = ParaList::bulleted(Bullet::Dot); + let mut t = TextObject::point(Point::ZERO, "* Pears\n# ", CharStyle::default()); + assert_eq!(t.typed_list_at(2), Some((0, dot))); + t.first_para_continues = true; + assert_eq!(t.typed_list_at(2), None, "a continued paragraph starts no list"); + assert_eq!(t.typed_list_at(10), Some((8, dot))); +} + #[test] fn character_controls_reject_collapsed_and_nonfinite_transforms() { let mut t = TextObject::point(Point::ZERO, "Text", CharStyle::default()); From f7bebdeaf098f6ee01025628032c7137d86e2ad7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 22:11:05 -0800 Subject: [PATCH 020/513] Live Paint: preserve face colors at shared curved boundaries Capture sweep-piece source attribution before endpoint pinning can move its midpoint off the original outlines. Keep the existing lookup after pinning when the original piece has no source. Add planar coverage and native compound Make/Expand/undo regressions, and document the existing front-most source-fill rule. --- crates/engine/src/cmd/buildcmds.rs | 2 +- crates/engine/src/tests/build.rs | 65 ++++++++++++++++++++++++++++++ crates/pathops/src/planar/map.rs | 7 +++- crates/pathops/src/planar/tests.rs | 42 +++++++++++++++++++ docs/mcp.md | 4 +- docs/target-app-parity.md | 1 + 6 files changed, 118 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 56ff8a6368..abc828b311 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -72,7 +72,7 @@ pub fn specs() -> Vec { "Make", ["Object", "Live Paint"], Some("Cmd+Alt+X"), - "{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); with a Live Paint group among them, add the others to it as livePaint.merge does → {id, faces, edges}", + "{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); each covered face starts with its front-most covering source's fill; with a Live Paint group among them, add the others to it as livePaint.merge does → {id, faces, edges}", has_selection_or_ids, lp_make ), diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index b0d839220e..43234dcc9d 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -1807,6 +1807,71 @@ fn live_paint_make_builds_group_with_hidden_sources() { assert_eq!(info["sources"], 2); } +/// Make and Expand preserve the colors of compound paths sharing a curved boundary. +#[test] +fn live_paint_make_and_expand_keep_abutting_compound_colors() { + use kurbo::Shape as _; + use vectorcraft_geom::shapes; + + let mut s = session(); + let mut ring = shapes::ellipse(Rect::new(0.0, 0.0, 1.0, 1.0)); + let mut disk = shapes::ellipse(Rect::new(0.2, 0.2, 0.8, 0.8)); + let mut hole = disk.clone(); + hole.reverse(); + ring.subpaths.extend(hole.subpaths); + disk.subpaths.extend(shapes::rectangle(Rect::new(1.0, 0.0, 1.3, 1.0)).subpaths); + let compound = |s: &mut Session, path: &PathData, color: &str| { + let id = s.execute("path.create", &json!({"d": path.to_bezpath().to_svg()})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"id": id, "color": color})).unwrap(); + s.execute("paint.setStroke", &json!({"id": id, "none": true})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()) + }; + let ink = compound(&mut s, &ring, "#000000"); + let blue = compound(&mut s, &disk, "#2878f0"); + s.execute("select.set", &json!({"ids": [ink.0, blue.0]})).unwrap(); + let history = s.doc().unwrap().history.undo.len(); + let made = s.execute("livePaint.make", &json!({})).unwrap(); + assert_eq!(made["faces"], 3); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + let group = NodeId(made["id"].as_u64().unwrap()); + let paint_at = |n: &Node, p: Point| { + n.children() + .unwrap() + .iter() + .filter(|c| c.visible && !c.appearance.fill_paint().is_none()) + .filter(|c| c.path_data().is_some_and(|path| path.to_bezpath().winding(p) != 0)) + .map(|c| c.appearance.fill_paint()) + .collect::>() + }; + let check_colors = |n: &Node| { + assert_eq!(paint_at(n, Point::new(0.1, 0.5)), vec![Paint::solid(Color::BLACK)]); + let blue = Paint::solid(Color::from_hex("#2878f0").unwrap()); + assert_eq!(paint_at(n, Point::new(0.5, 0.5)), vec![blue.clone()]); + assert_eq!(paint_at(n, Point::new(1.15, 0.5)), vec![blue]); + }; + check_colors(&node(&s, group)); + let info = s.execute("livePaint.info", &json!({"group": group.0})).unwrap(); + assert_eq!(info["sources"], 2); + assert_eq!(info["faces"].as_array().unwrap().len(), 3); + s.execute("livePaint.expand", &json!({})).unwrap(); + let expanded = node(&s, group); + assert!(!vectorcraft_tools::builder::is_live_paint(&expanded)); + assert_eq!(expanded.children().unwrap().len(), 3); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 2); + check_colors(&expanded); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(vectorcraft_tools::builder::is_live_paint(&node(&s, group))); + check_colors(&node(&s, group)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(layer_children(&s), 2); + assert!(matches!(node(&s, ink).kind, NodeKind::Compound { .. })); + assert!(matches!(node(&s, blue).kind, NodeKind::Compound { .. })); + s.execute("edit.redo", &json!({})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + check_colors(&node(&s, group)); +} + #[test] fn live_paint_fill_assigns_the_face_under_the_point() { let mut s = session(); diff --git a/crates/pathops/src/planar/map.rs b/crates/pathops/src/planar/map.rs index ec8b0b76c4..3abf7cfeaa 100644 --- a/crates/pathops/src/planar/map.rs +++ b/crates/pathops/src/planar/map.rs @@ -299,11 +299,16 @@ fn sweep_graph(inputs: &[(BezPath, usize)], eps: f64, precision: f64) -> Option< if ends[0] == ends[1] { continue; } + // Source attribution belongs to the sweep piece: pinning its endpoints can move the + // middle off the original outlines even though it still separates the same faces. + let mut sources = mid(&segs).map(|m| outlines.sources_at(m)).unwrap_or_default(); // Every edge at a vertex starts or ends exactly on it, so faces meeting there share its // coordinates: merging them (a union) then cancels their common edge, which it can't when // each face carries its own rounding of the corner (#893). pin_ends(&mut segs, p0, p1); - let sources = mid(&segs).map(|m| outlines.sources_at(m)).unwrap_or_default(); + if sources.is_empty() { + sources = mid(&segs).map(|m| outlines.sources_at(m)).unwrap_or_default(); + } let Some(&source) = sources.last() else { continue }; // Coincident pieces the sweep left apart are one edge (the front-most input's), lying on // the inputs of both. diff --git a/crates/pathops/src/planar/tests.rs b/crates/pathops/src/planar/tests.rs index 3ca7a48141..d1d05d4dff 100644 --- a/crates/pathops/src/planar/tests.rs +++ b/crates/pathops/src/planar/tests.rs @@ -230,6 +230,48 @@ fn curves_and_a_circle_crossed_by_a_line() { assert_eq!(edges.iter().filter(|e| e.key == 0).count(), 2, "two arcs"); } +/// Coincident curved boundaries retain the fill coverage of the regions they separate. +#[test] +fn coincident_curves_keep_their_source_faces() { + fn check(diameter: f64, offset: f64, rule: FillRule, reverse: bool, swap: bool) { + let mut ring = circle(0.5 * diameter, 0.5 * diameter, 0.5 * diameter, 0); + let mut hole = circle(0.5 * diameter, 0.5 * diameter, 0.3 * diameter, 1).path; + hole.reverse(); + ring.path.subpaths.extend(hole.subpaths); + ring.rule = rule; + let mut disk = circle(0.5 * diameter + offset, 0.5 * diameter, 0.3 * diameter, 1); + disk.rule = rule; + if reverse { + ring.path.reverse(); + disk.path.reverse(); + } + let shapes = if swap { vec![disk, ring] } else { vec![ring, disk] }; + let (faces, _) = live_paint(&shapes); + let label = format!("diameter={diameter}, offset={offset}, rule={rule:?}, reverse={reverse}, swap={swap}"); + for (x, source) in [(0.1 * diameter, usize::from(swap)), (0.5 * diameter, usize::from(!swap))] { + let covering = at(&faces, x, 0.5 * diameter); + assert_eq!(covering.len(), 1, "{label}: {covering:?}"); + assert_eq!(covering[0].sources, [source], "{label}"); + } + if offset == 0.0 { + assert_eq!(faces.len(), 2, "{label}"); + let ring_face = at(&faces, 0.1 * diameter, 0.5 * diameter)[0]; + assert_eq!(ring_face.path.subpaths.len(), 2, "{label}: the ring keeps its hole"); + } + } + for diameter in [1.0, 0.5, 2.0, 100.0] { + for offset in [0.0, 0.025, -0.025] { + for rule in [FillRule::NonZero, FillRule::EvenOdd] { + for reverse in [false, true] { + for swap in [false, true] { + check(diameter, offset, rule, reverse, swap); + } + } + } + } + } +} + #[test] fn a_line_ending_on_an_edge_splits_the_shape() { let s = [line((90.0, 20.0), (70.0, 10.0), 0), rect(80.0, 10.0, 90.0, 50.0, 1)]; diff --git a/docs/mcp.md b/docs/mcp.md index 57abddff1f..5dc19c6650 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1841,7 +1841,9 @@ already walks Image Trace. Short agent entry points: `ui.imageTracePresetDialog {params?, rename?}` opens the Image Trace panel's Save as New Preset… or Rename… dialog. - Live Paint: `livePaint.make`, `livePaint.merge`, `livePaint.fill {group?, point}`, `livePaint.strokeEdge`, `livePaint.info {group}`, `livePaint.release`, `livePaint.expand`, and `livePaint.gapOptions {ids?, detect?, size?, - color?, closeGaps?}` (Object › Live Paint › Gap Options). With `detect: true`, paint stops at the gaps that run + color?, closeGaps?}` (Object › Live Paint › Gap Options). Make gives each covered face the fill of its front-most + covering source, including compound paths with shared curved boundaries. Expand keeps those face fills. + With `detect: true`, paint stops at the gaps that run from a loose end of a path to the nearest path, up to `size` wide (`small` 3 pt, `medium` 6 pt, `large` 12 pt, or a number of points up to 72); `closeGaps: true` adds an unpainted path across each of them. The options are saved with the group, and the reply and `livePaint.info` list the gaps up to `size` wide that no path closes, as `[x0, y0, x1, y1]`. `livePaint.merge` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f7cc40f693..b79671899c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -996,6 +996,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Object › Live Paint › Merge adds the other selected paths and Live Paint groups to the bottom selected Live Paint group ([Live Paint groups](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/live-paint-groups.html)), which keeps its id, the paint of its faces and edges, and its name, lock, visibility, transparency, appearance, opacity mask and graphic style link. Object › Live Paint › Make with a Live Paint group selected, and a Live Paint Bucket click on a selected path beside a selected Live Paint group, add the paths to that group the same way. Make, Merge and the Live Paint Bucket take paths, compound paths and groups of them; with type, an image or another object among the selection they report that it has to be converted to paths first and change nothing, as type and raster images can't go into a Live Paint group directly ([Create Live Paint groups](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/create-live-paint-groups.html)); before, such an object went among the group's hidden sources and vanished from the canvas. Evidence: `tests_build::live_paint_refuses_type_and_images_and_changes_nothing`. With the Live Paint Bucket selected, Alt-click on vector art samples its fill, stroke and stroke weight into the paint defaults ([Paint with the Live Paint Bucket tool](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html)). On a placed image it samples the image pixel as a solid fill with no stroke. Alt+Shift-click samples only the color under the pointer, including an intermediate gradient color or image pixels, into the active fill or stroke ([Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). Neither click paints or changes the selection or selected art, and the next Bucket click paints with the sampled paint. Evidence: `tests_build::live_paint_bucket_alt_sample_paints_next_face_without_changing_selection`. Double-clicking the Live Paint Bucket opens Live Paint Bucket Options ([Paint with the Live Paint Bucket tool](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html)): Paint Fills (on) and Paint Strokes (off) set whether a click paints faces, edges or both, Highlight turns the outline of the face or edge under the pointer on or off, and Color and Width set it (red and 4 px by default). Faces are outlined at the Width and edges at half of it, as the page says faces are highlighted with a thick line and edges with a thin line. With both on, a click paints the edge within 4 px of the pointer, else the face, and Shift switches to Paint Fills only; with one on, Shift switches to the other. The options last across tool switches and are saved with the preferences (`tool.setOption {tool: "livePaintBucket"}`). Evidence: `builder::tests::{bucket_options_choose_what_a_click_paints, bucket_options_set_the_highlight, bucket_highlights_an_edge_thinner_than_a_face}`, `dialogs::live_paint_bucket::tests::double_clicking_the_tool_opens_its_options_and_ok_sets_them`. + Live Paint Make preserves the front-most covering source's fill when compound paths share a curved boundary, and Expand keeps the face fills. Regression evidence: `planar::tests::coincident_curves_keep_their_source_faces` checks source order, winding, fill rules and nearby boundaries; `tests::build::live_paint_make_and_expand_keep_abutting_compound_colors` checks native compound paths, Make, Expand and Undo/Redo. This preserves VectorCraft's source-fill rule without changing arrangement precision. Live Paint Gap Options (Object › Live Paint › Gap Options…, `livePaint.gapOptions`): with Gap Detection on, paint stops at the gaps that run from a loose end of a path to the nearest path, up to Small (3 pt), Medium (6 pt), Large (12 pt) or a custom size; Close Gaps With Paths adds an unpainted path across each gap; Preview applies the options live and draws the gaps in the Gap Preview Color. The options are saved, copied and undone with the group, and Merge keeps the bottom group's options when its Gap Detection is on, or else turns Gap Detection on with Small when another merged group has it on. When Gap Detection is off in every merged group, it stays off. View › Show Live Paint Gaps (`view.livePaintGaps`) draws the gaps of the selected Live Paint groups up to their Paint Stops At size, each in its group's Gap Preview Color, until Hide Live Paint Gaps or Hide Edges hides them ([Live Paint gaps](https://web.archive.org/web/20260105111201/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/find-and-close-gaps-in-live-paint-groups.html)). Double-clicking the Live Paint Selection tool opens its Tool Options ([Live Paint Selection tool options](https://web.archive.org/web/20250904012025/https://helpx.adobe.com/illustrator/using/selecting-objects.html)): with Select Fills off, a click selects an edge instead of a face; with Select Strokes off, Alt-click selects a face instead of an edge; Color and Width set the color and width of the highlight on the face or edge under the pointer (red and 4 px by default). The options last across tool switches and are saved with the preferences (`tool.setOption {tool: "livePaintSelection"}`). From d46079b8724b13098ac2ea47b90df10fcb8152ef Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 22:56:11 -0800 Subject: [PATCH 021/513] Docs: name glows with shadows in the pan raster entry, and mark VectorCraft's own values The panning entry says a Drop Shadow or Outer Glow raster holds the shadow or glow of group members outside the view. The Blob Brush Fidelity entry keeps its citation on the option and states that the slider and field range and the 1.5 pt default are VectorCraft's own values. The Escape in Selection tool drags entry is stated as VectorCraft's own behavior. --- docs/target-app-parity.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b79671899c..9367a069e8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -494,7 +494,7 @@ since 2026-10-01. - **Constrain Angle (#394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (). Tests: `tests_constrain_tools`, `tests_constrain_new` (engine), `geom` `constrain_axes` / `rotate_deg`, the shape, grid and type tool tests. - **Clipping paths on their outline (G1):** the selection tools (Selection, Direct Selection, Group Selection), Object Highlighting and a right-click take a clipping path on its outline before the art it clips; Select Behind lists the same; the eyedropper, the tools that act on what is drawn and the selection tools' double-clicks, loaded text and guide release take the art. Doc and tool regression tests; score unchanged. -- **Escape in Selection tool drags:** Escape during a Selection tool move or Alt-drag copy, a bounding-box scale or rotation, a marquee, or a corner widget, pie widget or bracket drag cancels it: the art returns to its state at the press, no copy is left, no undo step is added, the release does nothing, and the tool stays chosen. Regression tests: `escape_cancels_*` in `select/tests.rs` and `pie.rs`, and `escape_cancels_a_selection_tool_move_copy_scale_or_rotation` in `tests/selectescape.rs`. +- **Escape in Selection tool drags:** Escape during a Selection tool move or Alt-drag copy, a bounding-box scale or rotation, a marquee, or a corner widget, pie widget or bracket drag cancels it: the art returns to its state at the press, no copy is left, no undo step is added, the release does nothing, and the tool stays chosen. This is VectorCraft's own behavior. Regression tests: `escape_cancels_*` in `select/tests.rs` and `pie.rs`, and `escape_cancels_a_selection_tool_move_copy_scale_or_rotation` in `tests/selectescape.rs`. - **Global Edit: Shift-click leaves a match out:** while Global Edit is on, a Shift-click with the Selection tool on a highlighted match, or on an object inside a matched group, leaves that match out (`select.globalEditExclude`): it is no longer highlighted and later edits leave it as it is; the object the edit started from stays, and Global Edit ends when fewer than two matches are left ([Update assets quickly with Global Edit](https://helpx.adobe.com/ph_fil/illustrator/how-to/global-editing-sensei.html)). Regression tests: `a_shift_click_*`, `an_object_left_out_*`, `a_group_left_out_*` and `leaving_out_all_but_one_*` in `crates/engine/src/tests/globaledit.rs`. - **Pattern-only backquote drags:** With Selection move, bounding-box scale or rotate, or the Rotate, Reflect, Scale or Shear tool, backquote held at mouse release applies the drag matrix to selected pattern paint while object geometry stays in place. The key may be pressed after mouse press; if released before the mouse button, the drag commits as an ordinary transform. Objects without pattern paint stay still; stroke-only patterns and patterned objects in mixed selections take the same matrix. Regression tests: `backquote_move_uses_release_state_and_one_commit` and `backquote_box_scale_and_rotate_use_pattern_matrix_at_release` in `select/tests.rs`, `backquote_drag_previews_and_commits_pattern_only_for_each_transform_tool` in `xform/transform.rs`, `selection_backquote_drag_changes_pattern_fill_and_stroke_without_moving_mixed_art` and `selection_backquote_drag_changes_stroke_only_pattern` in `tests/pattern.rs`, `egui_backtick_drag_uses_key_state_at_release` in `canvas/tests.rs`, and `synthetic_pointer_backquote_keeps_solid_object_in_place` in `control/tests.rs`. Scores and hours unchanged. - **Existing-guide Escape cancellation (G1):** Escape clears a pending guide press or drag through Selection and Direct/Group Selection, cancelling a begun preview. Eight app-input regressions cover both axes, move/copy, temporary selection-tool borrowing from idle Pen, preselected-guide document/interaction-start selection and Undo/Redo/saved-state preservation, later on-canvas motion/release, Shift-press cancellation, and ordinary-release/Enter/idle controls. Historical focused checks on `8ab574b7` recorded five expected RED failures with three passing controls, then all eight GREEN tests and the Direct Selection Escape control passed. All nine also passed in current full CI. A full CI retry on the five-unit combined source at `a0671777` passed all seven stages with 6,613 test outcomes on 2026-10-14. An earlier full-CI run on the identical source panicked in the randomized `ai_mutated_save_never_panics` test; the cause remains unresolved. This five-fix batch does not claim to repair that failure. The original 1280×960 headless app capture from `b076025a` was reviewed for one vertical Selection guide after Escape; source review found its scene unchanged on `a0671777`. Scores and hours unchanged. @@ -813,7 +813,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Blob Brush Tool Options have Keep selected and Merge only with selection, both off by default: while Keep selected is off, the blob a stroke draws or merges into is not selected afterwards, and while Merge only with selection is on, a stroke merges only with selected blobs of its color that it touches (`path.blob` `keepSelected` and `mergeOnlySelection`). The Blob Brush Tool Options also have Angle and Roundness, as the reference app's [Blob Brush options](https://web.archive.org/web/20261012042029/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/blob-brush-options-and-best-practices.html) list them: Angle from −180° to 180° (0° by default) and Roundness from 0% to 100% (100%, a round tip, by default). The elliptical tip keeps its angle on the page along a stroke, a 0% tip is drawn 0.1% as wide as it is long, and the dialog shows the tip and three dabs of it. The values are kept with the tool's options (`path.blob` `angle` and `roundness`). Not done: the Random and pen-driven variations of Angle and Roundness. The Blob Brush Tool Options' tip preview is the Angle slider for screen readers, with the Angle in degrees as its value: a click or a drag in it points the Angle at the pointer and gives it the keyboard focus, Tab reaches it after the Roundness field, and the arrow keys step the Angle by 1° (10° with Shift, Home and End to −180° and 180°). - The Blob Brush Tool Options also have Fidelity, as the reference app's [Blob Brush options](https://web.archive.org/web/20261012042029/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/blob-brush-options-and-best-practices.html) list it: the Pencil's logarithmic slider from Accurate (0.01 pt) to Smooth (20 pt) and its field (up to 100 pt), 1.5 pt by default and kept with the tool's options. The brush follows the stroke fitted at the Fidelity, as a Pencil stroke is fitted: a low value follows the drag closely, jitter included, and a higher one gives smoother curves (`path.blob` `fidelity`). + The Blob Brush Tool Options also have Fidelity, which the reference app's [Blob Brush options](https://web.archive.org/web/20261012042029/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/blob-brush-options-and-best-practices.html) list as setting how far the pointer moves before the path gets a new anchor point. The range and default are VectorCraft's own values: the Pencil's logarithmic slider from Accurate (0.01 pt) to Smooth (20 pt) and its field (up to 100 pt), 1.5 pt by default and kept with the tool's options. The brush follows the stroke fitted at the Fidelity, as a Pencil stroke is fitted: a low value follows the drag closely, jitter included, and a higher one gives smoother curves (`path.blob` `fidelity`). A Blob Brush stroke merges with the topmost path of its fill color and no stroke that it touches, and with the other such paths it touches in the same group or layer that are next to that path in stacking order with no other kind of object between them; matching paths in other groups or layers are left alone, as the Blob Brush tool guidelines in [Paint with fills and strokes](https://web.archive.org/web/20241219085603/https://helpx.adobe.com/illustrator/using/painting-fills-strokes.html) describe (`path.blob`). - **Ruler guides as layer objects:** a guide goes on the current layer, shows, hides, locks and is deleted with it, is listed in the Layers panel (its row selects it) and moves to another layer (`guide.setLayer`, or its row dragged onto that layer's rows); guides on a hidden or locked layer can't be selected, moved or deleted, Duplicate copies a layer's guides and Merge Selected and Flatten Artwork keep them on the merged layer; guides from files saved before guides had layers go on the top visible, unlocked layer when the document opens. Not done: guides stacked among the art of their layer (they are listed above it), a guide row's own eye and lock. Lock Guides also locks the objects made into guides: they can't be selected, moved or deleted (#1543); they are drawn in the guide colour and style of Preferences, and a dragged selection snaps to ruler guides with Smart Guides on (#1583, fixes #1534). The Transform panel shows a selected ruler guide's X or Y, and typing a value moves it (#1659, part of #1597). This is not established by the documentation we could find: the public help pages on guides, rulers and the Transform, Control and Properties panels (read again on 2026-10-14) describe selecting and dragging unlocked guides and the panels' X and Y for a selection, not a guide's position in a panel, and the one public statement of it is a user's [community answer](https://community.adobe.com/questions-652/adding-a-new-custom-guide-785586), which is not documentation. It is kept as a convenience pending the owner's decision, with no parity claim and nothing counted towards a score. - **Releasing ruler guides:** View › Guides › Release Guides turns the selected ruler guides into paths with no fill or stroke. An artboard guide becomes a line across its artboard, and a canvas guide becomes a line across the artboards (`view.guides.release {index?, ids?}`). A Cmd/Ctrl+Shift double-click with the Selection, Direct Selection or Group Selection tool releases the ruler guide or guide path under the pointer. @@ -1280,7 +1280,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Dragging objects with raster effects when zoomed in (#2558):** during a drag with a tool on the canvas, the renderer draws filtered content (Gaussian Blur, Feather and the Photoshop-style filters) within 1,000,000 pixels, at a lower resolution where it would need more, unless it can draw the content from an earlier frame's raster. In the desktop app it does the same for drop shadows, outer glows and inner glows. No raster made that way is kept. The frame after the drag renders them as a still frame does, and a dialog's preview, exports and printing render as before. `zoomed_drag_perf` times a drag's frames at 100% to 6400%. - **Dragging other art over a wide blur (#2558):** an effect raster too large to keep whole (a wide blur, a shadow or glow, or any blur zoomed in) is cropped to what can show in the view, or made at a lower resolution and resampled to the view's pixels, and kept while the view stays the same, so dragging other art over the object draws its effects from the still frame instead of re-rendering them at the drag's lower resolution. A drag stays on the render worker once the worker drew the frame shown, since only that renderer holds the rasters. `tests_viewraster` covers each effect, and `a_drag_over_a_wide_blur_draws_the_blur_from_the_still_frame` the canvas on and off the worker. Not yet: a worker frame shows one display frame after the overlays, and the first frame of an interaction can land on the renderer that has not made the rasters yet (follow-up: render every canvas frame on the worker, waiting briefly for fast ones). -- **Panning over a cropped effect raster:** when a pan makes a shadow, glow or filtered content raster cropped to the view again at the same zoom and rotation, the renderer makes it over a margin around the view too (up to half the view's longer side, within 8.4 million pixels), and later pans that keep the view inside that margin draw the raster instead of making it again. Zooming and the first frame at a zoom make the raster without the margin. The canvas pans by whole device pixels: the wheel, a trackpad, a touch screen and the scroll bars add the part of a pixel left over to the next scroll of the same view, and Hand tool and scroll bar thumb drags round the distance dragged. A shadow or glow raster holds the shadows of group members outside the view, so a pan that shows a member draws its shadow. `pans_within_a_cropped_rasters_margin_draw_it_kept` covers Drop Shadow, Gaussian Blur and Feather on a large image at 100%. `a_groups_shadow_raster_holds_the_members_outside_the_view` covers a group's members, `fractional_scrolls_moved_in_whole_pixels_draw_a_cropped_raster_kept` covers scrolls by fractions of a pixel, and `scrolls_and_pans_move_the_view_by_whole_device_pixels` covers the canvas. +- **Panning over a cropped effect raster:** when a pan makes a shadow, glow or filtered content raster cropped to the view again at the same zoom and rotation, the renderer makes it over a margin around the view too (up to half the view's longer side, within 8.4 million pixels), and later pans that keep the view inside that margin draw the raster instead of making it again. Zooming and the first frame at a zoom make the raster without the margin. The canvas pans by whole device pixels: the wheel, a trackpad, a touch screen and the scroll bars add the part of a pixel left over to the next scroll of the same view, and Hand tool and scroll bar thumb drags round the distance dragged. A Drop Shadow or Outer Glow raster holds the shadow or glow of group members outside the view, so a pan that shows a member draws its shadow or glow from the raster. `pans_within_a_cropped_rasters_margin_draw_it_kept` covers Drop Shadow, Gaussian Blur and Feather on a large image at 100%. `a_groups_shadow_raster_holds_the_members_outside_the_view` covers a group's members, `fractional_scrolls_moved_in_whole_pixels_draw_a_cropped_raster_kept` covers scrolls by fractions of a pixel, and `scrolls_and_pans_move_the_view_by_whole_device_pixels` covers the canvas. - **Moving objects with raster effects (#1257):** during a drag or a dialog's preview, an object whose content only moved draws its cached drop shadows, outer glows and filtered content (Gaussian Blur, Feather and the Photoshop-style filters) from the rasters of an earlier frame at the nearest whole pixel, without running the effects again. The renderer first draws the moved content where the old content lies in its raster and compares the pixels. De-Interlace runs again. The frame after the drag runs the effects again and draws what a fresh renderer draws; on the desktop, the canvas renders that frame on the render worker. `texture_drag_perf` times a drag's frames and the frame after it. From b72c822f1d8e32a08b833402dd22a62a7f18fd07 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 12:39:55 -0800 Subject: [PATCH 022/513] Add font-aware OpenType stylistic sets menu --- crates/text/src/fontdb.rs | 2 + crates/text/src/fontdb/stylistic_sets.rs | 128 +++++++++++++++++++++++ crates/text/src/lib.rs | 6 +- crates/ui-egui/src/panels/opentype.rs | 29 ++++- docs/roadmap.md | 5 +- docs/target-app-parity.md | 5 +- docs/type-parity.md | 5 +- 7 files changed, 171 insertions(+), 9 deletions(-) create mode 100644 crates/text/src/fontdb/stylistic_sets.rs diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index 6eca651bb6..1972577ef5 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -26,6 +26,7 @@ mod glyph_pen; mod lookup; mod names; mod scan; +mod stylistic_sets; mod traits; mod wanted; @@ -57,6 +58,7 @@ pub(crate) use scan::file_face_names_within; #[cfg(test)] use scan::{MAX_FACES, enumerate_faces}; pub use scan::{is_font_file, is_suitcase}; +pub use stylistic_sets::StylisticSet; use traits::Alias; #[cfg(test)] use traits::{FaceKeys, face_names}; diff --git a/crates/text/src/fontdb/stylistic_sets.rs b/crates/text/src/fontdb/stylistic_sets.rs new file mode 100644 index 0000000000..3bded3d03f --- /dev/null +++ b/crates/text/src/fontdb/stylistic_sets.rs @@ -0,0 +1,128 @@ +//! The font-defined OpenType stylistic sets offered by the OpenType panel. +//! + +use skrifa::raw::TableProvider; +use skrifa::raw::tables::layout::{FeatureList, FeatureParams}; + +use super::FontFace; +use super::names::name; + +/// One `ss01`–`ss20` feature in a face. `number` is the tag's number; `name` is the font's UI +/// label when it supplies one, otherwise `Set 1` through `Set 20`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StylisticSet { + pub number: u8, + pub name: String, +} + +/// The `ssNN` number in a feature tag, if it is one of the twenty registered sets. +fn number(tag: [u8; 4]) -> Option { + if &tag[..2] != b"ss" || !tag[2].is_ascii_digit() || !tag[3].is_ascii_digit() { + return None; + } + let n = usize::from(tag[2] - b'0') * 10 + usize::from(tag[3] - b'0'); + (1..=20).contains(&n).then_some(n) +} + +/// Collect registered set records from either layout table. Fonts may carry a set in GSUB, GPOS, +/// or both. A readable custom name takes precedence over the numbered fallback. +fn collect(font: &skrifa::FontRef<'_>, features: FeatureList<'_>, labels: &mut [Option; 20]) { + for record in features.feature_records().iter().take(4096) { + let Some(n) = number(record.feature_tag().to_be_bytes()) else { continue }; + let Ok(feature) = record.feature(features.offset_data()) else { continue }; + if feature.lookup_list_indices().is_empty() { + continue; + } + let custom = feature.feature_params().and_then(Result::ok).and_then(|params| match params { + FeatureParams::StylisticSet(p) => name(font, &[p.ui_name_id()]), + _ => None, + }); + let slot = &mut labels[n - 1]; + if let Some(custom) = custom { + *slot = Some(custom); + } else if slot.is_none() { + *slot = Some(format!("Set {n}")); + } + } +} + +impl FontFace { + /// Sets this face lists in GSUB or GPOS, in number order. Damaged tables and records are + /// skipped, and no more than 4096 feature records from either table are read. + pub fn stylistic_sets(&self) -> Vec { + let Some(font) = self.skrifa() else { return Vec::new() }; + let mut labels: [Option; 20] = std::array::from_fn(|_| None); + if let Ok(gsub) = font.gsub() + && let Ok(features) = gsub.feature_list() + { + collect(&font, features, &mut labels); + } + if let Ok(gpos) = font.gpos() + && let Ok(features) = gpos.feature_list() + { + collect(&font, features, &mut labels); + } + labels.into_iter().enumerate().filter_map(|(i, name)| Some(StylisticSet { number: u8::try_from(i + 1).ok()?, name: name? })).collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use skrifa::MetadataProvider; + use write_fonts::FontBuilder; + use write_fonts::tables::gsub::{Gsub, SingleSubstFormat2, SubstitutionLookup, SubstitutionLookupList}; + use write_fonts::tables::layout::{ + CoverageFormat1, Feature, FeatureList, FeatureParams as WriteParams, FeatureRecord, LangSys, Lookup, Script, ScriptList, ScriptRecord, + StylisticSetParams, + }; + use write_fonts::types::{GlyphId16, NameId, Tag}; + + #[test] + fn registered_set_numbers_only() { + assert_eq!(number(*b"ss01"), Some(1)); + assert_eq!(number(*b"ss20"), Some(20)); + assert_eq!(number(*b"ss00"), None); + assert_eq!(number(*b"ss21"), None); + assert_eq!(number(*b"salt"), None); + } + + #[test] + fn face_lists_only_its_sets_with_the_fonts_name() { + const BASE: &[u8] = include_bytes!("../../../../assets/fonts/SourceSans3-Regular.ttf"); + let base = skrifa::FontRef::new(BASE).unwrap(); + let gid = |c| GlyphId16::new(u16::try_from(base.charmap().map(c).unwrap().to_u32()).unwrap()); + let subst = SingleSubstFormat2::new(CoverageFormat1::new(vec![gid('a')]).into(), vec![gid('A')]); + let lookup = SubstitutionLookup::Single(Lookup::new(Default::default(), vec![subst.into()])); + let features = FeatureList::new(vec![ + FeatureRecord::new(Tag::new(b"ss01"), Feature::new(Some(WriteParams::StylisticSet(StylisticSetParams::new(NameId::new(256)))), vec![0])), + FeatureRecord::new(Tag::new(b"ss03"), Feature::new(None, vec![0])), + FeatureRecord::new(Tag::new(b"ss05"), Feature::new(None, vec![])), + ]); + let scripts = ScriptList::new(vec![ScriptRecord::new(Tag::new(b"DFLT"), Script::new(Some(LangSys::new(vec![0, 1, 2])), vec![]))]); + let mut builder = FontBuilder::new(); + let names = crate::test_fonts::name_table(&[ + (1, "Stylistic Test Sans"), + (2, "Regular"), + (4, "Stylistic Test Sans Regular"), + (6, "StylisticTestSans-Regular"), + (256, "Curved Capitals"), + ]) + .unwrap(); + builder.add_raw(Tag::new(b"name"), names); + builder.add_table(&Gsub::new(scripts, features, SubstitutionLookupList::new(vec![lookup]))).unwrap(); + for record in base.table_directory.table_records() { + let tag = Tag::new(&record.tag().to_be_bytes()); + if !builder.contains(tag) { + builder.add_raw(tag, base.table_data(record.tag()).unwrap().as_bytes()); + } + } + let db = super::super::FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(builder.build()), 1); + let face = db.face("Stylistic Test Sans", "Regular").unwrap(); + assert_eq!( + face.stylistic_sets(), + [StylisticSet { number: 1, name: "Curved Capitals".into() }, StylisticSet { number: 3, name: "Set 3".into() }] + ); + } +} diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index a49e187aed..eb9f14bf3a 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -35,9 +35,9 @@ pub use bitmap::GlyphImage; pub use craft_fonts::{CRAFT_FONTS, CraftFont, WEB_FONTS, WebFont}; pub use features::{EXTRA_FEATURES, LIGATURE_TRACKING_LIMITS, MAX_STYLE_FEATURES, OtFeatures, explicit_ligatures, ligatures_suppressed_by}; pub use fontdb::{ - FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontMatch, FontTraits, IcfMargins, PlatformFontFiles, WantedFont, WantedFonts, app_font_dir, - is_font_file, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, style_weight, - system_font_dirs, user_font_dirs, + FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontMatch, FontTraits, IcfMargins, PlatformFontFiles, StylisticSet, WantedFont, WantedFonts, + app_font_dir, is_font_file, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, + style_weight, system_font_dirs, user_font_dirs, }; pub use hyphen::{hyphenation_exceptions, set_hyphenation_exceptions}; use std::sync::Arc; diff --git a/crates/ui-egui/src/panels/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index d6c62a13d1..443ca87e1a 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -4,7 +4,7 @@ use egui::Ui; use serde_json::json; -use vectorcraft_text::{EXTRA_FEATURES, OtFeatures}; +use vectorcraft_text::{EXTRA_FEATURES, FontDb, OtFeatures}; use super::character::{shared, text_editing, text_style}; use crate::VectorcraftApp; @@ -199,6 +199,21 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { change = Some(Change::Toggle(flag, !on)); } } + // The font, not the text, decides which numbered sets can be offered. Each set is an + // independent feature, so the menu permits several at once. A font's own label wins over + // the numbered fallback. See the public Stylistic Sets help page. + let sets = FontDb::global().face(&st.font_family, &st.font_style).map(|face| face.stylistic_sets()).unwrap_or_default(); + ui.add_enabled_ui(!sets.is_empty(), |ui| { + ui.menu_button(tl!("Stylistic Sets"), |ui| { + for set in &sets { + let flag = Flag::Extra(EXTRA_FEATURES[usize::from(set.number - 1)]); + let on = flag.get(&next); + if widgets::check(ui, &set.name, on, true) { + change = Some(Change::Toggle(flag, !on)); + } + } + }); + }); if cur.ligatures && vectorcraft_text::ligatures_suppressed_by(st.tracking) && !vectorcraft_text::explicit_ligatures(&st.features) { widgets::dim_label(ui, tl!("Ligatures are off while the text is tracked.")); } @@ -284,6 +299,18 @@ mod tests { } } + /// Stylistic sets are independent: selecting a second set keeps the first, and clearing one + /// keeps the other. The command reaches the selected text's stored OpenType feature tags. + #[test] + fn multiple_stylistic_sets_stay_independent() { + let mut app = selected_text(); + edit(&mut app, Change::Toggle(Flag::Extra("ss01"), true)); + edit(&mut app, Change::Toggle(Flag::Extra("ss03"), true)); + assert_eq!(text_style(&app).unwrap().0.features, ["ss01", "ss03"]); + edit(&mut app, Change::Toggle(Flag::Extra("ss01"), false)); + assert_eq!(text_style(&app).unwrap().0.features, ["ss03"]); + } + /// The Figure menu lists its five entries in order; Proportional Lining sets `pnum` and /// `lnum` and clears `tnum` and `onum`, Tabular Lining clears `pnum`, Proportional Oldstyle /// clears `lnum`, and Default Figure and Tabular Oldstyle clear `pnum` and `lnum`. diff --git a/docs/roadmap.md b/docs/roadmap.md index cd27fae7f4..d4bf3859c7 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (OpenType panel offers font-defined Stylistic Sets; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -105,7 +105,7 @@ Checked 2026-10-10 from the code, tests and open issues; no workflow fails, so V | M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; confirm the Scale Strokes & Effects default | 4–8 | | M5 | Performance | 🟡 background render + caches + MT done; `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 | -| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; tab leaders, spell check, vertical type pending | 45–60 | +| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; tab leaders, spell check, vertical type pending | 45–60 | | M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 🟡 Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; tab leaders, spell check, vertical type pending | 45–60 | | M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 🟡 Fullwidth `!` / `?` keep an upright fallback in vertical type; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; tab leaders, spell check, vertical type pending | 45–60 | | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box | 2–4 | @@ -158,6 +158,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | M7: the OpenType panel offers the selected font's available Stylistic Sets with custom or numbered names; estimates unchanged. | | 2026-11-03 | minor | M1: Enclosing Lasso adds freehand whole-object selection under Object › Plug-ins; estimates unchanged. | | 2026-11-02 | minor | Font-family fields in Character, Properties and Control step selected text with the wheel (#5253), with one undo step per notch; scores and estimates unchanged. | | 2026-11-03 | minor | M7 records Find Font's shipped replacement-source chooser (#5217); estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9367a069e8..cc60129135 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (Actions panel steps excluded from playback; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (OpenType Stylistic Sets menu added; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -23,6 +23,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | The OpenType panel offers the selected font's stylistic sets by custom or numbered name, and allows several to be active. Scores and estimates unchanged. | | 2026-11-03 | minor | Actions panel: an expanded action's steps can be excluded from playback and Batch… by clearing their checkmarks; action and set checkmarks include or exclude all their steps, and exclusions survive restart, duplication and `.vcactions` save/load. Scores and estimates unchanged. | | 2026-11-03 | minor | Correct the Type core missing list and remove duplicate target and Type core entries: Hyphenation and Justification options are complete; the remaining Every-line Composer fidelity limits stay listed. Record the Kashidas paragraph lengths and per-character switch in the feature history (#5404). Scores and estimates unchanged. | | 2026-11-03 | minor | Correct the Type core missing list: Hyphenation and Justification options are complete; the remaining Every-line Composer fidelity limits stay listed. Record the Kashidas paragraph lengths and per-character switch in the feature history (#5404). Scores and estimates unchanged. | @@ -143,6 +144,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (four generated libraries, User Defined, Other Library…, Save Brushes); remaining: Art brush Overlap, Pattern brush auto corners, pen pressure on macOS, tilt/bearing/rotation | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, 3D Classic, Turntable views, 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12) | +| Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout, optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied | | Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout, optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests) | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, spell check, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Symbols, blends, envelopes, Repeat, perspective | 5 | 87% | 30.7's Blend panel with ease in/out, on-canvas Direct Selection of parts inside dynamic symbol instances and their `.ai` round trip, more built-in symbol libraries, envelope Anti-Alias/Preserve Shape; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic symbols keep per-instance appearance linked, #4938) are done | 4–8 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; scores and hours unchanged | @@ -914,6 +916,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Character panel's Small Caps, Superscript and Subscript buttons and the panel menu's items of the same names turn small caps and the superscript or subscript position on and off for the selected type, or for the text the Type tool has selected (`text.setFormat` or `text.setRangeStyle` `{smallCaps, position}`), in Document Setup's proportions. Turning Superscript on turns Subscript off, and turning Subscript on turns Superscript off. A button or item shows as on when the first selected character (at a caret, the character before it) has its attribute. The OpenType panel's Stylistic Alternates and Titling Alternates checkboxes turn `salt` and `titl` on and off for the selected type, and its Figure menu lists Default Figure, Tabular Lining, Proportional Lining, Proportional Oldstyle and Tabular Oldstyle; Proportional Lining sets `pnum` and `lnum` and turns `tnum` and `onum` off, Tabular Lining turns `pnum` off and keeps `lnum`, Proportional Oldstyle turns `lnum` off and keeps `pnum`, and Default Figure and Tabular Oldstyle turn `pnum` and `lnum` off. Behavior reference: [Format text with OpenType features](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/format-text-with-opentype-features.html) and [Use swashes, titling alternates, or stylistic alternates](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/use-swashes-titling-alternates-or-stylistic-alternates.html) (public documentation). Tests: `panels::opentype::tests`. The OpenType panel's Position menu lists Default Position, Superscript, Subscript, Numerator and Denominator, as [Format text with OpenType features](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/format-text-with-opentype-features.html) describes; Superscript, Subscript, Numerator and Denominator set `sups`, `subs`, `numr` and `dnom` for the selected type and turn the other three off, and Default Position turns all four off. The menu shows Mixed when the characters it acts on differ, and an entry chosen then applies to all of them. These two rules are VectorCraft's own, as is setting the feature on type whose font lacks the glyphs, which then draws unchanged. The panel's menus and checkboxes change only their own features on each selected character, so characters keep their other OpenType features (`text.setStyle` and `text.setRangeStyle` `{featureChanges}`). Tests: `panels::opentype::tests`, `features::tests::numerators_and_denominators_are_kept_and_shaped`. + The OpenType panel's Stylistic Sets menu offers `ss01`–`ss20` sets present in the selected text's font, using the font's custom labels when available and numbered labels otherwise. Sets can be combined and deselected individually. With mixed fonts, the menu currently shows the first selected style's sets and applies the feature tag to all selected text; a font without that set draws unchanged. The mixed-font rule is a VectorCraft choice pending a behavior decision. Behavior reference: [Add stylistic sets to selected text](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/add-stylistic-sets-to-selected-text.html) and the [OpenType specification](https://learn.microsoft.com/en-us/typography/opentype/spec/features_pt). `text.setStyle {stroke, strokeWidth}` sets the character stroke's color and weight of the selected type or of a range of its characters (the weight in document points, as `stroke.set` sets it), in the same undo step as the command's other changes. Tests: `tests::textedit::set_style_sets_the_character_stroke`. - **Paragraph alignment:** the shared Paragraph/Properties alignment row leaves every button unselected when the paragraphs it acts on differ. Auto resolves per paragraph; choosing an alignment uses the existing command. Headless paragraph_mixed_alignment_* regressions exercise mixed → Center → Undo, caret/uniform states, Unicode range boundaries, Auto/direction, split runs and grouped text. These regressions and full integration CI pass. Original captures confirm mixed → Center → Undo in the existing alignment-button layout. The [public Paragraph panel guide](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/paragraph-panel-overview.html) lists the seven controls, but does not specify mixed-state rendering. Other paragraph fields remain outside this change; scores and hours unchanged. For Auto Size area type in columns, the bisection for the frame's height runs on the lines of the one-column layout, and its result is checked with at most two layouts of the columns. When the text wraps around objects or does not fit the one-column layout, or when the check fails, the columns are laid out at every step of the bisection, as before. Typing at the start of a story of 50,000 characters in 2 columns took 1,670 ms a keystroke and now takes 292 ms (release build, `auto_height_in_columns_typing_timing`). diff --git a/docs/type-parity.md b/docs/type-parity.md index 5e506c2360..59cafc3db7 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -1,6 +1,6 @@ # Type parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (Touch Type moves right-to-left characters along their line; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (OpenType panel lists font-defined stylistic sets; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) Type is Illustrator's largest single area by use (weight 13 of 105 across "Type core" and "Type advanced" in [target-app-parity.md](target-app-parity.md)). This checklist lists the features one by one. Status is from the @@ -29,7 +29,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Character and Paragraph panels, styles with overrides | done | Character-style Auto-leading resets, partial definitions, local leading overrides, override markers, Undo/Redo and native serialization have regression coverage; differing paragraph alignments leave the shared alignment buttons unselected (headless regressions, full integration CI and visual review pass); mixed-value display for other paragraph fields remains missing | | Character size and horizontal scale after object/group scaling | done | #1034: fields and setters compensate the stored affine; point size follows the transformed em-height axis, not the glyph ink bounds. Range edits, keyboard increments, leading and baseline shift use document points; rotation, reflection and shear remain editable. | | Preserve font sizes while scaling a group | missing | Separate enhancement; scaling still scales text with the other artwork. | -| OpenType panel, Glyphs panel, alternates | done | Highlight Alternate Glyphs preference (#394, off by default) paints pink behind OpenType substitutions on screen when on (required shaping such as Arabic joining forms and the lam-alef ligature, including a lam-alef older fonts file under `liga`, is not highlighted; an optional feature that changes the ligature is); stylistic sets ss01–ss20, stylistic and titling alternates, proportional and lining figures, superscript and subscript are character-style features (`text.setStyle {features}`, #1607); the OpenType panel's Position menu sets superscript, subscript, numerator or denominator glyphs (`sups`, `subs`, `numr`, `dnom`). The Glyphs panel highlights the character selected with the Type tool (a range's first character, else the one before the caret) and scrolls it into view as the selection moves (#4908; `panels::glyphs` tests); its Show menu lists Unicode ranges, and Alternates for Current Selection is not there yet | +| OpenType panel, Glyphs panel, alternates | done | Highlight Alternate Glyphs preference (#394, off by default) paints pink behind OpenType substitutions on screen when on (required shaping such as Arabic joining forms and the lam-alef ligature, including a lam-alef older fonts file under `liga`, is not highlighted; an optional feature that changes the ligature is); stylistic sets ss01–ss20, stylistic and titling alternates, proportional and lining figures, superscript and subscript are character-style features (`text.setStyle {features}`, #1607); the OpenType panel's Position menu sets superscript, subscript, numerator or denominator glyphs (`sups`, `subs`, `numr`, `dnom`). The OpenType panel's Stylistic Sets menu lists the selected font's `ss01`–`ss20` features, using a font-supplied name where available and `Set N` otherwise; several sets can be active, and selecting an active one removes it. For a mixed-font selection it currently uses the first selected style's font, a VectorCraft choice pending a behavior decision ([public help](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/add-stylistic-sets-to-selected-text.html), [OpenType feature specification](https://learn.microsoft.com/en-us/typography/opentype/spec/features_pt)). The Glyphs panel highlights the character selected with the Type tool (a range's first character, else the one before the caret) and scrolls it into view as the selection moves (#4908; `panels::glyphs` tests); its Show menu lists Unicode ranges, and Alternates for Current Selection is not there yet | | Font menu: samples, live preview, filters, favourites, recent families; font matching by any name; Find Font | done | #3515: recently applied families appear first, once each; missing families are omitted and the existing Number of Recent Fonts setting applies; #339; script filter: Japanese, Latin, Thai; the font scan on Linux also reads the folders fontconfig's configuration lists, such as TeX fonts under `/usr/share/texmf/fonts` (#1548, fixes #1529; not verified on Linux) | | Missing glyphs set in an installed font made for their script (Thai, Lao, Khmer, Myanmar first; then any font that has them) | done | Thai: Leelawadee UI, Tahoma, Thonburi, Sukhumvit Set, Noto Sans Thai, TLWG | | Full font-name matching (OpenType name ID 4) | done | #1258: loaded/cataloged faces and Missing Fonts searches; localized names and variable default faces; Windows font-service QA pending | @@ -77,6 +77,7 @@ Character Styles menu New/Redefine and footer New capture the first selected cha | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | The OpenType panel lists the selected font's available Stylistic Sets with its custom names or numbered labels; sets can be combined and deselected. Scores and estimates unchanged. | | 2026-11-03 | minor | Character-menu Kashidas controls selected characters separately from the paragraph's Insert Kashidas length. Existing text allows Kashidas by default; scores and estimates unchanged. | | 2026-11-03 | minor | Type on a Path Options has a Preview checkbox: the type follows the fields while it is on, Cancel restores it, OK is one undo step (#5360, as public tutorials of the dialog show); scores and estimates unchanged. | | 2026-11-02 | minor | The wheel over Character, Properties and Control font-family fields changes selected text, one undo step per notch (#5253); scores and estimates unchanged. | From 1858da4106d27ccb010d7ae0bc6ce9610d314b97 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 15:45:49 -0800 Subject: [PATCH 023/513] Type: use selected font version for stylistic sets --- crates/ui-egui/src/panels/opentype.rs | 2 +- docs/target-app-parity.md | 2 +- docs/type-parity.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index 443ca87e1a..cdff2df1c2 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -202,7 +202,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // The font, not the text, decides which numbered sets can be offered. Each set is an // independent feature, so the menu permits several at once. A font's own label wins over // the numbered fallback. See the public Stylistic Sets help page. - let sets = FontDb::global().face(&st.font_family, &st.font_style).map(|face| face.stylistic_sets()).unwrap_or_default(); + let sets = FontDb::global().style_face(&st).map(|face| face.stylistic_sets()).unwrap_or_default(); ui.add_enabled_ui(!sets.is_empty(), |ui| { ui.menu_button(tl!("Stylistic Sets"), |ui| { for set in &sets { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index cc60129135..02054ddd17 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -916,7 +916,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Character panel's Small Caps, Superscript and Subscript buttons and the panel menu's items of the same names turn small caps and the superscript or subscript position on and off for the selected type, or for the text the Type tool has selected (`text.setFormat` or `text.setRangeStyle` `{smallCaps, position}`), in Document Setup's proportions. Turning Superscript on turns Subscript off, and turning Subscript on turns Superscript off. A button or item shows as on when the first selected character (at a caret, the character before it) has its attribute. The OpenType panel's Stylistic Alternates and Titling Alternates checkboxes turn `salt` and `titl` on and off for the selected type, and its Figure menu lists Default Figure, Tabular Lining, Proportional Lining, Proportional Oldstyle and Tabular Oldstyle; Proportional Lining sets `pnum` and `lnum` and turns `tnum` and `onum` off, Tabular Lining turns `pnum` off and keeps `lnum`, Proportional Oldstyle turns `lnum` off and keeps `pnum`, and Default Figure and Tabular Oldstyle turn `pnum` and `lnum` off. Behavior reference: [Format text with OpenType features](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/format-text-with-opentype-features.html) and [Use swashes, titling alternates, or stylistic alternates](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/use-swashes-titling-alternates-or-stylistic-alternates.html) (public documentation). Tests: `panels::opentype::tests`. The OpenType panel's Position menu lists Default Position, Superscript, Subscript, Numerator and Denominator, as [Format text with OpenType features](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/format-text-with-opentype-features.html) describes; Superscript, Subscript, Numerator and Denominator set `sups`, `subs`, `numr` and `dnom` for the selected type and turn the other three off, and Default Position turns all four off. The menu shows Mixed when the characters it acts on differ, and an entry chosen then applies to all of them. These two rules are VectorCraft's own, as is setting the feature on type whose font lacks the glyphs, which then draws unchanged. The panel's menus and checkboxes change only their own features on each selected character, so characters keep their other OpenType features (`text.setStyle` and `text.setRangeStyle` `{featureChanges}`). Tests: `panels::opentype::tests`, `features::tests::numerators_and_denominators_are_kept_and_shaped`. - The OpenType panel's Stylistic Sets menu offers `ss01`–`ss20` sets present in the selected text's font, using the font's custom labels when available and numbered labels otherwise. Sets can be combined and deselected individually. With mixed fonts, the menu currently shows the first selected style's sets and applies the feature tag to all selected text; a font without that set draws unchanged. The mixed-font rule is a VectorCraft choice pending a behavior decision. Behavior reference: [Add stylistic sets to selected text](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/add-stylistic-sets-to-selected-text.html) and the [OpenType specification](https://learn.microsoft.com/en-us/typography/opentype/spec/features_pt). + The OpenType panel's Stylistic Sets menu offers `ss01`–`ss20` sets present in the selected text's font, using the font's custom labels when available and numbered labels otherwise. Sets can be combined and deselected individually. With mixed fonts, the menu shows the first selected character's font's sets and applies the feature tag to all selected text; a font without that set draws unchanged. The mixed-font rule is a VectorCraft design choice. Behavior reference: [Add stylistic sets to selected text](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/add-stylistic-sets-to-selected-text.html) and the [OpenType specification](https://learn.microsoft.com/en-us/typography/opentype/spec/features_pt). `text.setStyle {stroke, strokeWidth}` sets the character stroke's color and weight of the selected type or of a range of its characters (the weight in document points, as `stroke.set` sets it), in the same undo step as the command's other changes. Tests: `tests::textedit::set_style_sets_the_character_stroke`. - **Paragraph alignment:** the shared Paragraph/Properties alignment row leaves every button unselected when the paragraphs it acts on differ. Auto resolves per paragraph; choosing an alignment uses the existing command. Headless paragraph_mixed_alignment_* regressions exercise mixed → Center → Undo, caret/uniform states, Unicode range boundaries, Auto/direction, split runs and grouped text. These regressions and full integration CI pass. Original captures confirm mixed → Center → Undo in the existing alignment-button layout. The [public Paragraph panel guide](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/paragraph-panel-overview.html) lists the seven controls, but does not specify mixed-state rendering. Other paragraph fields remain outside this change; scores and hours unchanged. For Auto Size area type in columns, the bisection for the frame's height runs on the lines of the one-column layout, and its result is checked with at most two layouts of the columns. When the text wraps around objects or does not fit the one-column layout, or when the check fails, the columns are laid out at every step of the bisection, as before. Typing at the start of a story of 50,000 characters in 2 columns took 1,670 ms a keystroke and now takes 292 ms (release build, `auto_height_in_columns_typing_timing`). diff --git a/docs/type-parity.md b/docs/type-parity.md index 59cafc3db7..12b6ef401e 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -29,7 +29,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Character and Paragraph panels, styles with overrides | done | Character-style Auto-leading resets, partial definitions, local leading overrides, override markers, Undo/Redo and native serialization have regression coverage; differing paragraph alignments leave the shared alignment buttons unselected (headless regressions, full integration CI and visual review pass); mixed-value display for other paragraph fields remains missing | | Character size and horizontal scale after object/group scaling | done | #1034: fields and setters compensate the stored affine; point size follows the transformed em-height axis, not the glyph ink bounds. Range edits, keyboard increments, leading and baseline shift use document points; rotation, reflection and shear remain editable. | | Preserve font sizes while scaling a group | missing | Separate enhancement; scaling still scales text with the other artwork. | -| OpenType panel, Glyphs panel, alternates | done | Highlight Alternate Glyphs preference (#394, off by default) paints pink behind OpenType substitutions on screen when on (required shaping such as Arabic joining forms and the lam-alef ligature, including a lam-alef older fonts file under `liga`, is not highlighted; an optional feature that changes the ligature is); stylistic sets ss01–ss20, stylistic and titling alternates, proportional and lining figures, superscript and subscript are character-style features (`text.setStyle {features}`, #1607); the OpenType panel's Position menu sets superscript, subscript, numerator or denominator glyphs (`sups`, `subs`, `numr`, `dnom`). The OpenType panel's Stylistic Sets menu lists the selected font's `ss01`–`ss20` features, using a font-supplied name where available and `Set N` otherwise; several sets can be active, and selecting an active one removes it. For a mixed-font selection it currently uses the first selected style's font, a VectorCraft choice pending a behavior decision ([public help](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/add-stylistic-sets-to-selected-text.html), [OpenType feature specification](https://learn.microsoft.com/en-us/typography/opentype/spec/features_pt)). The Glyphs panel highlights the character selected with the Type tool (a range's first character, else the one before the caret) and scrolls it into view as the selection moves (#4908; `panels::glyphs` tests); its Show menu lists Unicode ranges, and Alternates for Current Selection is not there yet | +| OpenType panel, Glyphs panel, alternates | done | Highlight Alternate Glyphs preference (#394, off by default) paints pink behind OpenType substitutions on screen when on (required shaping such as Arabic joining forms and the lam-alef ligature, including a lam-alef older fonts file under `liga`, is not highlighted; an optional feature that changes the ligature is); stylistic sets ss01–ss20, stylistic and titling alternates, proportional and lining figures, superscript and subscript are character-style features (`text.setStyle {features}`, #1607); the OpenType panel's Position menu sets superscript, subscript, numerator or denominator glyphs (`sups`, `subs`, `numr`, `dnom`). The OpenType panel's Stylistic Sets menu lists the selected font's `ss01`–`ss20` features, using a font-supplied name where available and `Set N` otherwise; several sets can be active, and selecting an active one removes it. For a mixed-font selection it uses the first selected character's font, a VectorCraft design choice ([public help](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/add-stylistic-sets-to-selected-text.html), [OpenType feature specification](https://learn.microsoft.com/en-us/typography/opentype/spec/features_pt)). The Glyphs panel highlights the character selected with the Type tool (a range's first character, else the one before the caret) and scrolls it into view as the selection moves (#4908; `panels::glyphs` tests); its Show menu lists Unicode ranges, and Alternates for Current Selection is not there yet | | Font menu: samples, live preview, filters, favourites, recent families; font matching by any name; Find Font | done | #3515: recently applied families appear first, once each; missing families are omitted and the existing Number of Recent Fonts setting applies; #339; script filter: Japanese, Latin, Thai; the font scan on Linux also reads the folders fontconfig's configuration lists, such as TeX fonts under `/usr/share/texmf/fonts` (#1548, fixes #1529; not verified on Linux) | | Missing glyphs set in an installed font made for their script (Thai, Lao, Khmer, Myanmar first; then any font that has them) | done | Thai: Leelawadee UI, Tahoma, Thonburi, Sukhumvit Set, Noto Sans Thai, TLWG | | Full font-name matching (OpenType name ID 4) | done | #1258: loaded/cataloged faces and Missing Fonts searches; localized names and variable default faces; Windows font-service QA pending | From 4fa4862613e7598cf59518e4da0339f2e4850f3b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 21:01:29 -0800 Subject: [PATCH 024/513] Type: translate the numbered stylistic set label StylisticSet.name now holds only a name the font supplies. The OpenType panel shows a set without one as `Set {n}` through tl!, so the label is translated, and each UI catalog has a `Set {n}` row. --- crates/text/src/fontdb/stylistic_sets.rs | 20 ++++++++--------- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/panels/opentype.rs | 28 ++++++++++++++++++++++-- 28 files changed, 61 insertions(+), 13 deletions(-) diff --git a/crates/text/src/fontdb/stylistic_sets.rs b/crates/text/src/fontdb/stylistic_sets.rs index 3bded3d03f..8d65782270 100644 --- a/crates/text/src/fontdb/stylistic_sets.rs +++ b/crates/text/src/fontdb/stylistic_sets.rs @@ -8,11 +8,11 @@ use super::FontFace; use super::names::name; /// One `ss01`–`ss20` feature in a face. `number` is the tag's number; `name` is the font's UI -/// label when it supplies one, otherwise `Set 1` through `Set 20`. +/// label when it supplies one, and `None` otherwise. #[derive(Clone, Debug, PartialEq, Eq)] pub struct StylisticSet { pub number: u8, - pub name: String, + pub name: Option, } /// The `ssNN` number in a feature tag, if it is one of the twenty registered sets. @@ -25,8 +25,9 @@ fn number(tag: [u8; 4]) -> Option { } /// Collect registered set records from either layout table. Fonts may carry a set in GSUB, GPOS, -/// or both. A readable custom name takes precedence over the numbered fallback. -fn collect(font: &skrifa::FontRef<'_>, features: FeatureList<'_>, labels: &mut [Option; 20]) { +/// or both. `labels[n - 1]` is `Some` once set `n` is found, holding its readable custom name if +/// any record supplies one. +fn collect(font: &skrifa::FontRef<'_>, features: FeatureList<'_>, labels: &mut [Option>; 20]) { for record in features.feature_records().iter().take(4096) { let Some(n) = number(record.feature_tag().to_be_bytes()) else { continue }; let Ok(feature) = record.feature(features.offset_data()) else { continue }; @@ -38,10 +39,10 @@ fn collect(font: &skrifa::FontRef<'_>, features: FeatureList<'_>, labels: &mut [ _ => None, }); let slot = &mut labels[n - 1]; - if let Some(custom) = custom { + if custom.is_some() { *slot = Some(custom); } else if slot.is_none() { - *slot = Some(format!("Set {n}")); + *slot = Some(None); } } } @@ -51,7 +52,7 @@ impl FontFace { /// skipped, and no more than 4096 feature records from either table are read. pub fn stylistic_sets(&self) -> Vec { let Some(font) = self.skrifa() else { return Vec::new() }; - let mut labels: [Option; 20] = std::array::from_fn(|_| None); + let mut labels: [Option>; 20] = std::array::from_fn(|_| None); if let Ok(gsub) = font.gsub() && let Ok(features) = gsub.feature_list() { @@ -120,9 +121,6 @@ mod tests { let db = super::super::FontDb::with_font_dirs(vec![]); assert_eq!(db.add_font(builder.build()), 1); let face = db.face("Stylistic Test Sans", "Regular").unwrap(); - assert_eq!( - face.stylistic_sets(), - [StylisticSet { number: 1, name: "Curved Capitals".into() }, StylisticSet { number: 3, name: "Set 3".into() }] - ); + assert_eq!(face.stylistic_sets(), [StylisticSet { number: 1, name: Some("Curved Capitals".into()) }, StylisticSet { number: 3, name: None }]); } } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index b37a00f29d..a69bd4f0d7 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3238,6 +3238,7 @@ digits Malayalam Малаялам Swap start and end arrowheads Размяна на началната и крайната стрелка Swap the selected object for the file, keeping its place and transform Замяна на избрания обект с файла, като се запазват мястото и трансформациите му Stylistic Alternates Стилистични алтернативи + Set {n} Набор {n} Swash Декоративен елемент Swatch Conflict Конфликт на образци Swatch Conflicts Конфликти на образци diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 80241a31af..212e28f2bb 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1816,6 +1816,7 @@ digits Malayalam Malajalam Select text to set its OpenType features. Odaberite tekst da postavite njegove OpenType mogućnosti. Standard Ligatures Standardne ligature Stylistic Alternates Stilske alternative + Set {n} Skup {n} Swash Ukrasni potez Tabular Lining Tabelarne brojke Tabular Oldstyle Tabelarne stare brojke diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 95e790242c..552b0b8ac1 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6021,6 +6021,7 @@ anchor Points: Punts: Character Color Color del caràcter OpenType Features Funcions OpenType Stylistic Sets Jocs estilístics + Set {n} Joc {n} @msg features lists at most {max} tags features admet com a màxim {max} etiquetes @msg unknown OpenType feature `{t}` funció OpenType desconeguda `{t}` @msg {label} must be a number above 0 and at most {max} {label} ha de ser un nombre superior a 0 i com a màxim {max} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 358d560600..d96985198b 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6037,6 +6037,7 @@ anchor Points: Body: Character Color Barva znaků OpenType Features Funkce OpenType Stylistic Sets Stylistické sady + Set {n} Sada {n} @msg features lists at most {max} tags features obsahuje nejvýše {max} značek @msg unknown OpenType feature `{t}` neznámá funkce OpenType `{t}` @msg {label} must be a number above 0 and at most {max} {label} musí být číslo větší než 0 a nejvýše {max} diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 8c8b830238..b050dbb63d 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1656,6 +1656,7 @@ digits Malayalam Malayalam Select text to set its OpenType features. Markér tekst for at angive dens OpenType-funktioner. Standard Ligatures Standardligaturer Stylistic Alternates Stilistiske alternativer + Set {n} Sæt {n} Swash Sving Tabular Lining Tabulære versalcifre Tabular Oldstyle Tabulære mediævalcifre diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index ffdcec8b70..a26cc0c1af 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5622,6 +5622,7 @@ anchor Points: Punkte: Character Color Zeichenfarbe OpenType Features OpenType-Funktionen Stylistic Sets Stilsätze + Set {n} Satz {n} @msg features lists at most {max} tags features enthält höchstens {max} Tags @msg unknown OpenType feature `{t}` unbekannte OpenType-Funktion `{t}` @msg {label} must be a number above 0 and at most {max} {label} muss eine Zahl über 0 und höchstens {max} sein diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 8fc68ba0fc..78bc64257b 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5988,6 +5988,7 @@ anchor Points: Σημεία: Character Color Χρώμα χαρακτήρων OpenType Features Χαρακτηριστικά OpenType Stylistic Sets Στιλιστικά σύνολα + Set {n} Σύνολο {n} @msg features lists at most {max} tags Το features περιέχει έως {max} ετικέτες @msg unknown OpenType feature `{t}` άγνωστο χαρακτηριστικό OpenType `{t}` @msg {label} must be a number above 0 and at most {max} Το {label} πρέπει να είναι αριθμός μεγαλύτερος από 0 και έως {max} diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index ff63ecb215..4c49048ae8 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5979,6 +5979,7 @@ anchor Points: Puntos: Character Color Color de los caracteres OpenType Features Funciones OpenType Stylistic Sets Conjuntos estilísticos + Set {n} Conjunto {n} @msg features lists at most {max} tags features admite como máximo {max} etiquetas @msg unknown OpenType feature `{t}` función OpenType desconocida `{t}` @msg {label} must be a number above 0 and at most {max} {label} debe ser un número mayor que 0 y como máximo {max} diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 76aa0990b8..363c388db4 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6067,6 +6067,7 @@ anchor Points: Pisteet: Character Color Merkin väri OpenType Features OpenType-ominaisuudet Stylistic Sets Tyylisarjat + Set {n} Sarja {n} @msg features lists at most {max} tags features sisältää enintään {max} tunnistetta @msg unknown OpenType feature `{t}` tuntematon OpenType-ominaisuus `{t}` @msg {label} must be a number above 0 and at most {max} {label} on oltava luku, joka on yli 0 ja enintään {max} diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 22365ad64b..2fc442dab5 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6032,6 +6032,7 @@ anchor Points: Points : Character Color Couleur des caractères OpenType Features Fonctions OpenType Stylistic Sets Jeux stylistiques + Set {n} Jeu {n} @msg features lists at most {max} tags features contient au plus {max} balises @msg unknown OpenType feature `{t}` fonction OpenType inconnue `{t}` @msg {label} must be a number above 0 and at most {max} {label} doit être un nombre supérieur à 0 et au plus égal à {max} diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 9523bca336..f5be6e413b 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6021,6 +6021,7 @@ anchor Points: Pontok: Character Color Karakterszín OpenType Features OpenType-funkciók Stylistic Sets Stíluskészletek + Set {n} {n}. készlet @msg features lists at most {max} tags a features legfeljebb {max} címkét tartalmazhat @msg unknown OpenType feature `{t}` ismeretlen OpenType-funkció: `{t}` @msg {label} must be a number above 0 and at most {max} {label} 0-nál nagyobb és legfeljebb {max} értékű szám kell legyen diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 15969f1da1..0c4be65a60 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1656,6 +1656,7 @@ digits Malayalam Malayalam Select text to set its OpenType features. Pilih teks untuk mengatur fitur OpenType-nya. Standard Ligatures Ligatur standar Stylistic Alternates Alternatif gaya + Set {n} Set {n} Swash Swash Tabular Lining Lining tabular Tabular Oldstyle Oldstyle tabular diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 93ac2c95d2..12da089477 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5656,6 +5656,7 @@ anchor Points: Punti: Character Color Colore carattere OpenType Features Funzioni OpenType Stylistic Sets Set stilistici + Set {n} Set {n} @msg features lists at most {max} tags features contiene al massimo {max} tag @msg unknown OpenType feature `{t}` funzione OpenType sconosciuta `{t}` @msg {label} must be a number above 0 and at most {max} {label} deve essere un numero maggiore di 0 e al massimo {max} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 4fa88c824e..f68f17fc55 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5721,6 +5721,7 @@ anchor Points: ポイント: Character Color 文字カラー OpenType Features OpenType 機能 Stylistic Sets スタイルセット + Set {n} セット {n} @msg features lists at most {max} tags features に指定できるタグは {max} 個までです @msg unknown OpenType feature `{t}` 不明な OpenType 機能 `{t}` @msg {label} must be a number above 0 and at most {max} {label} には 0 より大きく {max} 以下の数値を指定してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index d3556f4434..f329a90f86 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6033,6 +6033,7 @@ anchor Points: წერტილები: Character Color სიმბოლოს ფერი OpenType Features OpenType შესაძლებლობები Stylistic Sets სტილისტური ნაკრებები + Set {n} ნაკრები {n} @msg features lists at most {max} tags features შეიძლება შეიცავდეს არაუმეტეს {max} ტეგს @msg unknown OpenType feature `{t}` უცნობი OpenType შესაძლებლობა `{t}` @msg {label} must be a number above 0 and at most {max} {label} უნდა იყოს 0-ზე მეტი და არაუმეტეს {max}-ისა რიცხვი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index b6e935e2ef..abdcb7cf63 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5617,6 +5617,7 @@ anchor Points: 포인트: Character Color 문자 색상 OpenType Features OpenType 기능 Stylistic Sets 스타일 세트 + Set {n} 세트 {n} @msg features lists at most {max} tags features에는 태그를 최대 {max}개까지 지정할 수 있습니다 @msg unknown OpenType feature `{t}` 알 수 없는 OpenType 기능 `{t}` @msg {label} must be a number above 0 and at most {max} {label}은(는) 0 초과 {max} 이하의 숫자여야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 2d2dcccf19..fb2ebeb99f 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1670,6 +1670,7 @@ digits Malayalam Malayalam Select text to set its OpenType features. Selecteer tekst om de OpenType-functies in te stellen. Standard Ligatures Standaardligaturen Stylistic Alternates Stilistische alternatieven + Set {n} Set {n} Swash Swash Tabular Lining Tabulaire lining Tabular Oldstyle Tabulaire oldstyle diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index d30c71807d..f329a539a8 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5891,6 +5891,7 @@ anchor Points: Punkty: Character Color Kolor znaków OpenType Features Funkcje OpenType Stylistic Sets Zestawy stylistyczne + Set {n} Zestaw {n} @msg features lists at most {max} tags features może zawierać najwyżej {max} znaczników @msg unknown OpenType feature `{t}` nieznana funkcja OpenType `{t}` @msg {label} must be a number above 0 and at most {max} {label} musi być liczbą większą od 0 i nie większą niż {max} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 9bde60f446..726c16d448 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5953,6 +5953,7 @@ anchor Points: Pontos: Character Color Cor do Caractere OpenType Features Recursos OpenType Stylistic Sets Conjuntos Estilísticos + Set {n} Conjunto {n} @msg features lists at most {max} tags features aceita no máximo {max} marcas @msg unknown OpenType feature `{t}` recurso OpenType desconhecido `{t}` @msg {label} must be a number above 0 and at most {max} {label} deve ser um número maior que 0 e no máximo {max} diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 0e55857a6b..ba7a946899 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6014,6 +6014,7 @@ anchor Points: Точки: Character Color Цвет символов OpenType Features Функции OpenType Stylistic Sets Стилистические наборы + Set {n} Набор {n} @msg features lists at most {max} tags features содержит не более {max} тегов @msg unknown OpenType feature `{t}` неизвестная функция OpenType `{t}` @msg {label} must be a number above 0 and at most {max} {label} должно быть числом больше 0 и не более {max} diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 49c81d06b7..81942ced57 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6089,6 +6089,7 @@ shape Open Öppen Character Color Teckenfärg OpenType Features OpenType-funktioner Stylistic Sets Stilistiska uppsättningar + Set {n} Uppsättning {n} @msg features lists at most {max} tags features får innehålla högst {max} taggar @msg unknown OpenType feature `{t}` okänd OpenType-funktion `{t}` @msg {label} must be a number above 0 and at most {max} {label} måste vara ett tal över 0 och högst {max} diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 3dfae8af33..af1a87f89f 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5994,6 +5994,7 @@ anchor Points: Noktalar: Character Color Karakter Rengi OpenType Features OpenType Özellikleri Stylistic Sets Stilistik Setler + Set {n} Set {n} @msg features lists at most {max} tags features en fazla {max} etiket içerebilir @msg unknown OpenType feature `{t}` bilinmeyen OpenType özelliği `{t}` @msg {label} must be a number above 0 and at most {max} {label} 0'ın üzerinde ve en fazla {max} olan bir sayı olmalıdır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 5d37cd09c3..07e5d8db94 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5636,6 +5636,7 @@ anchor Points: Точки: Character Color Колір символів OpenType Features Функції OpenType Stylistic Sets Стилістичні набори + Set {n} Набір {n} @msg features lists at most {max} tags features містить не більше {max} тегів @msg unknown OpenType feature `{t}` невідома функція OpenType `{t}` @msg {label} must be a number above 0 and at most {max} {label} має бути числом більше 0 і не більше {max} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 12fe935929..e0844fb251 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5637,6 +5637,7 @@ anchor Points: Điểm: Character Color Màu ký tự OpenType Features Tính năng OpenType Stylistic Sets Bộ phong cách + Set {n} Bộ {n} @msg features lists at most {max} tags features chứa tối đa {max} thẻ @msg unknown OpenType feature `{t}` tính năng OpenType không xác định `{t}` @msg {label} must be a number above 0 and at most {max} {label} phải là một số lớn hơn 0 và tối đa {max} diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index d9e5f84b42..1ea4703928 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5878,6 +5878,7 @@ anchor Points: 点: Character Color 字符颜色 OpenType Features OpenType 特性 Stylistic Sets 风格集 + Set {n} 风格集 {n} @msg features lists at most {max} tags features 最多包含 {max} 个标签 @msg unknown OpenType feature `{t}` 未知的 OpenType 特性 `{t}` @msg {label} must be a number above 0 and at most {max} {label} 必须是大于 0 且不超过 {max} 的数字 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index b387b0a810..8d7d0ff587 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5674,6 +5674,7 @@ anchor Points: 點: Character Color 字元顏色 OpenType Features OpenType 功能 Stylistic Sets 風格集 + Set {n} 風格集 {n} @msg features lists at most {max} tags features 最多包含 {max} 個標籤 @msg unknown OpenType feature `{t}` 未知的 OpenType 功能 `{t}` @msg {label} must be a number above 0 and at most {max} {label} 必須是大於 0 且不超過 {max} 的數字 diff --git a/crates/ui-egui/src/panels/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index cdff2df1c2..ca5a7dfb0e 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -4,7 +4,7 @@ use egui::Ui; use serde_json::json; -use vectorcraft_text::{EXTRA_FEATURES, FontDb, OtFeatures}; +use vectorcraft_text::{EXTRA_FEATURES, FontDb, OtFeatures, StylisticSet}; use super::character::{shared, text_editing, text_style}; use crate::VectorcraftApp; @@ -208,7 +208,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { for set in &sets { let flag = Flag::Extra(EXTRA_FEATURES[usize::from(set.number - 1)]); let on = flag.get(&next); - if widgets::check(ui, &set.name, on, true) { + if widgets::check(ui, &set_label(set), on, true) { change = Some(Change::Toggle(flag, !on)); } } @@ -222,6 +222,15 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// A Stylistic Sets menu entry: the font's own name for the set, or `Set 1` through `Set 20` in +/// the UI language. +fn set_label(set: &StylisticSet) -> String { + match &set.name { + Some(name) => name.clone(), + None => crate::i18n::fmt(tl!("Set {n}"), &[("n", &set.number.to_string())]), + } +} + /// The panel's checkbox rows, in the order they are drawn. fn rows() -> [Toggle; 9] { [ @@ -311,6 +320,21 @@ mod tests { assert_eq!(text_style(&app).unwrap().0.features, ["ss03"]); } + /// A set the font names keeps the font's name; a set without one gets the numbered label in + /// the UI language. + #[test] + fn stylistic_set_labels_follow_the_ui_language() { + let named = StylisticSet { number: 1, name: Some("Curved Capitals".into()) }; + let numbered = StylisticSet { number: 3, name: None }; + assert_eq!(set_label(&numbered), "Set 3"); + let Some(de) = crate::i18n::Lang::from_code("de") else { panic!("no German catalog") }; + crate::i18n::set_current(de); + let (named_de, numbered_de) = (set_label(&named), set_label(&numbered)); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(named_de, "Curved Capitals"); + assert_eq!(numbered_de, "Satz 3"); + } + /// The Figure menu lists its five entries in order; Proportional Lining sets `pnum` and /// `lnum` and clears `tnum` and `onum`, Tabular Lining clears `pnum`, Proportional Oldstyle /// clears `lnum`, and Default Figure and Tabular Oldstyle clear `pnum` and `lnum`. From 3bd1514acb7c30f70ffac216b3b9233d0d3787cf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 22:41:36 -0800 Subject: [PATCH 025/513] Type: offer stylistic sets only for an installed font, by their own names A font that is not installed offered the sets of the face drawn in its place; the menu now offers none. Set names the font supplies are shown as they are, without UI translation. --- crates/ui-egui/src/panels/opentype.rs | 32 +++++++++++++++++++++++---- docs/target-app-parity.md | 5 ++--- 2 files changed, 30 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/panels/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index ca5a7dfb0e..91b804365b 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -202,13 +202,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // The font, not the text, decides which numbered sets can be offered. Each set is an // independent feature, so the menu permits several at once. A font's own label wins over // the numbered fallback. See the public Stylistic Sets help page. - let sets = FontDb::global().style_face(&st).map(|face| face.stylistic_sets()).unwrap_or_default(); + let sets = offered_sets(&st); ui.add_enabled_ui(!sets.is_empty(), |ui| { ui.menu_button(tl!("Stylistic Sets"), |ui| { for set in &sets { let flag = Flag::Extra(EXTRA_FEATURES[usize::from(set.number - 1)]); let on = flag.get(&next); - if widgets::check(ui, &set_label(set), on, true) { + if widgets::check_name(ui, &set_label(set), on) { change = Some(Change::Toggle(flag, !on)); } } @@ -222,8 +222,19 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } -/// A Stylistic Sets menu entry: the font's own name for the set, or `Set 1` through `Set 20` in -/// the UI language. +/// The stylistic sets of the font `st` names. A font that is not available offers none, rather than +/// the sets of the face drawn in its place. +fn offered_sets(st: &vectorcraft_doc::CharStyle) -> Vec { + let db = FontDb::global(); + let (family, _) = db.canonical(&st.font_family, &st.font_style); + if !db.has_family(&family) { + return Vec::new(); + } + db.style_face(st).map(|face| face.stylistic_sets()).unwrap_or_default() +} + +/// A Stylistic Sets menu entry: the font's own name for the set, shown as the font gives it, or +/// `Set 1` through `Set 20` in the UI language. fn set_label(set: &StylisticSet) -> String { match &set.name { Some(name) => name.clone(), @@ -335,6 +346,19 @@ mod tests { assert_eq!(numbered_de, "Satz 3"); } + /// A font that is not available offers no sets, even though the face drawn in its place has + /// some. + #[test] + fn a_missing_font_offers_no_stylistic_sets() { + let fallback = vectorcraft_doc::CharStyle { font_family: vectorcraft_text::FALLBACK_FAMILY.into(), ..Default::default() }; + // Builds without the bundled fonts have no fallback face to draw in a missing font's place. + if FontDb::global().has_family(vectorcraft_text::FALLBACK_FAMILY) { + assert!(!offered_sets(&fallback).is_empty(), "the fallback face lists its sets"); + } + let missing = vectorcraft_doc::CharStyle { font_family: "No Such Family Zq".into(), ..fallback }; + assert!(offered_sets(&missing).is_empty()); + } + /// The Figure menu lists its five entries in order; Proportional Lining sets `pnum` and /// `lnum` and clears `tnum` and `onum`, Tabular Lining clears `pnum`, Proportional Oldstyle /// clears `lnum`, and Default Figure and Tabular Oldstyle clear `pnum` and `lnum`. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 02054ddd17..a792ebe271 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (OpenType Stylistic Sets menu added; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (OpenType Stylistic Sets menu added; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -144,8 +144,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (four generated libraries, User Defined, Other Library…, Save Brushes); remaining: Art brush Overlap, Pattern brush auto corners, pen pressure on macOS, tilt/bearing/rotation | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, 3D Classic, Turntable views, 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12) | -| Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout, optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied | -| Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout, optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests) | +| Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout, optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, spell check, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Symbols, blends, envelopes, Repeat, perspective | 5 | 87% | 30.7's Blend panel with ease in/out, on-canvas Direct Selection of parts inside dynamic symbol instances and their `.ai` round trip, more built-in symbol libraries, envelope Anti-Alias/Preserve Shape; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic symbols keep per-instance appearance linked, #4938) are done | 4–8 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; scores and hours unchanged | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), tab leaders, spell check, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | From b9d388187267d9f1fe1fbe103057d99c136240f0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 23:20:56 -0800 Subject: [PATCH 026/513] Docs: state the stop limit for Perceptual spot gradient shadings PDF export writes a Perceptual spot gradient as a Separation or DeviceN shading only when its expanded curve has at most 4,096 stops (MAX_INK_TINTS in crates/color/src/gradient.rs). Longer curves are written as images, with the process-color warning. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a792ebe271..92e4785728 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1369,7 +1369,7 @@ applies to fills). Tests: `color::gradient::tests` (perceptual midpoint, expansi `pdf::tests::dithered_perceptual_gradients_export_as_images_with_noise_on_the_fill` and the Gradient panel's `the_method_menu_makes_the_gradient_perceptual`. Scores and hours unchanged. -PDF export writes a Perceptual linear or radial gradient whose stops are tints of one spot color (and paper white) as a Separation shading in that ink instead of an image, so the ink keeps its plate ([swatches](https://helpx.adobe.com/illustrator/using/using-creating-swatches.html); [separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html)). Its tints follow the curve's stops, each the tint with the OKLab lightness of the color there (VectorCraft's own rule). A Perceptual gradient that mixes spot colors with each other or with CMYK or gray stops is written as a DeviceN shading of its inks: at each stop on the curve, the inks of the two stops on either side are mixed at the weight where the two colors mixed in display RGB have the OKLab lightness of the color there (VectorCraft's own rule). Dithered fills, freeform gradients and Perceptual gradients that mix a spot color with RGB or Lab stops are still images, and the export warns that their spot colors are written in process colors. Tests: `color::gradient::tests::ink_tints_follow_the_perceptual_curve` and `ink_mixes_follow_the_perceptual_curve`, `engine::tests::linked_stops::perceptual_spot_gradients_export_as_separation_shadings`, `perceptual_spot_gradients_mixed_with_other_inks_export_as_device_n_shadings` and `spot_gradients_drawn_as_images_warn`. +PDF export writes a Perceptual linear or radial gradient whose stops are tints of one spot color (and paper white) as a Separation shading in that ink instead of an image, so the ink keeps its plate ([swatches](https://helpx.adobe.com/illustrator/using/using-creating-swatches.html); [separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html)). Its tints follow the curve's stops, each the tint with the OKLab lightness of the color there (VectorCraft's own rule). A Perceptual gradient that mixes spot colors with each other or with CMYK or gray stops is written as a DeviceN shading of its inks: at each stop on the curve, the inks of the two stops on either side are mixed at the weight where the two colors mixed in display RGB have the OKLab lightness of the color there (VectorCraft's own rule). Dithered fills, freeform gradients, Perceptual gradients that mix a spot color with RGB or Lab stops, and Perceptual gradients whose curve has more than 4,096 stops once expanded (VectorCraft's own limit) are still images, and the export warns that their spot colors are written in process colors. Tests: `color::gradient::tests::ink_tints_follow_the_perceptual_curve` and `ink_mixes_follow_the_perceptual_curve`, `engine::tests::linked_stops::perceptual_spot_gradients_export_as_separation_shadings`, `perceptual_spot_gradients_mixed_with_other_inks_export_as_device_n_shadings` and `spot_gradients_drawn_as_images_warn`. In these Separation and DeviceN shadings, a white stop linked to a swatch that is not a spot color (a global White swatch, for example) is paper white, 0% of the ink, as an unlinked white stop is, so a gradient of one spot ink and such a stop stays a Separation shading; a stop linked to a white spot color stays a stop of that ink (VectorCraft's own rule). Test: `engine::tests::linked_stops::white_stops_linked_to_process_swatches_are_paper_in_spot_gradients`. From f15a16f2c192f6ff70af3f8a5ea222e0fe829e1f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 23:09:26 -0800 Subject: [PATCH 027/513] Render: placed-document bitmaps draw undecoded-image marks when the view does On screen, a placed document is drawn from a bitmap made in the background, and that bitmap was rendered with the default options. An image inside the placed file whose pixels cannot be decoded therefore drew nothing in the bitmap, even though the canvas marks such images with a crossed box. The bitmap now follows the frame's mark_undecoded_images setting, the bitmap cache keys on it, and a bitmap standing in for one still being made has the same setting. --- crates/render/src/placed_document.rs | 79 +++++++++++++++++----- crates/render/src/renderer.rs | 8 ++- crates/render/src/tests/placed_document.rs | 47 ++++++++++++- 3 files changed, 113 insertions(+), 21 deletions(-) diff --git a/crates/render/src/placed_document.rs b/crates/render/src/placed_document.rs index d9c0e3a810..9ebd347de0 100644 --- a/crates/render/src/placed_document.rs +++ b/crates/render/src/placed_document.rs @@ -6,7 +6,10 @@ //! //! On screen ([`RenderOptions::progressive_placed`]): a placed document can't be edited, so what //! it shows is cached as a bitmap per file and zoom step (a power of two, in device pixels per -//! point), shared by every object showing that file. A bitmap not made yet is made on a +//! point), shared by every object showing that file. Images inside it whose pixels can't be +//! decoded are drawn as crossed boxes in the bitmap when the frame marks them +//! ([`RenderOptions::mark_undecoded_images`]), and the bitmaps with and without marks are kept +//! apart. A bitmap not made yet is made on a //! background worker while the frame shows another step's bitmap, or a light placeholder; //! [`generation`] changes when one is ready, [`made_between`] says for which files, and [`busy`] //! says whether any is coming, so the screen can draw again where those files show @@ -45,8 +48,9 @@ const MAX_BYTES: usize = 4 * BUDGET; /// The smallest zoom step (device pixels per point). const MIN_STEP: f64 = 1.0 / 64.0; -/// A bitmap's identity: the file shown (its key) and the zoom step's bits. -type BitmapKey = (String, u64); +/// A bitmap's identity: the file shown (its key), the zoom step's bits, and whether images whose +/// pixels can't be decoded are marked ([`crate::RenderOptions::mark_undecoded_images`]). +type BitmapKey = (String, u64, bool); struct Bitmap { pm: Arc, @@ -130,10 +134,19 @@ pub(crate) fn scheduled(key: &str) -> usize { lock(&SCHEDULED).get(key).copied().unwrap_or(0) } -/// Mark the bitmap of file `key` at zoom `step` as not kept past [`MAX_BYTES`]. +/// Mark the bitmaps of file `key` at zoom `step`, with and without marks on undecoded images, as +/// not kept past [`MAX_BYTES`]. #[cfg(test)] pub(crate) fn mark_unkept(key: &str, step: f64) { - lock(&UNKEPT).insert((key.to_string(), step.to_bits())); + for mark in [false, true] { + lock(&UNKEPT).insert((key.to_string(), step.to_bits(), mark)); + } +} + +/// `object`'s file (`blob`) as a bitmap of `step` device pixels per point, made here and now. +#[cfg(test)] +pub(crate) fn bitmap(object: &PlacedDocument, blob: &ImageBlob, step: f64, mark_undecoded_images: bool) -> Option { + make(&mut Renderer::new(), object, blob, step, mark_undecoded_images) } /// The zoom step for `scale` device pixels per point: the power of two at or above it. @@ -150,11 +163,12 @@ impl Bitmaps { Some(b.pm.clone()) } - /// The bitmap of another step of the same file, the nearest to `step`. - fn nearest(&self, key: &str, step: f64) -> Option<(Arc, f64)> { + /// The bitmap of another step of the same file, with the same marks on undecoded images, the + /// nearest to `step`. + fn nearest(&self, key: &str, step: f64, mark: bool) -> Option<(Arc, f64)> { self.map .iter() - .filter(|((k, _), _)| k == key) + .filter(|((k, _, m), _)| k == key && *m == mark) .min_by(|a, b| (a.1.step / step).log2().abs().total_cmp(&(b.1.step / step).log2().abs())) .map(|(_, b)| (b.pm.clone(), b.step)) } @@ -245,14 +259,30 @@ fn depth() -> usize { /// Render `art` of a placed document's file (`doc`, its resources) into `w`×`h` transparent /// pixels through `view`, the placed documents inside it one level deeper. pub fn render_inside(r: &mut Renderer, doc: &vectorcraft_doc::Document, art: &Arc, w: u16, h: u16, view: Affine) -> Option { + render_inside_marked(r, doc, art, w, h, view, false) +} + +/// [`render_inside`], drawing images whose pixels can't be decoded as crossed boxes when +/// `mark_undecoded_images` is set ([`crate::RenderOptions::mark_undecoded_images`]). +fn render_inside_marked( + r: &mut Renderer, + doc: &vectorcraft_doc::Document, + art: &Arc, + w: u16, + h: u16, + view: Affine, + mark_undecoded_images: bool, +) -> Option { let _inside = Inside::enter(); - r.render_node(doc, art, w, h, view) + let opts = crate::RenderOptions { mark_undecoded_images, ..Default::default() }; + r.render_node_with(doc, art, w, h, view, &opts) } /// `object`'s file (`blob`) as a bitmap of `step` device pixels per point of its box: from its /// preview when that is all there is and is fine enough, else from the file (read again when -/// needed; the preview when it can't be). -fn make(r: &mut Renderer, object: &PlacedDocument, blob: &ImageBlob, step: f64) -> Option { +/// needed; the preview when it can't be). Images whose pixels can't be decoded are drawn as +/// crossed boxes when `mark_undecoded_images` is set. +fn make(r: &mut Renderer, object: &PlacedDocument, blob: &ImageBlob, step: f64, mark_undecoded_images: bool) -> Option { let (w, h) = (pixels(object.width * step), pixels(object.height * step)); let preview = if blob.is_proxy() { Some(blob.bytes.clone()) } else { blob.proxy.clone() }; let full = match blob.is_proxy() { @@ -265,7 +295,7 @@ fn make(r: &mut Renderer, object: &PlacedDocument, blob: &ImageBlob, step: f64) let f = e.frame; let (sx, sy) = (w as f64 / f.width(), h as f64 / f.height()); let view = Affine::scale_non_uniform(sx, sy) * Affine::translate((-f.x0, -f.y0)); - let img = render_inside(r, &e.doc, &e.art, w, h, view)?; + let img = render_inside_marked(r, &e.doc, &e.art, w, h, view, mark_undecoded_images)?; let data = img.pixels.as_chunks::<4>().0.iter().map(|&[r, g, b, a]| vello_cpu::color::PremulRgba8 { r, g, b, a }).collect(); Some(Pixmap::from_parts(data, w, h)) } @@ -281,7 +311,7 @@ fn pixels(v: f64) -> u16 { fn run(r: &mut Renderer, mut job: Job) { let scope = job.scope.take(); let mut body = || { - match make(r, &job.object, &job.blob, job.step) { + match make(r, &job.object, &job.blob, job.step, job.key.2) { Some(pm) => { if !lock(&BITMAPS).insert(job.key.clone(), pm, job.step, job.keep, (BUDGET, MAX_BYTES)) { lock(&UNKEPT).insert(job.key.clone()); @@ -413,7 +443,7 @@ impl Renderer { return false; } let Some(blob) = f.doc.images.get(&p.key).cloned() else { return true }; - let key = (p.key.clone(), step.to_bits()); + let key = (p.key.clone(), step.to_bits(), f.opts.mark_undecoded_images); // Not kept past [`MAX_BYTES`]: drawn exactly. if lock(&UNKEPT).contains(&key) { return false; @@ -423,7 +453,7 @@ impl Renderer { // The clock when this frame first drew a placed document's bitmap. let keep = *self.placed_frame.get_or_insert(b.clock); let found = b.get(&key); - let nearest = if found.is_none() { b.nearest(&p.key, step) } else { None }; + let nearest = if found.is_none() { b.nearest(&p.key, step, f.opts.mark_undecoded_images) } else { None }; (found, nearest, keep) }; let shown = match found { @@ -434,7 +464,7 @@ impl Renderer { schedule(Job { key, object: p.clone(), blob, step, keep, scope: SCOPE_CAPTURE.get().map(|capture| capture()) }); // Made here and now (no threads) or meanwhile another step's. let mut b = lock(&BITMAPS); - b.get(&(p.key.clone(), step.to_bits())).or(nearest.map(|n| n.0)) + b.get(&(p.key.clone(), step.to_bits(), f.opts.mark_undecoded_images)).or(nearest.map(|n| n.0)) } }; let rect = Rect::new(0.0, 0.0, p.width, p.height); @@ -480,7 +510,7 @@ mod tests { let mut b = Bitmaps::default(); // 400 bytes each: a budget of 1,000 bytes and at most 2,000. let limits = (1000, 2000); - let key = |name: &str| (name.to_string(), 1f64.to_bits()); + let key = |name: &str| (name.to_string(), 1f64.to_bits(), false); for name in ["a", "b", "c"] { assert!(b.insert(key(name), Pixmap::new(10, 10), 1.0, 0, limits)); } @@ -489,7 +519,7 @@ mod tests { let frame = b.clock; assert!(b.get(&key("a")).is_some()); assert!(b.insert(key("d"), Pixmap::new(10, 10), 1.0, frame, limits)); - let mut kept: Vec<&str> = b.map.keys().map(|(name, _)| name.as_str()).collect(); + let mut kept: Vec<&str> = b.map.keys().map(|(name, _, _)| name.as_str()).collect(); kept.sort_unstable(); assert_eq!((kept, b.bytes), (vec!["a", "d"], 800), "b and c, not drawn since, are dropped"); for name in ["e", "f", "g"] { @@ -499,4 +529,17 @@ mod tests { assert!(!b.insert(key("h"), Pixmap::new(10, 10), 1.0, frame, limits), "past the most: not kept"); assert!(!b.map.contains_key(&key("h")) && b.bytes == 2000); } + + /// While a bitmap is made, another step's bitmap stands in only when it has the same marks on + /// undecoded images. + #[test] + fn a_stand_in_bitmap_has_the_same_marks() { + let mut b = Bitmaps::default(); + let limits = (BUDGET, MAX_BYTES); + assert!(b.insert(("a".into(), 1f64.to_bits(), false), Pixmap::new(10, 10), 1.0, 0, limits)); + assert!(b.insert(("a".into(), 4f64.to_bits(), true), Pixmap::new(40, 40), 4.0, 0, limits)); + assert_eq!(b.nearest("a", 2.0, false).map(|n| n.1), Some(1.0)); + assert_eq!(b.nearest("a", 2.0, true).map(|n| n.1), Some(4.0)); + assert!(b.nearest("b", 2.0, false).is_none()); + } } diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 4d619e0454..db5ab2d6bc 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -307,15 +307,19 @@ impl Renderer { /// Render node `n` of `doc` (its resources) into `w`×`h` transparent pixels through `view`. pub fn render_node(&mut self, doc: &Document, n: &Arc, w: u16, h: u16, view: Affine) -> Option { + self.render_node_with(doc, n, w, h, view, &RenderOptions::default()) + } + + /// [`Self::render_node`] with `opts` (e.g. [`RenderOptions::mark_undecoded_images`]). + pub fn render_node_with(&mut self, doc: &Document, n: &Arc, w: u16, h: u16, view: Affine, opts: &RenderOptions) -> Option { self.check_plugins(); self.check_symbols(doc); let inv = view.inverse(); let visible = inv.transform_rect_bbox(Rect::new(0.0, 0.0, w as f64, h as f64)); let px = 1.0 / view.determinant().abs().sqrt().max(1e-12); let mut ctx = single_threaded_context(w, h); - let opts = RenderOptions::default(); let symbols = doc.symbol_boxes().quick(); - let frame = Frame { mt: false, doc, symbols: &symbols, view, visible, px, opts: &opts, ink: Ink::Display, plates: None }; + let frame = Frame { mt: false, doc, symbols: &symbols, view, visible, px, opts, ink: Ink::Display, plates: None }; self.begin_frame(); (self.knockout, self.nested, self.backdrop, self.picture) = (false, 0, None, None); self.clip_paths.clear(); diff --git a/crates/render/src/tests/placed_document.rs b/crates/render/src/tests/placed_document.rs index 400fc23e81..c3c00a4cf0 100644 --- a/crates/render/src/tests/placed_document.rs +++ b/crates/render/src/tests/placed_document.rs @@ -8,7 +8,9 @@ use vectorcraft_geom::shapes; use crate::*; /// Every file reads as a 40×20 artboard filled blue; a file whose bytes start with `loop` also -/// places itself (the same key) in its middle, and one whose bytes start with `bad` can't be read. +/// places itself (the same key) in its middle, one whose bytes start with `cut` also shows an +/// image whose pixels can't be decoded over its left half, and one whose bytes start with `bad` +/// can't be read. fn blue_page(p: &PlacedDocument, bytes: &[u8]) -> Option<(Document, Node, Rect)> { if bytes.starts_with(b"bad") { return None; @@ -17,6 +19,19 @@ fn blue_page(p: &PlacedDocument, bytes: &[u8]) -> Option<(Document, Node, Rect)> d.layers.clear(); let blue = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0); let mut children = vec![Arc::new(Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 40.0, 20.0)), blue))]; + if bytes.starts_with(b"cut") { + d.images.insert("cut-image".into(), ImageBlob::new("image/png", b"not a PNG: placed document".to_vec())); + let im = vectorcraft_doc::ImageObject { + key: "cut-image".into(), + width: 20, + height: 20, + xf: Affine::IDENTITY, + link: None, + placement: Default::default(), + pixels: None, + }; + children.push(Arc::new(Node::new(NodeId(3), NodeKind::Image(Box::new(im))))); + } if bytes.starts_with(b"loop") { d.images.insert(p.key.clone(), ImageBlob::new("application/json", bytes.to_vec())); let me = PlacedDocument { xf: Affine::translate((10.0, 5.0)) * Affine::scale(0.5), ..p.clone() }; @@ -254,6 +269,36 @@ fn a_bitmap_that_cant_be_made_is_not_asked_for_again() { assert!(shown != [255, 255, 255] && shown != [0, 0, 255], "the placeholder: {shown:?}"); } +/// A bitmap made for a frame that marks images whose pixels can't be decoded shows such an image +/// in the file as a crossed box; one made for a frame that does not shows the art under it. +#[test] +fn a_bitmap_marks_undecoded_images_when_the_frame_does() { + let d = doc_with("cut-1", b"cut"); + let Some(NodeKind::PlacedDocument(p)) = d.node(NodeId(50)).map(|n| &n.kind) else { panic!("a placed document") }; + let Some(blob) = d.images.get("cut-1") else { panic!("the file's bytes") }; + for mark in [false, true] { + // 40 × 20 pixels at one pixel a point; the image covers x 0 to 20. + let Some(pm) = placed_document::bitmap(p, blob, 1.0, mark) else { panic!("a bitmap") }; + let pixel = |x: usize, y: usize| pm.data_as_u8_slice()[(y * 40 + x) * 4..][..4].to_vec(); + assert_eq!(pixel(30, 10), [0, 0, 255, 255], "mark {mark}: the art beside the image"); + assert_eq!(pixel(5, 10) != [0, 0, 255, 255], mark, "mark {mark}: the crossed box over the art: {:?}", pixel(5, 10)); + } +} + +/// Frames with and without marks on undecoded images ask for bitmaps of their own, so a bitmap +/// made for one is not shown in the other. The file can't be read, so no bitmap is made after +/// the test ends. +#[test] +fn bitmaps_with_and_without_undecoded_marks_are_asked_for_apart() { + let _serial = serial(); + let d = doc_with("marks-1", b"bad"); + for mark in [false, true] { + let opts = RenderOptions { progressive_placed: true, mark_undecoded_images: mark, ..Default::default() }; + Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &opts); + } + assert_eq!(placed_document::scheduled("marks-1"), 2, "one for each"); +} + /// Once bitmaps are ready, drawing again where [`placed_area`] says gives what drawing the whole /// frame again gives. The area of a file covers every object showing it (a group's member and /// an object with a drop shadow too) and no object showing another file; art of a brush or a From e5834f7686c75a8202822fec13a6b16c69bc4c00 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 20:38:34 -0800 Subject: [PATCH 028/513] .ai import: the layers are compared with every page of a multi-artboard file A .ai file whose PDF part has a page for each artboard had its layers compared with the first page only. Art that the layers drew on a later artboard and its page didn't, or that a later page drew and the layers didn't, opened from the layers with no warning, and a text object that a later page doesn't draw stayed. When the PDF part has a page for every artboard, each page is now compared with the layers on its artboard, and the comparison fails when any page differs by more than it allows. Text objects that a later page doesn't draw are weighed there and left out, unless their layer doesn't print. Art that differs on a later page is handled as on the first page: such files now open from their PDF part with the usual warning, where they opened from their layers before. A PDF part with pages for some of the artboards, or with its pages cropped to the art, is still compared on its first page only. Pages are compared until their comparison drawings take 8,388,608 pixels (about 67 letter-size pages, or 4 when the PDF part is only images), and at most 128 pages are compared. The type share in the import's note is now that of the page whose type differs most. The layers are drawn once for the pages of the same size and cut into each page's part. Each page moves by less than half a pixel to start on a whole pixel, and the column or row the move takes past its artboard isn't compared. Each page's drawing and result are kept until the layers change, for the last two documents weighed. Taking a text object out draws again only the pages within reach of it (every page when type wraps). An artboard, or the page of an EPS's editing data, whose sides are within half a point of its page's is drawn on an area of the page's size, so both drawings have the same number of pixels. Before, such a file could open without its layers when the half point changed the rounded size of its drawing, even when its layers matched the page. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/eps/src/import/native.rs | 14 +- crates/eps/src/import/native/build.rs | 170 ++++- crates/eps/src/import/native/compare.rs | 904 ++++++++++++++++++++---- crates/eps/src/import/tests_native.rs | 191 +++++ docs/mcp.md | 11 +- docs/target-app-parity.md | 1 + 6 files changed, 1094 insertions(+), 197 deletions(-) diff --git a/crates/eps/src/import/native.rs b/crates/eps/src/import/native.rs index ce7eac542c..916451a380 100644 --- a/crates/eps/src/import/native.rs +++ b/crates/eps/src/import/native.rs @@ -91,7 +91,7 @@ mod tests { ring(&mut layers, Some(MADE), red, 6.0, square); ring(&mut layers, Some(MADE), red, 2.0, Rect::new(40.0, 40.0, 60.0, 60.0)); let rect = page.artboards[0].rect; - let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)] }; + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)], more: vec![] }; let mut view = PageView::new(&frame); assert_eq!(prune_unseen(&frame, &mut view, &mut layers, false), 1, "only the ring the page doesn't draw"); let widths: Vec = layers.layers[0].children().unwrap().iter().filter_map(|n| n.appearance.stroke().map(|s| s.width)).collect(); @@ -193,15 +193,15 @@ mod tests { let a = comparison_render(&mut renderer, &page, rect, 0.4, 1); let b = comparison_render(&mut vectorcraft_render::Renderer::new(), &vector, rect, 0.4, 1); assert!(compared(&a, &b, &[], &[]).solid > MAX_SOLID_DIFFERENCE, "the old point sampling falsely refused this page"); - let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)] }; + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)], more: vec![] }; let mut view = PageView::new(&frame); assert!(compare(&frame, &mut view, &vector, false).is_ok()); assert!(compare(&frame, &mut view, &Document::new(1000.0, 500.0), false).is_err(), "missing artwork remains an error"); let shifted = Rect::new(0.0, 0.0, 500.0, 500.0); - assert!(view.difference(&vector, shifted, false).any > MAX_DIFFERENCE, "wrong framing remains an error"); + assert!(view.difference_on_every_page(&vector, shifted, false).any > MAX_DIFFERENCE, "wrong framing remains an error"); } - /// The boxes `solid_regions` gives for a page of images are in the page's points: the + /// The boxes `solid_regions_on_every_page` gives for a page of images are in the page's points: the /// comparison is drawn at a multiple of the scale and resized, and the two sizes round /// differently on the short side, so a box at the far edge does not drift out of the object /// that makes it. @@ -218,7 +218,7 @@ mod tests { } } - /// The boxes `solid_regions` gives for a `width` × `height` page that is one image of a black + /// The boxes `solid_regions_on_every_page` gives for a `width` × `height` page that is one image of a black /// `object`, compared with layers that hold nothing. fn raster_page_regions(object: Rect, width: f64, height: f64) -> Vec { use vectorcraft_color::{Color, Paint}; @@ -256,9 +256,9 @@ mod tests { ); page.insert(Some(page.layers[0].id), usize::MAX, image).unwrap(); assert_eq!(comparison_samples(&page), 4); - let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)] }; + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)], more: vec![] }; let mut view = PageView::new(&frame); - let (_, regions) = view.solid_regions(&Document::new(width, height), rect, false).unwrap(); + let (_, regions) = view.solid_regions_on_every_page(&Document::new(width, height), false).unwrap(); assert!(!regions.is_empty()); regions } diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index e94dccfb5f..4226ccaacf 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -1,4 +1,6 @@ -use super::compare::{MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, PageView, compare, difference}; +use super::compare::{ + MAX_DIFFERENCE, MAX_PAGES_COMPARED, MAX_PIXELS_COMPARED, MAX_SOLID_DIFFERENCE, PageView, compare, comparison_samples, difference, pixels_compared, +}; use super::plan::{made_only, make_slots, plan, readable_all}; use super::slots::{ ART_LEFT_OUT, Content, DREW_DIFFERENTLY, MAX_PAIRS, MAX_SLOTS, MAX_TEXT, OUTLINE_REACH, SlotInfo, TEXT_LEFT_OUT, TYPE_LEFT_OUT, collect_slots, @@ -32,6 +34,10 @@ pub(super) struct Frame<'a> { pub(super) whole: bool, /// The PDF page areas and their moves into the editing document. pub(super) pages: Vec<(Rect, Affine)>, + /// The pages after the first that show artboards of the layers' document, each with that + /// artboard (as many as [`MAX_PIXELS_COMPARED`] allows): the layers are compared with them as + /// with the first. + pub(super) more: Vec<(Rect, Rect)>, } /// The document of the editing copy `data`, with the text (and strokes round it) of `visible`, the @@ -211,6 +217,9 @@ pub(super) fn build_from( Arc::make_mut(n).transform(shift, PAGE_MOVE); } } + // Pages cropped to the art are copies of the first, and a PDF saved with some of the + // artboards can hold any of them. + let more = more_pages(boards.filter(|b| !cropped && b.len() == doc.artboards.len()), &pages, comparison_samples(visible)); // An EPS saved as its artboard has the art outside it left out of its page. let artboard_page = artboard.is_some_and(|a| [a.x0 - art_box.x0, a.y0 - art_box.y0, a.x1 - art_box.x1, a.y1 - art_box.y1].iter().all(|d| d.abs() <= 1.0)); @@ -224,7 +233,7 @@ pub(super) fn build_from( } drop_guides_off_boards(&mut doc); } - frame = Some(Frame { page: visible, page_rect, rect, whole, pages: page_moves }); + frame = Some(Frame { page: visible, page_rect, rect, whole, pages: page_moves, more }); } let mut infos = vec![]; collect_slots(&doc.layers, true, &mut infos); @@ -326,7 +335,8 @@ pub(super) fn build_from( Ok(note) => { let closer = other.and_then(|mut other| { let unseen = prune_unseen(&frame, &mut view, &mut other, reflow); - let closer = view.difference(&other, frame.rect, reflow).any < view.difference(&doc, frame.rect, reflow).any; + let closer = view.difference_on_every_page(&other, frame.rect, reflow).any + < view.difference_on_every_page(&doc, frame.rect, reflow).any; closer.then(|| compare(&frame, &mut view, &other, reflow).ok()).flatten().map(|note| (other, unseen, note)) }); match closer { @@ -801,7 +811,11 @@ fn closer_first( reflow: bool, ) -> Vec<(Document, usize)> { match other { - Some(other) if view.difference(&other.0, frame.rect, reflow).any < view.difference(&doc.0, frame.rect, reflow).any => vec![other, doc], + Some(other) + if view.difference_on_every_page(&other.0, frame.rect, reflow).any < view.difference_on_every_page(&doc.0, frame.rect, reflow).any => + { + vec![other, doc] + } Some(other) => vec![doc, other], None => vec![doc], } @@ -847,13 +861,14 @@ fn keep_differing( // Where only spread edges or type differ, or only the art around the page, no object is // replaced. - let (diff, regions) = view.solid_regions(doc, frame.rect, reflow)?; + let (diff, regions) = view.solid_regions_on_every_page(doc, reflow)?; if diff.solid <= MAX_SOLID_DIFFERENCE { return None; } let mut objects = vec![]; top_level(&doc.layers, "", &mut objects); - objects.retain(|(_, _, b)| !b.intersect(frame.rect).is_zero_area()); + let pages = view.regions(frame.rect); + objects.retain(|(_, _, b)| pages.iter().any(|page| !b.intersect(*page).is_zero_area())); if regions.len().saturating_mul(objects.len()) > MAX_PATCH_PAIRS { return None; } @@ -1200,6 +1215,32 @@ fn shown_artboard(doc: &Document, visible: &Document, page: Page, page_rect: Rec best.map_or(0, |(i, _)| i) } +/// The pages after the first, each with the artboard it shows ([`page_boards`]), as [`Frame::more`] +/// holds them: none when the pages don't show the artboards. They stop before the page that would +/// take the pixels the comparisons draw (`samples`, [`comparison_samples`]), the first page's +/// included, past [`MAX_PIXELS_COMPARED`], and after [`MAX_PAGES_COMPARED`] pages. +fn more_pages(boards: Option<&[vectorcraft_doc::Artboard]>, pages: &[Rect], samples: u32) -> Vec<(Rect, Rect)> { + let Some(boards) = boards else { return vec![] }; + let mut left = MAX_PIXELS_COMPARED; + pages + .iter() + .zip(boards) + .map_while(|(page, board)| { + left = left.checked_sub(pixels_compared(*page, samples))?; + Some((*page, board.rect)) + }) + .take(MAX_PAGES_COMPARED) + .skip(1) + .collect() +} + +/// The artboards (or other areas) of `pages` that `bounds` lies on, with `margin` (points) round it: +/// the pages whose drawings taking it out can change. +fn pages_touched(bounds: Rect, pages: &[Rect], margin: f64) -> Vec { + let b = bounds.inflate(margin, margin); + pages.iter().enumerate().filter(|(_, p)| !b.intersect(**p).is_zero_area()).map(|(i, _)| i).collect() +} + /// The artboards of the layers' document (`boards`) that the pages show, one a page from the /// first page's (`first`), when they are the pages' sizes: every artboard, or those of a PDF saved /// with some of them (`first` after the first artboard). @@ -1310,35 +1351,51 @@ fn take_out(nodes: &mut Vec>, id: NodeId, hide: bool) -> bool { nodes.iter_mut().any(|n| !matches!(n.kind, NodeKind::Compound { .. }) && Arc::make_mut(n).children_mut().is_some_and(|c| take_out(c, id, hide))) } -/// The text objects made from the file's text document that show and print on the page's area, -/// where the page has no type to match them, and that the layers look no worse without, are not -/// drawn by the app that wrote the file (which paints every shown text object; it keeps the type -/// of what was turned to outlines): they are taken out. How many. `reflow`: the type is all laid -/// out again from the text document (see [`compare`]). +/// The text objects made from the file's text document that show and print on a page's area (the +/// frame's first page or another one, [`Frame::more`]), where the page has no type to match them, and +/// that the layers look no worse without on every page they lie on, are not drawn by the app that +/// wrote the file (which paints every shown text object; it keeps the type of what was turned to +/// outlines): they are taken out. How many. `reflow`: the type is all laid out again from the text +/// document (see [`compare`]). pub(super) fn prune_unseen(frame: &Frame<'_>, view: &mut PageView, doc: &mut Document, reflow: bool) -> usize { let mut found = vec![]; unmark(&mut doc.layers, true, true, &mut found); - let rect = frame.rect; if found.is_empty() || found.len() > MAX_WEIGHED { return 0; } - let with = view.difference(doc, rect, reflow).weighed(reflow); - // Taking a text object out changes only what is drawn in its box. When the art would still - // differ from the page by more than `compare` allows with every candidate gone, the layers - // aren't used whatever is pruned: don't draw them again for each one (#758). + let pages = view.regions(frame.rect); + // Taking a text object out changes only what is drawn in its box. When the art on a page would + // still differ from it by more than `compare` allows with every candidate gone, pruning doesn't + // make that page pass: the objects on it aren't drawn again one by one (#758). let margin = OUTLINE_REACH + 1.0; - let boxes: f64 = found.iter().filter_map(|(_, b)| *b).map(|b| b.inflate(margin, margin).intersect(rect).area().max(0.0)).sum(); - if with - boxes / rect.area().max(1e-9) > MAX_DIFFERENCE { - return 0; - } + let hopeless: Vec = view + .differences(doc, frame.rect, reflow) + .iter() + .zip(&pages) + .map(|(with, rect)| { + let boxes: f64 = found.iter().filter_map(|(_, b)| *b).map(|b| b.inflate(margin, margin).intersect(*rect).area().max(0.0)).sum(); + with.weighed(reflow) - boxes / rect.area().max(1e-9) > MAX_DIFFERENCE + }) + .collect(); // Weighed by colour, not only lightness: a text object's red stroke over a dark red one is no - // less there for being about as light (#1102). - let mut with = view.colour_difference(doc, rect); + // less there for being about as light (#1102). The view keeps each page's drawing and share: a + // removal has only the pages in `on` drawn again. let mut removed = 0; for (id, bounds) in found { // A removal before it can have let its area type flow differently. let bounds = if removed > 0 { doc.node(id).and_then(|n| n.visual_bounds()) } else { bounds }; - if bounds.is_none_or(|b| b.intersect(rect).is_zero_area()) { + let Some(b) = bounds else { continue }; + let mut lies = pages_touched(b, &pages, 0.0); + if lies.is_empty() { + continue; + } + // The pages its strokes and effects can reach past its box are drawn again too. + let mut on = pages_touched(b, &pages, margin); + // Area type that flows around it can reach other pages: they are all weighed. + if has_wraps(doc) { + (lies, on) = ((0..pages.len()).collect(), (0..pages.len()).collect()); + } + if lies.iter().any(|i| hopeless.get(*i).copied().unwrap_or(true)) { continue; } let mut without = doc.clone(); @@ -1347,11 +1404,12 @@ pub(super) fn prune_unseen(frame: &Frame<'_>, view: &mut PageView, doc: &mut Doc } // Area type that wrapped around the text object flows without it. relayout_wrapped(&mut without); - let d = view.colour_difference(&without, rect); - if d - with <= UNSEEN_MARGIN { + let shares = view.weigh_without(doc, &without, &on); + if shares.len() == on.len() && shares.iter().all(|(_, before, after)| after - before <= UNSEEN_MARGIN) { take_out(&mut doc.layers, id, false); relayout_wrapped(doc); - with = d; + // Only the pages in `on` can draw differently (every page when type wraps). + view.adopt(doc); removed += 1; } } @@ -1364,6 +1422,42 @@ mod candidate_tests { use vectorcraft_doc::{ImageBlob, ImageObject}; + /// The pages compared stop where their drawings would take more than the pixels allowed. + #[test] + fn the_pages_compared_stop_at_the_pixel_bound() { + let pages: Vec = (0..1000).map(|i| Rect::new(f64::from(i) * 700.0, 0.0, f64::from(i) * 700.0 + 612.0, 792.0)).collect(); + let doc = Document::new(612.0, 792.0); + let boards: Vec = pages + .iter() + .map(|page| { + let mut board = doc.artboards[0].clone(); + board.rect = *page; + board + }) + .collect(); + let more = more_pages(Some(&boards), &pages, 1); + let each = pixels_compared(pages[0], 1); + assert_eq!(more.len() + 1, (MAX_PIXELS_COMPARED / each) as usize); + assert!(more.len() >= 64, "{}", more.len()); + assert_eq!(more_pages(Some(&boards[..3]), &pages[..3], 1).len(), 2); + // Pages drawn with 4 × 4 samples a pixel take 16 times the pixels. + assert_eq!(more_pages(Some(&boards), &pages, 4).len() + 1, (MAX_PIXELS_COMPARED / (each * 16)) as usize); + // Tiny pages stop at the page count. + let tiny: Vec = (0..1000).map(|i| Rect::new(f64::from(i) * 2.0, 0.0, f64::from(i) * 2.0 + 1.0, 1.0)).collect(); + let tiny_boards: Vec = + boards.iter().zip(&tiny).map(|(b, r)| vectorcraft_doc::Artboard { rect: *r, ..b.clone() }).collect(); + assert_eq!(more_pages(Some(&tiny_boards), &tiny, 1).len() + 1, MAX_PAGES_COMPARED); + } + + /// The pages a box touches with a margin round it include those it only comes near. + #[test] + fn the_pages_within_reach_of_a_box_count_as_touched() { + let pages = [Rect::new(0.0, 0.0, 100.0, 100.0), Rect::new(110.0, 0.0, 210.0, 100.0)]; + let near_the_second = Rect::new(60.0, 40.0, 106.0, 60.0); + assert_eq!(pages_touched(near_the_second, &pages, 0.0), vec![0]); + assert_eq!(pages_touched(near_the_second, &pages, OUTLINE_REACH + 1.0), vec![0, 1]); + } + /// Layers read in the units of a page scaled up to points take their wrap offsets with their art, /// within ±1000 points. #[test] @@ -1504,7 +1598,7 @@ mod candidate_tests { page.insert(Some(page.layers[0].id), 0, image).unwrap(); let rect = Rect::new(0.0, 0.0, 100.0, 100.0); - let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)] }; + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)], more: vec![] }; let kinds = replace_unread( &mut doc, &frame, @@ -1546,8 +1640,14 @@ mod candidate_tests { page.insert(Some(page.layers[0].id), page.layers[0].children().unwrap().len(), art).unwrap(); } let (first, second) = (Rect::new(0.0, 0.0, 100.0, 100.0), Rect::new(100.0, 0.0, 200.0, 100.0)); - let frame = - Frame { page: &page, page_rect: first, rect: first, whole: false, pages: vec![(first, Affine::IDENTITY), (second, Affine::IDENTITY)] }; + let frame = Frame { + page: &page, + page_rect: first, + rect: first, + whole: false, + pages: vec![(first, Affine::IDENTITY), (second, Affine::IDENTITY)], + more: vec![], + }; let result = replace_unread(&mut doc, &frame, &[(id, vec!["placed files".into()])], &[], &BTreeSet::new(), &mut BTreeSet::new()); assert_eq!(result.unwrap_err(), "an unread object lies on more than one artboard"); } @@ -1572,7 +1672,7 @@ mod candidate_tests { ); page.insert(Some(page.layers[0].id), 0, art).unwrap(); let rect = Rect::new(0.0, 0.0, 100.0, 100.0); - let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)] }; + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)], more: vec![] }; let result = replace_unread(&mut doc, &frame, &[(id, vec!["placed files".into()])], &[], &BTreeSet::new(), &mut BTreeSet::new()); assert_eq!(result.unwrap_err(), "an unread object lies on an artboard that has no page"); @@ -1603,7 +1703,7 @@ mod candidate_tests { ); page.insert(Some(page.layers[0].id), 0, art).unwrap(); let rect = Rect::new(0.0, 0.0, 100.0, 100.0); - let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)] }; + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)], more: vec![] }; let result = replace_unread( &mut doc, &frame, @@ -1641,7 +1741,7 @@ mod candidate_tests { page.insert(Some(page.layers[0].id), page.layers[0].children().unwrap().len(), art).unwrap(); } let rect = Rect::new(0.0, 0.0, 100.0, 100.0); - let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)] }; + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)], more: vec![] }; let kinds = replace_unread( &mut doc, &frame, @@ -1682,7 +1782,7 @@ mod candidate_tests { page.insert(Some(page.layers[0].id), page.layers[0].children().unwrap().len(), art).unwrap(); } let rect = Rect::new(0.0, 0.0, 100.0, 100.0); - let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)] }; + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)], more: vec![] }; let result = replace_unread(&mut doc, &frame, &[(id, vec!["placed files".into()])], &[], &BTreeSet::new(), &mut BTreeSet::new()); assert_eq!(result.unwrap_err(), "an unread object's appearance is not identifiable in the page art"); } @@ -1712,7 +1812,7 @@ mod candidate_tests { page.insert(Some(page.layers[0].id), page.layers[0].children().unwrap().len(), art).unwrap(); } let rect = Rect::new(0.0, 0.0, 100.0, 100.0); - let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)] }; + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)], more: vec![] }; let unread = [(first, vec!["placed files".into()]), (second, vec!["placed files".into()])]; let mut one_box_doc = doc.clone(); let kinds = replace_unread(&mut doc, &frame, &unread, &[(second, Rect::new(50.0, 50.0, 60.0, 60.0))], &BTreeSet::new(), &mut BTreeSet::new()) @@ -1756,7 +1856,7 @@ mod candidate_tests { page.insert(Some(page.layers[0].id), page.layers[0].children().unwrap().len(), art).unwrap(); } let rect = Rect::new(0.0, 0.0, 100.0, 100.0); - let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)] }; + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)], more: vec![] }; let unread = [(id, vec!["placed files".into()])]; let mut shown: Vec>> = nodes.iter().map(|n| vec![Arc::clone(n)]).collect(); let taken = take_unread_type(&doc, Some(&frame), &unread, &[(id, Rect::new(50.0, 50.0, 60.0, 60.0))], &mut shown); diff --git a/crates/eps/src/import/native/compare.rs b/crates/eps/src/import/native/compare.rs index c20ed8383d..044dbd2401 100644 --- a/crates/eps/src/import/native/compare.rs +++ b/crates/eps/src/import/native/compare.rs @@ -48,6 +48,9 @@ const WHITE: u32 = 8; /// Do two pixels look different: in lightness, or one inked (as a light yellow is) where the other /// is white? pub(in crate::import) fn differ(p: &[u8; 4], q: &[u8; 4]) -> bool { + if p == q { + return false; + } let (p, q) = (on_white(p), on_white(q)); let (a, b) = (ink(p), ink(q)); lightness(p).abs_diff(lightness(q)) > SAME_PIXEL || (a.min(b) <= WHITE && a.abs_diff(b) > SAME_PIXEL) @@ -60,6 +63,9 @@ const SAME_COLOUR: u32 = 64; /// Are two pixels different colours ([`differ`] also takes a red and a dark red of about the same /// lightness to be alike)? pub(in crate::import) fn differ_in_colour(p: &[u8; 4], q: &[u8; 4]) -> bool { + if p == q { + return false; + } let (p, q) = (on_white(p), on_white(q)); p.iter().zip(q).any(|(a, b)| a.abs_diff(b) > SAME_COLOUR) } @@ -73,6 +79,9 @@ pub(super) struct Difference { pub(super) any: f64, art: f64, pub(super) solid: f64, + /// The share that differs in the type's areas (`any` less `art`), kept on its own when the + /// shares of several regions are taken together ([`Self::max`]). + typed: f64, } impl Difference { @@ -81,6 +90,15 @@ impl Difference { pub(super) fn weighed(&self, reflow: bool) -> f64 { if reflow { self.art } else { self.any } } + + /// The larger of each share of `self` and `other`: how two regions differ, the one that differs + /// most for each. + fn max(self, other: Self) -> Self { + Self { any: self.any.max(other.any), art: self.art.max(other.art), solid: self.solid.max(other.solid), typed: self.typed.max(other.typed) } + } + + /// Two drawings that can't be compared: every pixel differs. + const ALL: Self = Self { any: 1.0, art: 1.0, solid: 1.0, typed: 0.0 }; } /// The scale the comparisons draw a region at: about 400 pixels along its longer side. @@ -126,146 +144,506 @@ pub(super) fn comparison_render( vectorcraft_render::Rendered { width, height, pixels } } -/// The page drawn once, to weigh the layers' art against it: [`Self::difference`] draws the layers -/// with a renderer of their own, which keeps their decoded images between draws (the page's images -/// can share their keys and not their pixels, so the two don't share one). -pub(super) struct PageView { - page: vectorcraft_render::Rendered, +/// The most pixels the pages of a frame are drawn in for a comparison, all of them together +/// ([`pixels_compared`]): the pages after those that reach it aren't compared. It holds about 67 +/// letter-size pages drawn with one sample a pixel, and 4 drawn with 4 × 4 ([`comparison_samples`]). +pub(super) const MAX_PIXELS_COMPARED: u64 = 1 << 23; + +/// The most pages of a frame compared, the first included, however few pixels they take. +pub(super) const MAX_PAGES_COMPARED: usize = 128; + +/// How many pixels the comparisons draw the page `page` of the PDF part in, at [`compare_scale`] +/// with `samples` × `samples` samples a pixel ([`comparison_samples`]): `u64::MAX` for one that +/// can't be drawn. +pub(super) fn pixels_compared(page: Rect, samples: u32) -> u64 { + let samples = u64::from(samples) * u64::from(samples); + vectorcraft_render::raster_size(page, compare_scale(page)).map_or(u64::MAX, |(w, h)| (u64::from(w) * u64::from(h)).saturating_mul(samples)) +} + +/// The longest side (pixels) of a sheet ([`Sheet`]). +const MAX_SHEET_SIDE: f64 = 8192.0; + +/// How many times its pages' pixels a sheet may have, the gaps between them included. +const SHEET_SPREAD: f64 = 2.0; + +/// One page of the PDF part, drawn once. +struct Page { + drawn: vectorcraft_render::Rendered, /// Where the page's own type is, in its pixels. page_type: Vec, /// Where objects read with their art style lie, in its pixels: the page has Illustrator's /// rendering of the style there, the layers VectorCraft's live effects, and the two aren't /// held to look alike. restyled: Vec, - /// Where the page draws anything (its type, or its own outlines of type) or has its type. - page_marks: Shares, - layers: vectorcraft_render::Renderer, + /// The column and row of its pixels that its move ([`Self::region`]) took partly off its area, + /// where the layers can draw a neighboring artboard's art and the page the space between pages: + /// they count as alike. + edges: Vec, + /// Where the page draws anything (its type, or its own outlines of type) or has its type, in its + /// pixels row by row. + page_marks: Vec, scale: f64, - samples: u32, + /// The page area's width and height ([`sized`]). + size: (f64, f64), + /// The area of the layers' document the page is compared with: its artboard ([`sized`]), moved + /// by up to half a pixel to start on a pixel of its sheet, the page's area with it. + region: Rect, } -impl PageView { - pub(super) fn new(frame: &Frame<'_>) -> Self { - let ra = frame.page_rect; - let scale = compare_scale(ra); - // Drawn on nothing and then seen on white: blending modes have no page to blend with, as in - // the app that wrote the file. - let samples = comparison_samples(frame.page); - let page = comparison_render(&mut vectorcraft_render::Renderer::new(), frame.page, ra, scale, samples); +impl Page { + /// The area `ra` of `page`, `drawn` at `scale` ([`compare_scale`]), to be compared with the layers + /// on `region`, both moved by (`dx`, `dy`) pixels from where the artboard and page lie. + fn on(page: &Document, drawn: vectorcraft_render::Rendered, ra: Rect, region: Rect, scale: f64, (dx, dy): (f64, f64)) -> Self { let mut page_type = vec![]; - type_areas(&frame.page.layers, ra, scale, &mut page_type); - let (w, h) = (page.width as usize, page.height as usize); + type_areas(&page.layers, ra, scale, &mut page_type); + let (w, h) = (drawn.width as usize, drawn.height as usize); let typed = in_areas(&page_type, w, h); - let marks: Vec = page.pixels.as_chunks::<4>().0.iter().zip(&typed).map(|(p, t)| *t || ink(on_white(p)) > WHITE).collect(); - let page_marks = Shares::of(&marks, w, h); - Self { page, page_type, restyled: vec![], page_marks, layers: vectorcraft_render::Renderer::new(), scale, samples } + // A pixel with nothing drawn on it is white. + let page_marks: Vec = + drawn.pixels.as_chunks::<4>().0.iter().zip(&typed).map(|(p, t)| *t || (p[3] != 0 && ink(on_white(p)) > WHITE)).collect(); + let (wf, hf) = (f64::from(drawn.width), f64::from(drawn.height)); + let mut edges = vec![]; + // Moved left (or up), the first column (or row) starts before the area; moved right (or + // down), the last one ends past it. + match dx { + d if d > 1e-6 => edges.push(Rect::new(0.0, 0.0, 1.0, hf)), + d if d < -1e-6 => edges.push(Rect::new(wf - 1.0, 0.0, wf, hf)), + _ => {} + } + match dy { + d if d > 1e-6 => edges.push(Rect::new(0.0, 0.0, wf, 1.0)), + d if d < -1e-6 => edges.push(Rect::new(0.0, hf - 1.0, wf, hf)), + _ => {} + } + Self { drawn, page_type, restyled: vec![], edges, page_marks, scale, size: (ra.width(), ra.height()), region } } - /// Leave the drawn looks in `looks` (on `region`, the page's area in the layers' document) out - /// of the comparisons ([`Structure::restyled`](ai::Structure)). - pub(super) fn restyled(&mut self, looks: &[Rect], region: Rect) { - let s = self.scale; - self.restyled = looks - .iter() - .map(|r| r.inflate(OUTLINE_REACH, OUTLINE_REACH)) - .map(|r| Rect::new((r.x0 - region.x0) * s, (r.y0 - region.y0) * s, (r.x1 - region.x0) * s, (r.y1 - region.y0) * s)) - .collect(); + /// The pixels that count as alike: the restyled looks' and the edges'. + fn skipped(&self) -> Vec { + self.restyled.iter().chain(&self.edges).copied().collect() } - /// How `b` on `rb` (a rectangle the page's size) draws differently from the page ([`compared`]). - /// With `reflow` (`b`'s type laid out again from the file's text), type counts as type only where - /// both have something: `b`'s where the page has type or draws anything in at least [`MARKED`] - /// of it, the page's where at least half of it lies where `b` has a text object, shown or not, - /// or a placed file. Elsewhere it is art the other lacks. - pub(super) fn difference(&mut self, b: &Document, rb: Rect, reflow: bool) -> Difference { - // The page doesn't print what isn't printed. - let printed = as_printed(b); - let b = printed.as_ref().unwrap_or(b); - let y = comparison_render(&mut self.layers, b, rb, self.scale, self.samples); - let areas = self.counted_type(b, rb, reflow); - compared(&self.page, &y, &areas, &self.restyled) - } - - /// Where [`Self::difference`] counts `b`'s and the page's pixels as type, in the page's pixels. + /// Where [`PageView::difference_on_every_page`] counts `b`'s (on `rb`) and the page's pixels as + /// type, in the page's pixels. With `reflow` (`b`'s type laid out again from the file's text), + /// type counts as type only where both have something: `b`'s where the page has type or draws + /// anything in at least [`MARKED`] of it, the page's where at least half of it lies where `b` has + /// a text object, shown or not, or a placed file. Elsewhere it is art the other lacks. fn counted_type(&self, b: &Document, rb: Rect, reflow: bool) -> Vec { let mut areas = vec![]; type_areas(&b.layers, rb, self.scale, &mut areas); if reflow { - areas.retain(|r| self.page_marks.share(r) >= MARKED); + let (w, h) = (self.drawn.width as usize, self.drawn.height as usize); + let marked = shares(&self.page_marks, w, h, &areas); + areas = areas.into_iter().zip(marked).filter(|(_, share)| *share >= MARKED).map(|(r, _)| r).collect(); let mut texts = vec![]; all_type_areas(&b.layers, rb, self.scale, &mut texts); - let (w, h) = (self.page.width as usize, self.page.height as usize); - let on_layers = Shares::of(&in_areas(&texts, w, h), w, h); - areas.extend(self.page_type.iter().filter(|r| on_layers.share(r) >= 0.5)); + let on_layers = shares(&in_areas(&texts, w, h), w, h, &self.page_type); + areas.extend(self.page_type.iter().zip(on_layers).filter(|(_, share)| *share >= 0.5).map(|(r, _)| *r)); } else { areas.extend(&self.page_type); } areas } +} - /// The share (0 to 1) of the pixels where `b` on `rb` draws another colour than the page - /// ([`differ_in_colour`]), type included: what taking an object out of the layers changes - /// there, when it is covered by one of about the same lightness (#1102). - pub(super) fn colour_difference(&mut self, b: &Document, rb: Rect) -> f64 { - let printed = as_printed(b); - let b = printed.as_ref().unwrap_or(b); - let y = comparison_render(&mut self.layers, b, rb, self.scale, self.samples); - if (y.width, y.height) != (self.page.width, self.page.height) { - return 1.0; +/// `rb`, or when its sides are within half a point of `size` (a page area's, as an artboard taken for +/// its page is), the area of that size at its top-left: the layers are drawn on it, so that both +/// drawings have the same number of pixels. +fn sized((w, h): (f64, f64), rb: Rect) -> Rect { + if (rb.width() - w).abs() <= 0.5 && (rb.height() - h).abs() <= 0.5 { Rect::new(rb.x0, rb.y0, rb.x0 + w, rb.y0 + h) } else { rb } +} + +/// An area of the layers' document that holds the areas of some of the pages drawn at one scale, +/// each starting on one of its pixels: the layers are drawn on it once for all of them, and cut +/// apart. +struct Sheet { + rect: Rect, + scale: f64, + /// Its pages, as [`PageView::regions`] counts them. + pages: Vec, + /// How many pixels its pages take. + pixels: f64, +} + +impl Sheet { + /// The move (less than half a pixel) that makes `region` start on one of the sheet's pixels, and + /// the sheet's area with it: `None` when the sheet would then be too large ([`MAX_SHEET_SIDE`], + /// [`SHEET_SPREAD`]). + fn room(&self, region: Rect) -> Option<((f64, f64), Rect)> { + let s = self.scale; + let off = |v: f64, from: f64| { + let px = (v - from) * s; + (px - px.round()) / s + }; + let (dx, dy) = (off(region.x0, self.rect.x0), off(region.y0, self.rect.y0)); + let moved = Rect::new(region.x0 - dx, region.y0 - dy, region.x1 - dx, region.y1 - dy); + let all = self.rect.union(moved); + let (w, h) = (all.width() * s, all.height() * s); + let pixels = self.pixels + moved.width() * s * moved.height() * s; + (w.is_finite() && h.is_finite() && w.max(h) <= MAX_SHEET_SIDE && w * h <= SHEET_SPREAD * pixels).then_some(((dx, dy), all)) + } +} + +/// How many documents' drawings a [`PageView`] keeps. +const KEPT_DOCUMENTS: usize = 2; + +/// The layers of one document as drawn on the pages' areas, kept between comparisons. +struct Drawn { + /// The document's layers, held so that a document changed since never shares them. Only the + /// layers are compared: the import changes the documents it compares in their layers, and two + /// documents with the same layers and other symbols, patterns, swatches or color mode would + /// share their drawings. + layers: Vec>, + /// Each page's drawing, once drawn. + pages: Vec>, +} + +impl Drawn { + /// Are these the drawings of `b`, for `n` pages? + fn of(&self, b: &Document, n: usize) -> bool { + self.pages.len() == n && self.layers.len() == b.layers.len() && self.layers.iter().zip(&b.layers).all(|(x, y)| Arc::ptr_eq(x, y)) + } +} + +/// The layers drawn on one page's area, with how they differ from the page once weighed. +struct Layered { + pixels: vectorcraft_render::Rendered, + /// [`compared`] as [`PageView::difference_on_every_page`] weighs it, without and with `reflow`. + laid: Option, + reflowed: Option, + /// [`colour_share`]. + colour: Option, +} + +/// The pages drawn once, to weigh the layers' art against them, and the layers' drawings of the last +/// two documents weighed. The layers are drawn with a renderer of their own, which keeps their decoded +/// images between draws (the page's images can share their keys and not their pixels, so the two +/// don't share one). +pub(super) struct PageView { + /// The frame's first page, then its other pages ([`Frame::more`]). + pages: Vec, + /// The areas in the layers' document that the pages are compared on, as the frame gives them. + boards: Vec, + sheets: Vec, + samples: u32, + layers: vectorcraft_render::Renderer, + /// The drawings of the last [`KEPT_DOCUMENTS`] documents weighed, the last one weighed last (the + /// import weighs two readings of a file back and forth). + drawn: Vec, + /// The drawings of the last document [`Self::weigh_without`] weighed, with their shares. + without: Vec<(usize, vectorcraft_render::Rendered, f64)>, + /// How many times the layers were drawn. + draws: usize, +} + +impl PageView { + pub(super) fn new(frame: &Frame<'_>) -> Self { + let samples = comparison_samples(frame.page); + // Each page's area, the area of the layers' document it is compared with, and its scale. + let (mut planned, mut boards, mut sheets) = (vec![], vec![], Vec::::new()); + for (ra, rb) in std::iter::once((frame.page_rect, frame.rect)).chain(frame.more.iter().copied()) { + let (scale, i) = (compare_scale(ra), planned.len()); + let region = sized((ra.width(), ra.height()), rb); + let pixels = region.width() * scale * region.height() * scale; + // A page whose drawings are resampled ([`comparison_samples`]) is drawn on its own. + // Pages of one size can have scales a rounding error apart: they take the sheet's. + let room = sheets.last().filter(|s| samples == 1 && (s.scale - scale).abs() <= scale * 1e-9).and_then(|s| s.room(region)); + let (dx, dy, scale) = match (room, sheets.last_mut()) { + (Some(((dx, dy), all)), Some(sheet)) => { + sheet.rect = all; + sheet.pixels += pixels; + sheet.pages.push(i); + (dx, dy, sheet.scale) + } + _ => { + sheets.push(Sheet { rect: region, scale, pages: vec![i], pixels }); + (0.0, 0.0, scale) + } + }; + let moved = |r: Rect| Rect::new(r.x0 - dx, r.y0 - dy, r.x1 - dx, r.y1 - dy); + planned.push((moved(ra), moved(region), scale, (dx * scale, dy * scale))); + boards.push(rb); } - let differing = self.page.pixels.as_chunks::<4>().0.iter().zip(y.pixels.as_chunks::<4>().0).filter(|(p, q)| differ_in_colour(p, q)).count(); - differing as f64 / (f64::from(y.width) * f64::from(y.height)).max(1.0) + // Drawn on nothing and then seen on white: blending modes have no page to blend with, as in + // the app that wrote the file. + let mut renderer = vectorcraft_render::Renderer::new(); + let pages = planned + .into_iter() + .map(|(ra, region, scale, moved)| { + Page::on(frame.page, comparison_render(&mut renderer, frame.page, ra, scale, samples), ra, region, scale, moved) + }) + .collect(); + Self { pages, boards, sheets, samples, layers: vectorcraft_render::Renderer::new(), drawn: vec![], without: vec![], draws: 0 } } - /// How `b` on `rb` draws differently from the page ([`Self::difference`]), and the boxes (in - /// `b`'s terms) around each patch of the pixels counted in its `solid` share (they and all - /// their neighbors differ, away from type), neighbors touching corner to corner counting as one patch. `None` when the two - /// drawings aren't the same size. - pub(super) fn solid_regions(&mut self, b: &Document, rb: Rect, reflow: bool) -> Option<(Difference, Vec)> { + /// The areas in the layers' document that the pages are compared on: `rb` for the first page, + /// then each other page's artboard. + pub(super) fn regions(&self, rb: Rect) -> Vec { + std::iter::once(rb).chain(self.boards.iter().skip(1).copied()).collect() + } + + /// Leave the drawn looks in `looks` (on `region`, the first page's area in the layers' document) + /// out of the comparisons ([`Structure::restyled`](ai::Structure)), on the other pages' artboards + /// too. + pub(super) fn restyled(&mut self, looks: &[Rect], region: Rect) { + for (i, page) in self.pages.iter_mut().enumerate() { + let (s, region) = (page.scale, if i == 0 { region } else { page.region }); + page.restyled = looks + .iter() + .map(|r| r.inflate(OUTLINE_REACH, OUTLINE_REACH)) + .map(|r| Rect::new((r.x0 - region.x0) * s, (r.y0 - region.y0) * s, (r.x1 - region.x0) * s, (r.y1 - region.y0) * s)) + .collect(); + } + self.drawn.clear(); + } + + /// `b`, as printed, drawn on the areas of the pages `wanted`: on their sheet when they are more + /// than one and take at least half its pixels, else each on its own. + fn draw(&mut self, b: &Document, wanted: &[usize]) -> Vec<(usize, vectorcraft_render::Rendered)> { + let mut out = vec![]; + for sheet in &self.sheets { + let on: Vec = sheet.pages.iter().copied().filter(|i| wanted.contains(i)).collect(); + let s = sheet.scale; + let taken: f64 = on.iter().filter_map(|i| self.pages.get(*i)).map(|p| p.region.width() * s * p.region.height() * s).sum(); + // A pixel more on the right and at the bottom, for the pages' areas rounded up. + let whole = (on.len() > 1 && taken * 2.0 >= sheet.rect.width() * s * sheet.rect.height() * s).then(|| { + self.draws += 1; + let r = sheet.rect; + comparison_render(&mut self.layers, b, Rect::new(r.x0, r.y0, r.x1 + 1.0 / s, r.y1 + 1.0 / s), s, 1) + }); + for i in on { + let Some(page) = self.pages.get(i) else { continue }; + let r = page.region; + let part = whole + .as_ref() + .zip(vectorcraft_render::raster_size(r, s).ok()) + .and_then(|(whole, (w, h))| cut(whole, (r.x0 - sheet.rect.x0) * s, (r.y0 - sheet.rect.y0) * s, w, h)); + let drawn = match part { + Some(part) => part, + None => { + self.draws += 1; + comparison_render(&mut self.layers, b, r, page.scale, self.samples) + } + }; + out.push((i, drawn)); + } + } + out + } + + /// Have the layers of `b` drawn on the pages `wanted`, keeping those already drawn when `b` is the + /// document last drawn. + fn layered(&mut self, b: &Document, wanted: &[usize]) { + let n = self.pages.len(); + match self.drawn.iter().position(|d| d.of(b, n)) { + Some(at) => { + let kept = self.drawn.remove(at); + self.drawn.push(kept); + } + None => { + if self.drawn.len() >= KEPT_DOCUMENTS { + self.drawn.remove(0); + } + self.drawn.push(Drawn { layers: b.layers.clone(), pages: (0..n).map(|_| None).collect() }); + } + } + let missing: Vec = + wanted.iter().copied().filter(|i| self.drawn.last().and_then(|d| d.pages.get(*i)).is_some_and(Option::is_none)).collect(); + if missing.is_empty() { + return; + } + // The page doesn't print what isn't printed. + let printed = as_printed(b); + for (i, pixels) in self.draw(printed.as_ref().unwrap_or(b), &missing) { + if let Some(slot) = self.drawn.last_mut().and_then(|d| d.pages.get_mut(i)) { + *slot = Some(Layered { pixels, laid: None, reflowed: None, colour: None }); + } + } + } + + /// How `b` draws differently from each page ([`compared`]), the first on `rb` (its frame's area, + /// or another rectangle its size), the others on their artboards. + pub(super) fn differences(&mut self, b: &Document, rb: Rect, reflow: bool) -> Vec { + let all: Vec = (0..self.pages.len()).collect(); + self.layered(b, &all); + let printed = as_printed(b); + let printed = printed.as_ref().unwrap_or(b); + let mut out = vec![]; + for i in all { + let d = if i == 0 && self.boards.first() != Some(&rb) { self.elsewhere(printed, rb, reflow) } else { self.weighed(i, printed, reflow) }; + out.push(d); + } + out + } + + /// The first page compared with `b` (as printed) on `rb`, drawn for it alone. + fn elsewhere(&mut self, b: &Document, rb: Rect, reflow: bool) -> Difference { + let Some(page) = self.pages.first() else { return Difference::ALL }; + let rb = sized(page.size, rb); + self.draws += 1; + let y = comparison_render(&mut self.layers, b, rb, page.scale, self.samples); + compared(&page.drawn, &y, &page.counted_type(b, rb, reflow), &page.skipped()) + } + + /// Page `i` compared with its drawing of `b` (as printed, already drawn), weighed once. + fn weighed(&mut self, i: usize, b: &Document, reflow: bool) -> Difference { + let Some((page, Some(layered))) = self.pages.get(i).zip(self.drawn.last_mut().and_then(|d| d.pages.get_mut(i))) else { + return Difference::ALL; + }; + let memo = if reflow { &mut layered.reflowed } else { &mut layered.laid }; + *memo.get_or_insert_with(|| compared(&page.drawn, &layered.pixels, &page.counted_type(b, page.region, reflow), &page.skipped())) + } + + /// [`Self::differences`] taken together: each share is that of the page that differs most. + pub(super) fn difference_on_every_page(&mut self, b: &Document, rb: Rect, reflow: bool) -> Difference { + self.differences(b, rb, reflow).into_iter().reduce(Difference::max).unwrap_or(Difference::ALL) + } + + /// How `b` draws differently from the pages ([`Self::difference_on_every_page`]), and the boxes + /// (in `b`'s terms) around each patch of the pixels counted in its `solid` share (they and all + /// their neighbors differ, away from type), neighbors touching corner to corner counting as one + /// patch. `None` when the two drawings of a page aren't the same size. + pub(super) fn solid_regions_on_every_page(&mut self, b: &Document, reflow: bool) -> Option<(Difference, Vec)> { + let all: Vec = (0..self.pages.len()).collect(); + self.layered(b, &all); let printed = as_printed(b); let b = printed.as_ref().unwrap_or(b); - let y = comparison_render(&mut self.layers, b, rb, self.scale, self.samples); - let areas = self.counted_type(b, rb, reflow); - let (diff, mut solid) = compared_with_solid(&self.page, &y, &areas, &self.restyled); - let (w, h) = (y.width as usize, y.height as usize); - if solid.len() != w * h { - return None; - } - // A pixel's size in points: [`comparison_render`] draws at `scale * samples`, rounds that - // raster to whole pixels and resizes it to `w` × `h`, so the two sizes can round differently. - let k = f64::from(self.samples); - let drawn = vectorcraft_render::raster_size(rb, self.scale * k).map_or((w as f64, h as f64), |(dw, dh)| (f64::from(dw), f64::from(dh))); - let pitch = (drawn.0 / (w as f64 * k * self.scale), drawn.1 / (h as f64 * k * self.scale)); - let mut regions = vec![]; - let mut stack = vec![]; - for start in 0..solid.len() { - if !solid.get(start).copied().unwrap_or(false) { - continue; - } - // The patch's pixels are cleared as they are taken, so each is taken once. - if let Some(s) = solid.get_mut(start) { - *s = false; - } - stack.push(start); - let (mut i0, mut j0, mut i1, mut j1) = (start % w, start / w, start % w, start / w); - while let Some(k) = stack.pop() { - let (i, j) = (k % w, k / w); - (i0, j0, i1, j1) = (i0.min(i), j0.min(j), i1.max(i), j1.max(j)); - for n in j.saturating_sub(1)..=(j + 1).min(h - 1) { - for m in i.saturating_sub(1)..=(i + 1).min(w - 1) { - if let Some(s) = solid.get_mut(n * w + m).filter(|s| **s) { - *s = false; - stack.push(n * w + m); - } - } - } - } - let at = |i: usize, j: usize| (rb.x0 + i as f64 * pitch.0, rb.y0 + j as f64 * pitch.1); - let ((x0, y0), (x1, y1)) = (at(i0, j0), at(i1 + 1, j1 + 1)); - regions.push(Rect::new(x0, y0, x1, y1)); + let (mut diff, mut regions) = (Difference { any: 0.0, art: 0.0, solid: 0.0, typed: 0.0 }, vec![]); + for (page, layered) in self.pages.iter().zip(&self.drawn.last()?.pages) { + let y = &layered.as_ref()?.pixels; + let (d, solid) = compared_with_solid(&page.drawn, y, &page.counted_type(b, page.region, reflow), &page.skipped()); + regions.extend(patches(solid, y.width as usize, y.height as usize, page.region, page.scale, self.samples)?); + diff = diff.max(d); } Some((diff, regions)) } + + /// The share (0 to 1) of the pixels where `b` on page `i`'s area draws another color than the + /// page ([`colour_share`]). + fn colour_difference(&mut self, i: usize, b: &Document) -> f64 { + self.layered(b, &[i]); + let Some((page, Some(layered))) = self.pages.get(i).zip(self.drawn.last_mut().and_then(|d| d.pages.get_mut(i))) else { return 1.0 }; + *layered.colour.get_or_insert_with(|| colour_share(&page.drawn, &layered.pixels, &page.edges)) + } + + /// `doc`'s and `without`'s shares ([`colour_share`]) on each of the pages `on`, `without` being + /// `doc` with an object taken out that lies on those pages only. `without`'s drawings are kept + /// for [`Self::adopt`]. + pub(super) fn weigh_without(&mut self, doc: &Document, without: &Document, on: &[usize]) -> Vec<(usize, f64, f64)> { + self.layered(doc, on); + let printed = as_printed(without); + let drawn = self.draw(printed.as_ref().unwrap_or(without), on); + let mut shares = vec![]; + self.without.clear(); + for (i, pixels) in drawn { + let before = self.colour_difference(i, doc); + let Some(page) = self.pages.get(i) else { continue }; + let after = colour_share(&page.drawn, &pixels, &page.edges); + shares.push((i, before, after)); + self.without.push((i, pixels, after)); + } + shares + } + + /// `doc` now has the object [`Self::weigh_without`] last took out taken out: its drawings are the + /// ones made without the object on the pages it lay on, and the ones kept on the others. + pub(super) fn adopt(&mut self, doc: &Document) { + let without = std::mem::take(&mut self.without); + let Some(drawn) = self.drawn.last_mut() else { return }; + drawn.layers = doc.layers.clone(); + // The type areas on a page can reach past the object's box. + for layered in drawn.pages.iter_mut().flatten() { + (layered.laid, layered.reflowed) = (None, None); + } + for (i, pixels, colour) in without { + if let Some(slot) = drawn.pages.get_mut(i) { + *slot = Some(Layered { pixels, laid: None, reflowed: None, colour: Some(colour) }); + } + } + } +} + +/// The `w` × `h` pixels of `from` from pixel (`x`, `y`): `None` unless they lie in it, from a pixel. +fn cut(from: &vectorcraft_render::Rendered, x: f64, y: f64, w: u32, h: u32) -> Option { + let (rx, ry) = (x.round(), y.round()); + if !((x - rx).abs() < 0.01 && (y - ry).abs() < 0.01 && rx >= 0.0 && ry >= 0.0) { + return None; + } + let (x, y, wu, hu) = (rx as usize, ry as usize, w as usize, h as usize); + let stride = from.width as usize * 4; + if x + wu > from.width as usize || y + hu > from.height as usize { + return None; + } + let mut pixels = Vec::with_capacity(wu * hu * 4); + for row in y..y + hu { + pixels.extend_from_slice(from.pixels.get(row * stride + x * 4..row * stride + (x + wu) * 4)?); + } + Some(vectorcraft_render::Rendered { width: w, height: h, pixels }) +} + +/// The boxes (in the terms of the document drawn on `rb` at `scale` with `samples` × `samples` +/// samples a pixel, [`comparison_render`]) around each patch of the `w` × `h` pixels `solid` marks, +/// neighbors touching corner to corner counting as one patch. `None` when `solid` doesn't have that +/// many pixels. +fn patches(mut solid: Vec, w: usize, h: usize, rb: Rect, scale: f64, samples: u32) -> Option> { + if solid.len() != w * h { + return None; + } + // A pixel's size in points: [`comparison_render`] draws at `scale * samples`, rounds that + // raster to whole pixels and resizes it to `w` × `h`, so the two sizes can round differently. + let k = f64::from(samples); + let drawn = vectorcraft_render::raster_size(rb, scale * k).map_or((w as f64, h as f64), |(dw, dh)| (f64::from(dw), f64::from(dh))); + let pitch = (drawn.0 / (w as f64 * k * scale), drawn.1 / (h as f64 * k * scale)); + let mut regions = vec![]; + let mut stack = vec![]; + for start in 0..solid.len() { + if !solid.get(start).copied().unwrap_or(false) { + continue; + } + // The patch's pixels are cleared as they are taken, so each is taken once. + if let Some(s) = solid.get_mut(start) { + *s = false; + } + stack.push(start); + let (mut i0, mut j0, mut i1, mut j1) = (start % w, start / w, start % w, start / w); + while let Some(k) = stack.pop() { + let (i, j) = (k % w, k / w); + (i0, j0, i1, j1) = (i0.min(i), j0.min(j), i1.max(i), j1.max(j)); + for n in j.saturating_sub(1)..=(j + 1).min(h - 1) { + for m in i.saturating_sub(1)..=(i + 1).min(w - 1) { + if let Some(s) = solid.get_mut(n * w + m).filter(|s| **s) { + *s = false; + stack.push(n * w + m); + } + } + } + } + let at = |i: usize, j: usize| (rb.x0 + i as f64 * pitch.0, rb.y0 + j as f64 * pitch.1); + let ((x0, y0), (x1, y1)) = (at(i0, j0), at(i1 + 1, j1 + 1)); + regions.push(Rect::new(x0, y0, x1, y1)); + } + Some(regions) +} + +/// The share (0 to 1) of the pixels where `y` draws another color than the page `x` +/// ([`differ_in_colour`]), type included and pixels in `skip` counting as alike: what taking an +/// object out of the layers changes there, when it is covered by one of about the same lightness +/// (#1102). +fn colour_share(x: &vectorcraft_render::Rendered, y: &vectorcraft_render::Rendered, skip: &[Rect]) -> f64 { + if (y.width, y.height) != (x.width, x.height) { + return 1.0; + } + let skipped = in_areas(skip, x.width as usize, x.height as usize); + let differing = x + .pixels + .as_chunks::<4>() + .0 + .iter() + .zip(y.pixels.as_chunks::<4>().0) + .zip(&skipped) + .filter(|((p, q), s)| !**s && differ_in_colour(p, q)) + .count(); + differing as f64 / (f64::from(y.width) * f64::from(y.height)).max(1.0) } /// How `a` on `ra` and `b` on `rb` (rectangles of the same size) draw differently ([`compared`]), @@ -296,32 +674,33 @@ pub(super) fn compared(x: &vectorcraft_render::Rendered, y: &vectorcraft_render: /// the drawings can't be compared. fn compared_with_solid(x: &vectorcraft_render::Rendered, y: &vectorcraft_render::Rendered, areas: &[Rect], skip: &[Rect]) -> (Difference, Vec) { if x.width == 0 || x.height == 0 || x.width != y.width || x.height != y.height { - return (Difference { any: 1.0, art: 1.0, solid: 1.0 }, vec![]); + return (Difference { any: 1.0, art: 1.0, solid: 1.0, typed: 0.0 }, vec![]); } let (w, h) = (x.width as usize, x.height as usize); // Pixels in `skip` count as alike. let skipped = in_areas(skip, w, h); let differs: Vec = x.pixels.as_chunks::<4>().0.iter().zip(y.pixels.as_chunks::<4>().0).zip(&skipped).map(|((p, q), s)| !*s && differ(p, q)).collect(); - let at = |i: usize, j: usize| j.checked_mul(w).and_then(|row| row.checked_add(i)).and_then(|k| differs.get(k)).copied().unwrap_or(false); + if !differs.contains(&true) { + return (Difference { any: 0.0, art: 0.0, solid: 0.0, typed: 0.0 }, vec![false; w * h]); + } let typed = in_areas(areas, w, h); let art = differs.iter().zip(&typed).filter(|(d, t)| **d && !**t).count(); + // Which pixels differ with their left and right neighbors. + let mut across = vec![false; w * h]; + for (k, a) in across.iter_mut().enumerate() { + let i = k % w; + *a = i > 0 && i + 1 < w && differs.get(k - 1..=k + 1).is_some_and(|d| d.iter().all(|d| *d)); + } // A pixel on the region's edge has neighbours outside it, which don't count as differing. let mut solid = vec![false; w * h]; - for (i, j) in (1..h.saturating_sub(1)).flat_map(|j| (1..w.saturating_sub(1)).map(move |i| (i, j))) { - if !typed.get(j * w + i).copied().unwrap_or(true) - && (j - 1..=j + 1).all(|n| (i - 1..=i + 1).all(|m| at(m, n))) - && let Some(s) = solid.get_mut(j * w + i) - { - *s = true; - } + for (k, s) in solid.iter_mut().enumerate().skip(w).take(w * h.saturating_sub(2)) { + *s = !typed.get(k).copied().unwrap_or(true) && [k - w, k, k + w].iter().all(|n| across.get(*n).copied().unwrap_or(false)); } let area = (w as f64 * h as f64).max(1.0); - let shares = Difference { - any: differs.iter().filter(|d| **d).count() as f64 / area, - art: art as f64 / area, - solid: solid.iter().filter(|s| **s).count() as f64 / area, - }; + let any = differs.iter().filter(|d| **d).count() as f64 / area; + let art = art as f64 / area; + let shares = Difference { any, art, solid: solid.iter().filter(|s| **s).count() as f64 / area, typed: any - art }; (shares, solid) } @@ -371,14 +750,16 @@ impl Shares { pub(super) fn of(marks: &[bool], w: usize, h: usize) -> Self { let stride = w + 1; let mut sums = vec![0u32; stride * (h + 1)]; - for (k, marked) in marks.iter().enumerate().take(w * h) { - let (i, j) = (k % w.max(1), k / w.max(1)); - let left = sums.get((j + 1) * stride + i).copied().unwrap_or(0); - let up = sums.get(j * stride + i + 1).copied().unwrap_or(0); - let corner = sums.get(j * stride + i).copied().unwrap_or(0); - if let Some(s) = sums.get_mut((j + 1) * stride + i + 1) { - *s = (left + up + u32::from(*marked)).saturating_sub(corner); + // Row by row: the marked pixels left of each corner in its row, added to the row above's. + let mut above = vec![0u32; stride]; + for (j, out) in sums.chunks_exact_mut(stride).skip(1).enumerate() { + let row = marks.get(j * w..).unwrap_or(&[]).iter().copied().chain(std::iter::repeat(false)).take(w); + let mut run = 0u32; + for ((marked, s), up) in row.zip(out.iter_mut().skip(1)).zip(above.iter().skip(1)) { + run += u32::from(marked); + *s = up + run; } + above.copy_from_slice(out); } Self { sums, w, h } } @@ -386,8 +767,7 @@ impl Shares { /// The share (0 to 1) of `r`'s pixels that are marked: 0 for one with none of the pixels. pub(super) fn share(&self, r: &Rect) -> f64 { let (w, h, stride) = (self.w, self.h, self.w + 1); - let clamp = |v: f64, max: usize| if v.is_finite() { v.clamp(0.0, max as f64) as usize } else { 0 }; - let (x0, y0, x1, y1) = (clamp(r.x0.floor(), w), clamp(r.y0.floor(), h), clamp(r.x1.ceil(), w), clamp(r.y1.ceil(), h)); + let (x0, y0, x1, y1) = pixel_box(r, w, h); if !r.is_finite() || x1 <= x0 || y1 <= y0 { return 0.0; } @@ -397,35 +777,78 @@ impl Shares { } } +/// The pixels `r` touches of `w` × `h` (first and last column and row, the last ones excluded). +fn pixel_box(r: &Rect, w: usize, h: usize) -> (usize, usize, usize, usize) { + let clamp = |v: f64, max: usize| if v.is_finite() { v.clamp(0.0, max as f64) as usize } else { 0 }; + (clamp(r.x0.floor(), w), clamp(r.y0.floor(), h), clamp(r.x1.ceil(), w), clamp(r.y1.ceil(), h)) +} + +/// [`Shares::share`] of each of `rects` for the `w` × `h` pixels `marks` marks: counted one by one +/// when the rectangles hold fewer pixels in all than there are, else with [`Shares`]. +fn shares(marks: &[bool], w: usize, h: usize, rects: &[Rect]) -> Vec { + let few = rects + .iter() + .map(|r| pixel_box(r, w, h)) + .try_fold(0usize, |n, (x0, y0, x1, y1)| n.checked_add(x1.saturating_sub(x0).checked_mul(y1.saturating_sub(y0))?)); + if !few.is_some_and(|n| n <= w * h) { + let counted = Shares::of(marks, w, h); + return rects.iter().map(|r| counted.share(r)).collect(); + } + let share = |r: &Rect| { + let (x0, y0, x1, y1) = pixel_box(r, w, h); + if !r.is_finite() || x1 <= x0 || y1 <= y0 { + return 0.0; + } + let inside: usize = (y0..y1).map(|y| marks.get(y * w + x0..y * w + x1).map_or(0, |row| row.iter().filter(|m| **m).count())).sum(); + inside as f64 / ((x1 - x0) as f64 * (y1 - y0) as f64) + }; + rects.iter().map(share).collect() +} + /// Which of `w` × `h` pixels (row by row) lie in one of `areas`. fn in_areas(areas: &[Rect], w: usize, h: usize) -> Vec { + if areas.is_empty() { + return vec![false; w * h]; + } + let pixels: Vec<(usize, usize, usize, usize)> = areas.iter().map(|r| pixel_box(r, w, h)).collect(); + // Areas that cover fewer pixels in all than there are are marked one by one. + let covered = + pixels.iter().try_fold(0usize, |n, &(x0, y0, x1, y1)| if x1 < x0 || y1 < y0 { None } else { n.checked_add((x1 - x0).checked_mul(y1 - y0)?) }); + if covered.is_some_and(|n| n <= w * h) { + let mut inside = vec![false; w * h]; + for (x0, y0, x1, y1) in pixels { + for y in y0..y1 { + if let Some(row) = inside.get_mut(y * w + x0..y * w + x1) { + row.fill(true); + } + } + } + return inside; + } // Each area adds one inside it: corners marked, then summed along the rows and down the columns. let stride = w + 1; let mut count = vec![0i64; stride * (h + 1)]; - let clamp = |v: f64, max: usize| if v.is_finite() { v.clamp(0.0, max as f64) as usize } else { 0 }; - for r in areas { - let (x0, y0, x1, y1) = (clamp(r.x0.floor(), w), clamp(r.y0.floor(), h), clamp(r.x1.ceil(), w), clamp(r.y1.ceil(), h)); + for (x0, y0, x1, y1) in pixels { for (x, y, d) in [(x0, y0, 1), (x1, y0, -1), (x0, y1, -1), (x1, y1, 1)] { if let Some(c) = count.get_mut(y * stride + x) { *c += d; } } } - for row in count.chunks_mut(stride) { - let mut run = 0; - for c in row { - run += *c; - *c = run; - } + let mut inside = vec![false; w * h]; + if w == 0 { + return inside; } let mut column = vec![0i64; stride]; - for row in count.chunks_mut(stride) { - for (c, sum) in row.iter_mut().zip(column.iter_mut()) { - *sum += *c; - *c = *sum; + for (row, out) in count.chunks_exact(stride).zip(inside.chunks_exact_mut(w)) { + let mut run = 0; + for ((c, sum), o) in row.iter().zip(column.iter_mut()).zip(out) { + run += *c; + *sum += run; + *o = *sum > 0; } } - (0..h).flat_map(|j| (0..w).map(move |i| (i, j))).map(|(i, j)| count.get(j * stride + i).is_some_and(|c| *c > 0)).collect() + inside } /// The least share of a text object's area (with the margin round it) where the page draws anything @@ -447,13 +870,14 @@ pub(in crate::import) const MAX_SOLID_DIFFERENCE: f64 = 0.001; const PAST_THE_PAGE: f64 = 1.0; /// Do the layers' art and the page's own look alike (where the page holds all the art that prints, -/// also round it)? An error says they don't; `Ok` has the notes to give when they differ a little: -/// with the share of the pixels that differ away from type when that is notable, otherwise with the -/// share of those that differ in the type's areas. With `type_reflow` (all the type laid out again -/// from the file's text, which may show in another font), type that differs doesn't make them -/// differ: only art away from type does, and the type's share is a note of its own. +/// also round it), on every page the frame has ([`Frame::more`])? An error says they don't; `Ok` has +/// the notes to give when they differ a little: with the share of the pixels that differ away from +/// type when that is notable, otherwise with the share of those that differ in the type's areas, on +/// the page that differs most. With `type_reflow` (all the type laid out again from the file's text, +/// which may show in another font), type that differs doesn't make them differ: only art away from +/// type does, and the type's share is a note of its own. pub(super) fn compare(frame: &Frame<'_>, view: &mut PageView, layered: &Document, type_reflow: bool) -> Result, String> { - let mut diff = view.difference(layered, frame.rect, type_reflow); + let mut diff = view.difference_on_every_page(layered, frame.rect, type_reflow); if frame.whole && let Some(art) = vectorcraft_render::encode::art_bounds(as_printed(layered).as_ref().unwrap_or(layered)) .filter(|a| !frame.rect.inflate(PAST_THE_PAGE, PAST_THE_PAGE).contains_rect(*a)) @@ -461,8 +885,7 @@ pub(super) fn compare(frame: &Frame<'_>, view: &mut PageView, layered: &Document // The page and the art the layers print beyond it, each in its own document's place. let all = frame.rect.union(art); let (dx, dy) = (frame.page_rect.x0 - frame.rect.x0, frame.page_rect.y0 - frame.rect.y0); - let round = difference(frame.page, Rect::new(all.x0 + dx, all.y0 + dy, all.x1 + dx, all.y1 + dy), layered, all); - diff = Difference { any: diff.any.max(round.any), art: diff.art.max(round.art), solid: diff.solid.max(round.solid) }; + diff = diff.max(difference(frame.page, Rect::new(all.x0 + dx, all.y0 + dy, all.x1 + dx, all.y1 + dy), layered, all)); } if diff.weighed(type_reflow) > MAX_DIFFERENCE || diff.solid > MAX_SOLID_DIFFERENCE { return Err(format!("the art on them differs from the page's in {:.1}% of it", diff.weighed(type_reflow) * 100.0)); @@ -476,12 +899,189 @@ pub(super) fn compare(frame: &Frame<'_>, view: &mut PageView, layered: &Document ); let typed = format!( "the type on the layers differs from the file's own page in about {:.1}% of it (type laid out again from the file's text, or drawn in another font)", - (diff.any - diff.art) * 100.0 + diff.typed * 100.0 ); let art_notable = diff.art > NOTABLE_DIFFERENCE; - Ok(match (art_notable, type_reflow && diff.any - diff.art > NOTABLE_DIFFERENCE) { + Ok(match (art_notable, type_reflow && diff.typed > NOTABLE_DIFFERENCE) { (true, true) => vec![art, typed], (true, false) => vec![art], (false, _) => vec![typed], }) } + +#[cfg(test)] +mod tests { + use super::*; + + /// One page that differs only in its type and another that differs only in its art keep both + /// shares when they are taken together. + #[test] + fn the_type_share_of_one_page_stays_beside_the_art_share_of_another() { + let typed = Difference { any: 0.03, art: 0.0, solid: 0.0, typed: 0.03 }; + let art = Difference { any: 0.04, art: 0.04, solid: 0.0, typed: 0.0 }; + let both = typed.max(art); + assert_eq!((both.any, both.art, both.typed), (0.04, 0.04, 0.03)); + } + + /// Shares and areas counted pixel by pixel match those read from sums. + #[test] + fn pixels_counted_one_by_one_match_the_sums() { + let (w, h) = (37, 23); + let marks: Vec = (0..w * h).map(|k| (k * 7 + k / 5) % 3 == 0).collect(); + let rects = + [Rect::new(-2.0, 3.5, 10.2, 9.0), Rect::new(5.0, 5.0, 12.0, 12.0), Rect::new(3.0, 3.0, 3.0, 8.0), Rect::new(10.5, 2.2, 20.7, 22.9)]; + // 66 + 49 + 0 + 231 pixels, fewer than the 851 there are: counted one by one. + let held: usize = rects.iter().map(|r| pixel_box(r, w, h)).map(|(x0, y0, x1, y1)| x1.saturating_sub(x0) * y1.saturating_sub(y0)).sum(); + assert_eq!(held, 346); + let summed = Shares::of(&marks, w, h); + let one_by_one = shares(&marks, w, h, &rects); + assert_eq!(one_by_one, rects.iter().map(|r| summed.share(r)).collect::>()); + // So many rectangles that they hold more pixels than there are: read from sums. + let many: Vec = rects.iter().cycle().take(40).copied().collect(); + assert_eq!(shares(&marks, w, h, &many)[..4], one_by_one[..]); + assert_eq!(in_areas(&many, w, h), in_areas(&rects, w, h)); + assert!(in_areas(&rects, w, h).contains(&true)); + } + + /// A document with a 40-point gray square in each of `n` 100-point areas side by side, `gap` + /// apart (the one in area `nudged` 20 points to the right), the areas, and the squares' ids. + fn squares(n: usize, gap: f64, nudged: Option) -> (Document, Vec, Vec) { + let mut doc = Document::new(100.0, 100.0); + let layer = doc.layers[0].id; + let (mut areas, mut ids) = (vec![], vec![]); + for i in 0..n { + let x = i as f64 * (100.0 + gap); + areas.push(Rect::new(x, 0.0, x + 100.0, 100.0)); + let x = if nudged == Some(i) { x + 20.0 } else { x }; + ids.push(square(&mut doc, layer, Rect::new(x + 30.0, 30.0, x + 70.0, 70.0))); + } + (doc, areas, ids) + } + + /// A gray square on `rect` added to `layer` of `doc`: its id. + fn square(doc: &mut Document, layer: vectorcraft_doc::NodeId, rect: Rect) -> vectorcraft_doc::NodeId { + filled(doc, layer, rect, 0.5) + } + + /// A rectangle on `rect` filled with `k` black added to `layer` of `doc`: its id. + fn filled(doc: &mut Document, layer: vectorcraft_doc::NodeId, rect: Rect, k: f32) -> vectorcraft_doc::NodeId { + let paint = vectorcraft_color::Paint::solid(vectorcraft_color::Color::cmyk(0.0, 0.0, 0.0, k)); + let appearance = vectorcraft_doc::Appearance { + items: vec![vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(paint))], + ..Default::default() + }; + let node = Node::path(doc.alloc_id(), vectorcraft_geom::shapes::rectangle(rect), appearance); + let id = node.id; + doc.insert(Some(layer), 0, node).unwrap(); + id + } + + /// A frame of `page`'s `areas`, each its own artboard. + fn frame_of<'a>(page: &'a Document, areas: &[Rect]) -> Frame<'a> { + let first = areas[0]; + Frame { page, page_rect: first, rect: first, whole: false, pages: vec![], more: areas[1..].iter().map(|r| (*r, *r)).collect() } + } + + /// The layers are drawn once for all the pages of a sheet, a fraction of a pixel apart as they + /// are, and the drawings are kept until the document changes. + #[test] + fn the_layers_are_drawn_once_for_the_pages_and_kept() { + let (doc, areas, _) = squares(4, 20.3, None); + let frame = frame_of(&doc, &areas); + let mut view = PageView::new(&frame); + assert_eq!(view.sheets.len(), 1); + let each = view.differences(&doc, areas[0], false); + assert_eq!(each.len(), 4); + assert!(each.iter().all(|d| d.any == 0.0), "{:?}", each.iter().map(|d| d.any).collect::>()); + assert_eq!(view.draws, 1, "one drawing for the four pages"); + assert!(compare(&frame, &mut view, &doc, false).is_ok()); + assert_eq!(view.difference_on_every_page(&doc, areas[0], true).any, 0.0); + assert_eq!(view.draws, 1, "the same document isn't drawn again"); + let (nudged, _, _) = squares(4, 20.3, Some(3)); + let each = view.differences(&nudged, areas[0], false); + assert_eq!(view.draws, 2); + assert!(each[3].solid > MAX_SOLID_DIFFERENCE && each[..3].iter().all(|d| d.any == 0.0)); + } + + /// Taking an object out of the layers has only the pages it lies on drawn again; the other + /// pages' drawings are kept for the document without it. + #[test] + fn a_removal_draws_again_only_the_pages_it_lies_on() { + let (page, areas, _) = squares(4, 20.3, None); + let (mut layers, _, _) = squares(4, 20.3, None); + let layer = layers.layers[0].id; + let extra = square(&mut layers, layer, Rect::new(2.0 * 120.3 + 5.0, 5.0, 2.0 * 120.3 + 25.0, 25.0)); + let frame = frame_of(&page, &areas); + let mut view = PageView::new(&frame); + let before = view.differences(&layers, areas[0], false); + assert!(before[2].any > 0.0); + let mut without = layers.clone(); + without.node_mut(extra).unwrap().visible = false; + let shares = view.weigh_without(&layers, &without, &[2]); + assert_eq!(view.draws, 2, "only the third page is drawn without it"); + assert!(shares.len() == 1 && shares[0].2 < shares[0].1, "{shares:?}"); + view.adopt(&without); + let after = view.differences(&without, areas[0], false); + assert_eq!(view.draws, 2, "the other pages' drawings are kept"); + let again = PageView::new(&frame).differences(&without, areas[0], false); + for (a, b) in after.iter().zip(&again) { + assert!((a.any - b.any).abs() < 1e-3 && (a.solid - b.solid).abs() < 1e-3); + } + assert_eq!(after[2].any, 0.0); + } + + /// Pages far apart are drawn on sheets of their own, and a long row of them on sheets no longer + /// than the limit. + #[test] + fn sheets_stay_within_their_limits() { + let (doc, areas, _) = squares(3, 5000.0, None); + assert_eq!(PageView::new(&frame_of(&doc, &areas)).sheets.len(), 3); + let (doc, areas, _) = squares(40, 0.0, None); + let frame = frame_of(&doc, &areas); + let mut view = PageView::new(&frame); + assert!(view.sheets.len() > 1); + assert!(view.sheets.iter().all(|s| s.rect.width() * s.scale <= MAX_SHEET_SIDE)); + assert!(view.differences(&doc, areas[0], false).iter().all(|d| d.any == 0.0)); + assert_eq!(view.draws, view.sheets.len()); + let before = view.draws; + assert_eq!(view.draw(&doc, &[0, 1]).len(), 2); + assert_eq!(view.draws, before + 2, "two pages of a long sheet are drawn on their own"); + } + + /// A page moved by a fraction of a pixel onto its sheet doesn't count the column its move took + /// off its artboard, where the layers have art past the artboard before it and the page has none. + #[test] + fn the_column_a_page_moved_onto_doesnt_count() { + // The second area starts 400.4 pixels from the first at 4 pixels a point: it moves 0.4 pixels + // to the left, and its first column starts at 100 points. + let areas = [Rect::new(0.0, 0.0, 100.0, 100.0), Rect::new(100.1, 0.0, 200.1, 100.0)]; + let mut page = Document::new(100.0, 100.0); + let layer = page.layers[0].id; + filled(&mut page, layer, areas[0], 1.0); + let mut layers = page.clone(); + let layer = layers.layers[0].id; + // Black reaching past the first artboard, into the space between the two. + filled(&mut layers, layer, Rect::new(99.0, 0.0, 100.1, 100.0), 1.0); + let frame = frame_of(&page, &areas); + let mut view = PageView::new(&frame); + assert_eq!(view.sheets.len(), 1); + let each = view.differences(&layers, areas[0], false); + assert!(each.iter().all(|d| d.any == 0.0), "{:?}", each.iter().map(|d| d.any).collect::>()); + assert_eq!(compare(&frame, &mut view, &layers, false), Ok(vec![])); + assert_eq!(view.colour_difference(1, &layers), 0.0); + } + + /// The drawings of two documents weighed in turn are both kept. + #[test] + fn the_drawings_of_two_documents_are_kept() { + let (doc, areas, _) = squares(4, 20.3, None); + let (other, _, _) = squares(4, 20.3, Some(1)); + let frame = frame_of(&doc, &areas); + let mut view = PageView::new(&frame); + for _ in 0..3 { + view.differences(&doc, areas[0], false); + view.differences(&other, areas[0], false); + } + assert_eq!(view.draws, 2, "each document is drawn once"); + } +} diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 9f7a8f4e72..dd18482662 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -1580,6 +1580,197 @@ fn a_pdf_of_its_second_artboard_is_compared_on_that_artboard() { assert!((e - 190.0).abs() < 1e-6 && (f - 20.0).abs() < 1e-6, "on the second artboard: {:?}", texts[0].xf); } +/// Two 100-point artboards, the second 50 below the first (art space, y up), as the editing data +/// lists them. +const TWO_BOARDS: &str = "%_/Document :\n%_/Dictionary :\n%_/Array :\n\ + %_/Dictionary :\n%_0 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_100 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\ + %_/Dictionary :\n%_0 -50 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_100 -150 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\ + %_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n"; + +/// The PDF part of a file with [`TWO_BOARDS`]: a page for each artboard in a row, the first with a +/// square at (10, 86), and the second with one at (`x`, `y`) of its own when given. +fn two_pages(second: Option<(f64, f64)>) -> Document { + let mut page = pdf_part(10.0, 86.0); + let mut board = page.artboards[0].clone(); + (board.id, board.rect) = (2, vectorcraft_geom::Rect::new(120.0, 0.0, 220.0, 100.0)); + page.artboards.push(board); + if let Some((x, y)) = second { + let other = pdf_part(120.0 + x, y); + let square = page.reid(&other.layers[0].children().unwrap()[0]); + let layer = page.layers[0].id; + page.insert(Some(layer), 1, square).unwrap(); + } + page +} + +/// The layers are compared with every page: art that they draw on the second artboard and its page +/// doesn't sends the file to its PDF part, as it would on the first. +#[test] +fn art_only_the_layers_draw_on_the_second_artboard_makes_the_file_come_in_as_its_pdf_part() { + // A 60-point square on the second artboard, 20 from its left and 20 down. + let big = "0 0 1 0 k\n20 -130 m\n80 -130 L\n80 -70 L\n20 -70 L\nf"; + let art = native(&(TWO_BOARDS.to_string() + &layer("Live", true, &square(10, 10)) + &layer("Second", true, big))); + let (d, w, read) = crate::layered_ai(&private(&art), two_pages(None), vec![], false, false, 1.0); + assert!(!read, "{w:?}"); + assert_ne!(names(&d), ["Live", "Second"], "{w:?}"); + assert!(w.iter().any(|w| w.contains("differs from the page's")), "{w:?}"); + // The same square on the first artboard, which its page doesn't draw either. + let big = "0 0 1 0 k\n20 20 m\n80 20 L\n80 80 L\n20 80 L\nf"; + let art = native(&(TWO_BOARDS.to_string() + &layer("Live", true, &square(10, 10)) + &layer("Second", true, big))); + let (_, w, read) = crate::layered_ai(&private(&art), two_pages(None), vec![], false, false, 1.0); + assert!(!read && w.iter().any(|w| w.contains("differs from the page's")), "{w:?}"); +} + +/// Art that the second page draws and the layers don't sends the file to its PDF part too. +#[test] +fn art_only_the_second_page_draws_makes_the_file_come_in_as_its_pdf_part() { + let art = native(&(TWO_BOARDS.to_string() + &layer("Live", true, &square(10, 10)))); + // A 60-point square on the second page, 20 from its left and 20 down. + let mut page = two_pages(None); + let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(140.0, 20.0, 200.0, 80.0)); + let paint = vectorcraft_color::Paint::solid(vectorcraft_color::Color::cmyk(0.0, 0.0, 0.0, 1.0)); + let appearance = vectorcraft_doc::Appearance { + items: vec![vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(paint))], + ..Default::default() + }; + let node = Node::path(page.alloc_id(), path, appearance); + let layer_id = page.layers[0].id; + page.insert(Some(layer_id), 1, node).unwrap(); + let (_, w, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(!read, "{w:?}"); + assert!(w.iter().any(|w| w.contains("differs from the page's")), "{w:?}"); +} + +/// A PDF saved with some of the artboards, not starting with the first, can hold any of the +/// others after it: its later pages aren't compared with the artboards that follow the first. +#[test] +fn the_later_pages_of_a_pdf_of_some_artboards_are_not_compared() { + // Four 100-point artboards side by side, 50 apart (art space, y up), a 4-point square on the + // first, second and fourth, and a 60-point square on the third. + let board = |x0: i32| { + format!( + "%_/Dictionary :\n%_{x0} 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_{} 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n", + x0 + 100 + ) + }; + let boards = format!( + "%_/Document :\n%_/Dictionary :\n%_/Array :\n{}{}{}{}%_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n", + board(0), + board(150), + board(300), + board(450) + ); + let big = "0 0 1 0 k\n320 20 m\n380 20 L\n380 80 L\n320 80 L\nf"; + let art = native(&(boards + &layer("Art", true, &(square(10, 10) + "\n" + &square(180, 50) + "\n" + big + "\n" + &square(460, 30))))); + // The PDF part: a page for the second artboard, then one for the fourth. + let mut pdf = pdf_part(30.0, 46.0); + let mut second = pdf.artboards[0].clone(); + (second.id, second.rect) = (2, vectorcraft_geom::Rect::new(120.0, 0.0, 220.0, 100.0)); + pdf.artboards.push(second); + let other = pdf_part(130.0, 66.0); + let fourth = pdf.reid(&other.layers[0].children().unwrap()[0]); + let layer_id = pdf.layers[0].id; + pdf.insert(Some(layer_id), 1, fourth).unwrap(); + let (d, w, read) = crate::layered_ai(&private(&art), pdf, vec![], false, false, 1.0); + assert!(read, "{w:?}"); + assert_eq!(d.artboards.len(), 4, "{w:?}"); +} + +/// Layers that draw each page's art on its artboard come in. +#[test] +fn layers_that_match_every_page_come_in() { + // A square on the second artboard, 50 from its left and 46 down, which its page draws too. + let second = "0 0 1 0 k\n50 -100 m\n54 -100 L\n54 -96 L\n50 -96 L\nf"; + let art = native(&(TWO_BOARDS.to_string() + &layer("Live", true, &square(10, 10)) + &layer("Second", true, second))); + let (d, w, read) = crate::layered_ai(&private(&art), two_pages(Some((50.0, 46.0))), vec![], false, false, 1.0); + assert!(read, "{w:?}"); + assert_eq!(names(&d), ["Live", "Second"], "{w:?}"); + assert!(w.is_empty(), "{w:?}"); +} + +/// Layers that draw each page's art come in from [`TWO_BOARDS`] changed to `boards`. +fn two_boards_come_in(boards: String) { + let second = "0 0 1 0 k\n50 -100 m\n54 -100 L\n54 -96 L\n50 -96 L\nf"; + let art = native(&(boards + &layer("Live", true, &square(10, 10)) + &layer("Second", true, second))); + let (d, w, read) = crate::layered_ai(&private(&art), two_pages(Some((50.0, 46.0))), vec![], false, false, 1.0); + assert!(read, "{w:?}"); + assert_eq!(names(&d), ["Live", "Second"], "{w:?}"); +} + +/// A first artboard up to half a point larger than its page is compared on an area of the page's +/// size. +#[test] +fn a_first_artboard_a_little_wider_than_its_page_is_compared_on_the_pages_size() { + two_boards_come_in(TWO_BOARDS.replace("%_100 0 /", "%_100.3 0 /")); +} + +/// A later artboard up to half a point smaller than its page is compared on an area of the page's +/// size. +#[test] +fn a_second_artboard_a_little_shorter_than_its_page_is_compared_on_the_pages_size() { + two_boards_come_in(TWO_BOARDS.replace("%_100 -150", "%_100 -149.7")); +} + +/// A text object the second page doesn't draw is left out even when the first page differs by more +/// than the comparison allows. +#[test] +fn an_unseen_text_object_on_the_second_page_is_weighed_while_the_first_page_differs() { + let doc = text_document(&[("Ghost\r", 0, (8200.0, 8330.0), (0.0, 0.0), 0.0)]); + let big = "0 0 1 0 k\n20 20 m\n80 20 L\n80 80 L\n20 80 L\nf"; + let art = native_with_text(&(TWO_BOARDS.to_string() + &layer("Art", true, &(square(10, 10) + "\n" + big + "\n" + &text_object(0)))), &doc); + // The first page draws the 60-point square in black. + let mut page = two_pages(None); + let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(20.0, 20.0, 80.0, 80.0)); + let paint = vectorcraft_color::Paint::solid(vectorcraft_color::Color::cmyk(0.0, 0.0, 0.0, 1.0)); + let appearance = vectorcraft_doc::Appearance { + items: vec![vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(paint))], + ..Default::default() + }; + let node = Node::path(page.alloc_id(), path, appearance); + let layer_id = page.layers[0].id; + page.insert(Some(layer_id), 1, node).unwrap(); + let (d, w, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(read, "{w:?}"); + let mut texts = vec![]; + d.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + texts.push(t.plain_text()); + } + }); + assert!(texts.is_empty(), "{w:?}"); + assert!(w.iter().any(|w| w.contains("doesn't draw")), "{w:?}"); +} + +/// A text object on the second artboard that its page doesn't draw is weighed as one on the first +/// is: it is taken out, unless its layer doesn't print. +#[test] +fn a_text_object_the_second_page_doesnt_draw_is_left_out_unless_its_layer_doesnt_print() { + // "Ghost" 38.5 down the second artboard (150 below the first's anchor in the canvas). + let doc = text_document(&[("Ghost\r", 0, (8200.0, 8330.0), (0.0, 0.0), 0.0)]); + let all_text = |d: &Document| { + let mut all = vec![]; + d.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + all.push(t.plain_text()); + } + }); + all + }; + let art = native_with_text(&(TWO_BOARDS.to_string() + &layer("Art", true, &(square(10, 10) + "\n" + &text_object(0)))), &doc); + let (d, w, read) = crate::layered_ai(&private(&art), two_pages(None), vec![], false, false, 1.0); + assert!(read, "{w:?}"); + assert!(all_text(&d).is_empty(), "{w:?}"); + assert!(w.iter().any(|w| w.contains("doesn't draw")), "{w:?}"); + // On a layer that shows and doesn't print, it stays. + let tips = layer("Tips", true, &text_object(0)).replace("1 1 1 1 0 0 1 0 79", "1 1 1 0 0 0 1 0 79"); + let art = native_with_text(&(TWO_BOARDS.to_string() + &layer("Art", true, &square(10, 10)) + &tips), &doc); + let (d, w, read) = crate::layered_ai(&private(&art), two_pages(None), vec![], false, false, 1.0); + assert!(read, "{w:?}"); + assert_eq!(names(&d), ["Art", "Tips"], "{w:?}"); + assert_eq!(all_text(&d), ["Ghost"], "{w:?}"); + assert!(!w.iter().any(|w| w.contains("doesn't draw")), "{w:?}"); +} + #[test] fn an_ai_file_that_cant_be_read_through_its_editing_data_keeps_its_pdf_part() { let pdf = pdf_part(10.0, 86.0); diff --git a/docs/mcp.md b/docs/mcp.md index 5dc19c6650..3f2b9333e4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -772,9 +772,14 @@ layer, even where the page doesn't draw it. A file whose editing data can't be d pattern fills, placed files or anything else the reader doesn't read on a layer that shows, or whose layers look different from its page, opens as before: an EPS as its printed page, a `.ai` file from its PDF content (where plain groups open ungrouped), with a warning saying why. Layers look different when they draw an object the page doesn't (or -miss one it draws), and, for an EPS whose page is the box of its art, when they print art outside it. A file whose -editing data is for a page of another size opens the same way, and its warning gives both sizes in points, with the -scale of the editing data's page to the file's page (1:10 for a tenth of its size) when their sides are in proportion. +miss one it draws), and, for an EPS whose page is the box of its art, when they print art outside it. When the PDF +content of a `.ai` has a page for each artboard, the layers are compared with each page on its artboard, until the +pages compared take 8,388,608 pixels at the comparison's scale (about 67 letter-size pages, or 4 when the PDF content +is only images) or number 128; when it has pages for some of the artboards, or its pages are cropped to the art, they +are compared with the first page only. An artboard, or the page of an EPS's editing data, whose sides are within half +a point of its page's is compared on an area of the page's size. A file whose editing data is for a page of another +size opens the same way, and its warning gives both sizes in points, with the scale of the editing data's page to the +file's page (1:10 for a tenth of its size) when their sides are in proportion. With `textAs: "outlines"` a `.ai` file whose type shows opens from its PDF content, which has the type's outlines. A PDF saved with Illustrator's editing data holds it in `AIPDFPrivateData` streams and opens from it as a `.ai` file does. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 92e4785728..da687715a4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1148,6 +1148,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A `.ai` opened from its editing data opens its Objects on Path groups live, with their path, their objects in order along it, Pivot and Rotate, and their art where the file draws it; a group whose spacing has been dragged, or with options an Objects on Path group doesn't hold, opens as a plain group (`crates/eps/src/import/ai/tests.rs`). In a `.ai` opened from its editing data, a path or type object with Offset Path, Outline Object or Outline Stroke on the whole object opens as itself with those effects live, in their order and shown or hidden; on a fill or stroke of type they stay on that fill or stroke. Offset Path keeps its Offset, Joins and Miter Limit, and Outline Stroke takes its width from the stroke. An Offset Path with a setting missing, out of range or not read keeps the drawn art, as does a path with a Path effect on one fill or stroke (`crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). A PDF page whose `UserUnit` (PDF 1.6) is above 1 opens at its size in points, its numbers times the `UserUnit` (one above 75,000 counts as 75,000), and `document.pdfInfo` gives its size and boxes in points too. A `.ai` whose editing data has its artboards in the units of such a page opens from that data at the page's size, with its layers, and when the layers can't be read its pages still take the artboard layout of the data, scaled the same way (part of #1482). + When the PDF content of a `.ai` has a page for each artboard, the layers are compared with every page on its artboard (until the pages compared take 8,388,608 pixels at the comparison's scale, about 67 letter-size pages, or number 128): art that only the layers or only a later page draws is handled as art that differs on the first page is, and a text object that a later page doesn't draw is left out unless its layer doesn't print (`crates/eps/src/import/tests_native.rs`). When the editing data of a `.ai` or EPS is for a page of another size than the file's, the warning that its layers weren't read gives both sizes in points, and the scale of the editing data's page to the file's page (1:10 for a tenth of its size) when their sides are in proportion (#2034; `crates/eps/src/import/tests_native.rs`). A `.ai`, or a PDF saved with Illustrator's editing data, whose editing data can't be decompressed opens from its PDF part with a warning that its layers weren't read and why, and an export or Save As to its own path asks first (`acknowledgeLoss`), as for a file whose layers the reader can't read (`crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). From 2ac1fa4ccef174f042fad4fc0abd4a3a13dd3e0d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 21:57:11 -0800 Subject: [PATCH 029/513] Layers: Layer Options keeps a Lock or Dim Images that was set before Template changes Setting Template in the dialog (the checkbox, or ui.dialog.set of template) also set Lock and Dim Images, replacing a value set in the dialog earlier. That value was then sent to every selected row, and ui.dialog.set gave different results depending on the order of its fields. A Lock or Dim Images set in the dialog now keeps its value when Template changes. --- crates/ui-egui/src/dialogs/layer_options.rs | 31 +++++++++++++++++++-- docs/mcp.md | 2 +- 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/layer_options.rs b/crates/ui-egui/src/dialogs/layer_options.rs index 6b3d294089..beb6321a50 100644 --- a/crates/ui-egui/src/dialogs/layer_options.rs +++ b/crates/ui-egui/src/dialogs/layer_options.rs @@ -53,7 +53,8 @@ pub(super) fn note_set(d: &mut Dialog, field: &str, value: &Value) { } /// Turns Template on or off. A template is locked and dims its images, and turning Template off -/// unlocks it and turns Dim Images off. For several rows, OK sends Lock and Dim Images only when +/// unlocks it and turns Dim Images off; a Lock or Dim Images that was set in the dialog keeps its +/// value. For several rows, OK sends Lock and Dim Images only when /// they are set in the dialog. `layer.setProps` then locks each row that becomes a template and /// dims it to 50%, unless a percentage is set in the dialog, so the dialog shows 50%; it unlocks /// each row that stops being a template and stops dimming it. @@ -61,8 +62,11 @@ pub(super) fn note_set(d: &mut Dialog, field: &str, value: &Value) { /// the dialog show the first row's values again. fn set_template(d: &mut Dialog, on: bool) { choose(d, "template", json!(on)); - d.fields.insert("locked".into(), json!(on)); - d.fields.insert("dimImages".into(), json!(on)); + for key in ["locked", "dimImages"] { + if !is_set(d, key) { + d.fields.insert(key.into(), json!(on)); + } + } let Some(opened) = d.fields.get(OPENED).cloned() else { return; }; @@ -584,6 +588,27 @@ mod tests { assert_eq!(p, json!({"template": false, "dimImages": 40.0, "ids": [first.0, second.0]})); } + /// Lock and Dim Images set in the dialog stay as set when Template is set after them, so + /// `ui.dialog.set` gives the same result in either order. + #[test] + fn template_keeps_lock_and_dim_images_that_were_set() { + let mut app = app(); + let (first, second) = two_layers(&mut app); + set(&mut app, "locked", json!(false)); + set(&mut app, "dimImages", json!(false)); + set(&mut app, "template", json!(true)); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(d.bool("template") && !d.bool("locked") && !d.bool("dimImages")); + let by_template_last = params(d).1; + assert_eq!(by_template_last, json!({"template": true, "locked": false, "dimImages": false, "ids": [first.0, second.0]})); + app.run("ui.layerOptions", json!({"ids": [first.0, second.0]})).unwrap(); + draw(&mut app); + set(&mut app, "template", json!(true)); + set(&mut app, "locked", json!(false)); + set(&mut app, "dimImages", json!(false)); + assert_eq!(params(app.ui.dialog.as_ref().unwrap()).1, by_template_last); + } + #[test] fn new_layer_options_make_a_layer_and_objects_get_name_show_and_lock() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 3f2b9333e4..6f3fc30330 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2608,7 +2608,7 @@ and `layerRows`, the rows highlighted in the panel. - **Dialogs and panel state** (control channel and the app's MCP): `ui.layerOptions {ids?}` and `ui.newLayer {sublayer?}` open Layer Options (dialog `layerOptions`: name, color, template, locked, visible, printable, preview, dimImages, dimPercent; OK is one undo step; `ui.dialog.set` of `template` also sets `locked` and `dimImages`, as the - checkbox does; for several `ids` the dialog shows the first row's settings, and OK sends only the fields set with a + checkbox does, except one that was set before it; for several `ids` the dialog shows the first row's settings, and OK sends only the fields set with a control or `ui.dialog.set`; Cmd/Ctrl+Alt+L runs `ui.newLayer` for a new layer), `ui.layersPanelOptions` opens Panel Options (`layersPanelOptions`: layersOnly, locateSelected, rowSize small|medium|large|other, otherSize, thumbLayers, thumbGroups, thumbObjects), and `ui.layersExpand {ids?, open?}` opens or closes rows as their triangles do (Alt-click: everything inside). From 4aa8a8b0c8e573a070e6274bca70e80dac27cccc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 23:36:30 -0800 Subject: [PATCH 030/513] Layers: Template always locks the layer in Layer Options Template sets Lock again even when Lock was set in the dialog before it, so a template layer is always locked. Only a Dim Images set before Template keeps its value. --- crates/ui-egui/src/dialogs/layer_options.rs | 52 +++++++++++---------- docs/mcp.md | 2 +- 2 files changed, 28 insertions(+), 26 deletions(-) diff --git a/crates/ui-egui/src/dialogs/layer_options.rs b/crates/ui-egui/src/dialogs/layer_options.rs index beb6321a50..d40d61c6f5 100644 --- a/crates/ui-egui/src/dialogs/layer_options.rs +++ b/crates/ui-egui/src/dialogs/layer_options.rs @@ -53,19 +53,17 @@ pub(super) fn note_set(d: &mut Dialog, field: &str, value: &Value) { } /// Turns Template on or off. A template is locked and dims its images, and turning Template off -/// unlocks it and turns Dim Images off; a Lock or Dim Images that was set in the dialog keeps its -/// value. For several rows, OK sends Lock and Dim Images only when -/// they are set in the dialog. `layer.setProps` then locks each row that becomes a template and +/// unlocks it and turns Dim Images off; a Dim Images that was set in the dialog keeps its value. +/// For several rows, OK sends Lock and Dim Images only when they are set in the dialog. `layer.setProps` then locks each row that becomes a template and /// dims it to 50%, unless a percentage is set in the dialog, so the dialog shows 50%; it unlocks /// each row that stops being a template and stops dimming it. /// When Template is set back to the first row's value, Lock and Dim Images that were not set in /// the dialog show the first row's values again. fn set_template(d: &mut Dialog, on: bool) { choose(d, "template", json!(on)); - for key in ["locked", "dimImages"] { - if !is_set(d, key) { - d.fields.insert(key.into(), json!(on)); - } + d.fields.insert("locked".into(), json!(on)); + if !is_set(d, "dimImages") { + d.fields.insert("dimImages".into(), json!(on)); } let Some(opened) = d.fields.get(OPENED).cloned() else { return; @@ -588,25 +586,29 @@ mod tests { assert_eq!(p, json!({"template": false, "dimImages": 40.0, "ids": [first.0, second.0]})); } - /// Lock and Dim Images set in the dialog stay as set when Template is set after them, so - /// `ui.dialog.set` gives the same result in either order. + /// A Dim Images set in the dialog stays as set when Template is set after it, so + /// `ui.dialog.set` gives the same result in either order. Template still locks the layers. #[test] - fn template_keeps_lock_and_dim_images_that_were_set() { - let mut app = app(); - let (first, second) = two_layers(&mut app); - set(&mut app, "locked", json!(false)); - set(&mut app, "dimImages", json!(false)); - set(&mut app, "template", json!(true)); - let d = app.ui.dialog.as_ref().unwrap(); - assert!(d.bool("template") && !d.bool("locked") && !d.bool("dimImages")); - let by_template_last = params(d).1; - assert_eq!(by_template_last, json!({"template": true, "locked": false, "dimImages": false, "ids": [first.0, second.0]})); - app.run("ui.layerOptions", json!({"ids": [first.0, second.0]})).unwrap(); - draw(&mut app); - set(&mut app, "template", json!(true)); - set(&mut app, "locked", json!(false)); - set(&mut app, "dimImages", json!(false)); - assert_eq!(params(app.ui.dialog.as_ref().unwrap()).1, by_template_last); + fn template_keeps_dim_images_that_was_set() { + for dim_first in [true, false] { + let mut app = app(); + let (first, second) = two_layers(&mut app); + if dim_first { + set(&mut app, "dimImages", json!(false)); + set(&mut app, "template", json!(true)); + } else { + set(&mut app, "template", json!(true)); + set(&mut app, "dimImages", json!(false)); + } + let d = app.ui.dialog.as_ref().unwrap(); + assert!(d.bool("template") && d.bool("locked") && !d.bool("dimImages"), "dim first: {dim_first}"); + assert_eq!(params(d).1, json!({"template": true, "dimImages": false, "ids": [first.0, second.0]}), "dim first: {dim_first}"); + super::super::confirm(&mut app).unwrap(); + for id in [first, second] { + let n = layer(&app, id); + assert!(n.locked && matches!(n.kind, NodeKind::Layer { template: true, dim_images: None, .. }), "{id:?}, dim first: {dim_first}"); + } + } } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 6f3fc30330..681eb58dcd 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2608,7 +2608,7 @@ and `layerRows`, the rows highlighted in the panel. - **Dialogs and panel state** (control channel and the app's MCP): `ui.layerOptions {ids?}` and `ui.newLayer {sublayer?}` open Layer Options (dialog `layerOptions`: name, color, template, locked, visible, printable, preview, dimImages, dimPercent; OK is one undo step; `ui.dialog.set` of `template` also sets `locked` and `dimImages`, as the - checkbox does, except one that was set before it; for several `ids` the dialog shows the first row's settings, and OK sends only the fields set with a + checkbox does, except a Dim Images set before it; for several `ids` the dialog shows the first row's settings, and OK sends only the fields set with a control or `ui.dialog.set`; Cmd/Ctrl+Alt+L runs `ui.newLayer` for a new layer), `ui.layersPanelOptions` opens Panel Options (`layersPanelOptions`: layersOnly, locateSelected, rowSize small|medium|large|other, otherSize, thumbLayers, thumbGroups, thumbObjects), and `ui.layersExpand {ids?, open?}` opens or closes rows as their triangles do (Alt-click: everything inside). From 40318753dbac8d5ea4b86473425725ad2f3d17a0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 23:21:57 -0800 Subject: [PATCH 031/513] Blends: Convert on a replaced spine changes only its handles Convert to Smooth or Corner on a blend whose spine came from Replace Spine stored key anchors with the converted spine, so the spine's points then moved onto the key centers. It now changes only the spine's handles: the points stay where they are and the keys stay spread along the spine. Direct Selection's spine conversion and the other spine edits are unchanged. --- crates/engine/src/cmd/path.rs | 23 ++++++++++++----- crates/engine/src/tests/blendspine.rs | 36 +++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index fb63bf12ec..f1bc3e501a 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -112,7 +112,7 @@ pub fn specs() -> Vec { "Convert Anchor Points", [], None, - "{to: \"corner\"|\"smooth\"} convert the direct-selected anchors (all anchors of fully selected paths, every point of a selected blend's spine) as one undo step: corner retracts both handles, smooth pulls handles in line with the neighbours (smooth anchors keep theirs)", + "{to: \"corner\"|\"smooth\"} convert the direct-selected anchors (all anchors of fully selected paths, every point of a selected blend's spine; a spine from Replace Spine changes only its handles, its points and the keys' spread along it staying as they are) as one undo step: corner retracts both handles, smooth pulls handles in line with the neighbours (smooth anchors keep theirs)", has_selection, convert_anchors ), @@ -1155,11 +1155,7 @@ fn convert_anchors(s: &mut Session, p: &Value) -> Result { } } } - for id in &blends { - let Some(NodeKind::Blend { children, spec }) = d.node_mut(*id).map(|n| &mut n.kind) else { continue }; - let Some((mut path, anchors)) = vectorcraft_doc::live::pin_spine(children, spec) else { continue }; - let pinned = path.clone(); - let Some(sp) = path.subpaths.first_mut() else { continue }; + let convert = |sp: &mut SubPath| { for ai in 0..sp.anchors.len() { if smooth { sp.smooth_anchor(ai); @@ -1167,6 +1163,21 @@ fn convert_anchors(s: &mut Session, p: &Value) -> Result { a.retract(); } } + }; + for id in &blends { + let Some(NodeKind::Blend { children, spec }) = d.node_mut(*id).map(|n| &mut n.kind) else { continue }; + // A spine from Replace Spine keeps its points and its keys spread along it: only the + // handles change, and the keys are not pinned to points. + if vectorcraft_doc::live::blend_spine(children, spec).is_some_and(|(_, anchors)| anchors.is_none()) { + if let Some(sp) = spec.spine.as_mut().and_then(|p| p.subpaths.first_mut()) { + convert(sp); + } + continue; + } + let Some((mut path, anchors)) = vectorcraft_doc::live::pin_spine(children, spec) else { continue }; + let pinned = path.clone(); + let Some(sp) = path.subpaths.first_mut() else { continue }; + convert(sp); // A spine the conversion leaves as it was stays as the blend has it. if path != pinned { spec.key_anchors = anchors.iter().map(|a| u32::try_from(*a).unwrap_or(u32::MAX)).collect(); diff --git a/crates/engine/src/tests/blendspine.rs b/crates/engine/src/tests/blendspine.rs index 0ab2aac5b6..5db598a197 100644 --- a/crates/engine/src/tests/blendspine.rs +++ b/crates/engine/src/tests/blendspine.rs @@ -144,6 +144,42 @@ fn converting_anchors_of_a_selected_blend_converts_its_spine() { assert_eq!(spec(&s, g).spine.unwrap().subpaths[0].anchors[1], middle, "one undo step"); } +/// Converting the points of a blend whose spine came from Replace Spine changes only the spine's +/// handles: its points stay where they are, the keys are not pinned to points, and the steps stay +/// spread along the spine instead of the spine's ends moving onto the keys. +#[test] +fn converting_anchors_of_a_replaced_spine_changes_only_its_handles() { + let mut s = session(); + let (_, _, g) = blend(&mut s); + let spine = id_of(&s.execute("path.create", &json!({"d": "M100 300 L200 200 L300 300"})).unwrap()); + s.execute("select.set", &json!({"ids": [g.0, spine.0]})).unwrap(); + s.execute("object.blend.replaceSpine", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + let points = |s: &Session| spec(s, g).spine.unwrap().subpaths[0].anchors.iter().map(|a| a.p).collect::>(); + let before = points(&s); + let ends = |s: &Session| { + let st = steps(s, g); + (center(&st[0]), center(&st[st.len() - 1])) + }; + let ends_before = ends(&s); + s.execute("path.convertAnchors", &json!({"to": "smooth"})).unwrap(); + let sp = spec(&s, g); + assert!(sp.key_anchors.is_empty(), "{:?}", sp.key_anchors); + assert_eq!(points(&s), before, "the spine's points stay put"); + let middle = sp.spine.as_ref().unwrap().subpaths[0].anchors[1]; + assert!(middle.has_in() && middle.has_out(), "{middle:?}"); + assert_eq!(ends(&s), ends_before, "the end steps stay at the spine's ends"); + assert!(center(&steps(&s, g)[1]).distance(Point::new(200.0, 200.0)) < 1e-6, "the step stays on the spine"); + + s.execute("path.convertAnchors", &json!({"to": "corner"})).unwrap(); + let sp = spec(&s, g); + assert!(sp.key_anchors.is_empty(), "{:?}", sp.key_anchors); + assert!(sp.spine.unwrap().subpaths[0].anchors.iter().all(|a| !a.has_in() && !a.has_out())); + assert_eq!(points(&s), before); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(spec(&s, g).spine.unwrap().subpaths[0].anchors[1], middle, "one undo step"); +} + #[test] fn moving_a_key_point_moves_the_key_and_the_other_way_round() { let mut s = session(); From 92640179e504c0739f246bdbc2a8edd539c0b726 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 23:22:11 -0800 Subject: [PATCH 032/513] Type: Select All in a threaded frame selects the whole story While the Type tool edits a frame of threaded text, Select All selects the text of every frame of the story, highlighted in each frame. The tool edits the first frame that holds text. - Typing, Delete and Cut replace the whole story as one undo step (`text.editRange` takes `clear`, the other frames whose text goes). - Copy and Cut take the whole story (`text.getRange {id, story: true}`). - Fills and strokes, `type.step`, `appearance.copyFrom`, the Character, Paragraph, OpenType and text style panels, the Tabs panel's tab stops, the font menus and the Justification dialog act on every frame's text (`text.setRangeStyle {id, story: true}` styles them in one edit). - A caret move, a click or a word or paragraph selection ends it. Select All in unthreaded type is unchanged. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/appearance.rs | 46 ++++-- crates/engine/src/cmd/paint.rs | 35 +++-- crates/engine/src/cmd/select.rs | 27 +++- crates/engine/src/cmd/textedit.rs | 155 +++++++++++++++---- crates/engine/src/cmd/threads.rs | 8 + crates/engine/src/tests/textedit.rs | 122 +++++++++++++++ crates/tools/src/text.rs | 60 ++++++- crates/tools/src/text/tool.rs | 41 ++++- crates/ui-egui/src/dialogs/justification.rs | 6 +- crates/ui-egui/src/font_menu.rs | 6 + crates/ui-egui/src/panels/character.rs | 52 ++++++- crates/ui-egui/src/panels/character/tests.rs | 42 +++++ crates/ui-egui/src/panels/opentype.rs | 11 +- crates/ui-egui/src/panels/paragraph.rs | 42 ++++- crates/ui-egui/src/panels/tabs.rs | 7 +- crates/ui-egui/src/panels/text_styles.rs | 16 +- docs/mcp.md | 10 +- docs/target-app-parity.md | 2 +- 18 files changed, 598 insertions(+), 90 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 178a4ec545..990a4d97de 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -1087,15 +1087,25 @@ fn copy_from(s: &mut Session, p: &Value) -> Result { s.eyedropper_sample = Some(node); } let range = range.filter(|(id, _, _)| targets.contains(id)); + // The highlighted characters' type objects and ranges: after Select All in threaded text, all + // the text of every frame of the story. + let story = super::textedit::editing_story(s); + let ranges: Vec<(NodeId, Option<(usize, usize)>)> = match range { + Some((id, _, _)) if story.contains(&id) => story.iter().map(|f| (*f, None)).collect(), + Some((id, start, end)) => vec![(id, Some((start, end)))], + None => vec![], + }; // Character styles cannot represent object transparency. Refuse before even changing // paint defaults; applying it to the object would also alter the unselected characters. - if let Some((id, _, _)) = range.filter(|_| attrs.appearance.transparency) { - let target = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?; - if picked.opacity != 1.0 || picked.blend != BlendMode::Normal || target.opacity != 1.0 || target.blend != BlendMode::Normal { - return Err(bad( - C, - "object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object", - )); + if attrs.appearance.transparency { + for (id, _) in &ranges { + let target = s.doc()?.doc.node(*id).ok_or(EngineError::NoNode(*id))?; + if picked.opacity != 1.0 || picked.blend != BlendMode::Normal || target.opacity != 1.0 || target.blend != BlendMode::Normal { + return Err(bad( + C, + "object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object", + )); + } } } if !reverse { @@ -1104,19 +1114,23 @@ fn copy_from(s: &mut Session, p: &Value) -> Result { if targets.is_empty() || attrs.is_empty() { return Ok(json!({ "ids": [] })); } - if let Some((id, start, end)) = range { + if !ranges.is_empty() { + let ids: Vec = ranges.iter().map(|(f, _)| *f).collect(); let before = s.doc()?.doc.clone(); super::overprint::edit_counted(s, "Eyedropper", |d| { - let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) }; - let placed = picked.placed(Some(t.local_bounds())); - vectorcraft_text::edit::style_range(&mut t.runs, start, end, |st| picked.run(st, &placed, &attrs)); - if let Some((_, para)) = picked.text.as_ref().filter(|_| attrs.paragraph) { - t.edit_paras(Some(t.paragraphs_in(start, end)), |p| *p = para.clone()); + for &(id, range) in &ranges { + let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) }; + let (start, end) = range.unwrap_or((0, vectorcraft_text::edit::runs_len(&t.runs))); + let placed = picked.placed(Some(t.local_bounds())); + vectorcraft_text::edit::style_range(&mut t.runs, start, end, |st| picked.run(st, &placed, &attrs)); + if let Some((_, para)) = picked.text.as_ref().filter(|_| attrs.paragraph) { + t.edit_paras(Some(t.paragraphs_in(start, end)), |p| *p = para.clone()); + } + super::typecmd::refresh_bounds(t); } - super::typecmd::refresh_bounds(t); - Ok(count_changed(d, &before, &[id])) + Ok(count_changed(d, &before, &ids)) })?; - return Ok(json!({ "ids": [id.0] })); + return Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>() })); } // When every target comes out as it was, the document and its undo history stay as they are. let before = s.doc()?.doc.clone(); diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index e53b9b8f3a..3abe60b541 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -433,29 +433,36 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) && let Some((id, a, b)) = super::textedit::editing_range(s)? && a != b { + // After Select All in threaded text, every frame's text takes it. + let story = super::textedit::editing_story(s); + let ranges: Vec<(NodeId, usize, usize)> = + if story.is_empty() { vec![(id, a, b)] } else { story.iter().map(|f| (*f, 0, usize::MAX)).collect() }; + let ids: Vec = ranges.iter().map(|(f, _, _)| *f).collect(); // When the type comes out as it was, the document and its undo history stay as they are. let before = s.doc()?.doc.clone(); super::overprint::edit_counted(s, if fill { "Fill Color" } else { "Stroke Color" }, |d| { - let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) }; - let (xf, lb) = (t.xf, t.local_bounds()); - vectorcraft_text::edit::style_range(&mut t.runs, a, b, |st| { - if fill { - st.fill = place_run_paint(&paint, p, xf, lb); - } else { - if !paint.is_none() { - run_stroke_weight(st); + for &(id, a, b) in &ranges { + let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) }; + let (xf, lb) = (t.xf, t.local_bounds()); + vectorcraft_text::edit::style_range(&mut t.runs, a, b, |st| { + if fill { + st.fill = place_run_paint(&paint, p, xf, lb); + } else { + if !paint.is_none() { + run_stroke_weight(st); + } + st.stroke = place_run_paint(&paint, p, xf, vectorcraft_doc::appearance::stroke_paint_bounds(lb, st.stroke_width)); } - st.stroke = place_run_paint(&paint, p, xf, vectorcraft_doc::appearance::stroke_paint_bounds(lb, st.stroke_width)); - } - }); - super::typecmd::refresh_bounds(t); - Ok(super::appearance::count_changed(d, &before, &[id])) + }); + super::typecmd::refresh_bounds(t); + } + Ok(super::appearance::count_changed(d, &before, &ids)) })?; if focus { s.fill_active = fill; } s.remember_paint(&paint); - return Ok(json!({"objects": 1})); + return Ok(json!({"objects": ids.len()})); } // Resolve the requested targets before mutating defaults or the active proxy. let item = item_target(s, p, cmd)?.of_kind(s, fill); diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index 2f04b95c69..a851660245 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -20,7 +20,7 @@ pub fn specs() -> Vec { "All", ["Select"], Some("Cmd+A"), - "{} → {count}; while the Type tool edits text, all of that text instead → {editing, start, end} (byte offsets)", + "{} → {count}; while the Type tool edits text, all of that text instead → {editing, start, end} (byte offsets); in a frame of threaded text, the whole story: the tool edits the thread's first frame that holds text (selected when it was not) with the text of every frame selected → {editing, start, end, story: [id…] (the frames in thread order)}", has_doc, all ), @@ -271,6 +271,31 @@ fn all(s: &mut Session, _: &Value) -> Result { // While the Type tool edits text, Select All takes all of that text and leaves the art // selection as it is (Illustrator: text cursor in a text object). if s.tool_wants_text() { + // In a frame of threaded text, the whole story: the tool edits its first frame that holds + // text with every frame's text selected, and that frame is selected when it was not. + let editing = s.tool_options()["editing"].as_u64().map(NodeId); + let story = match editing { + Some(id) => super::threads::story_of(&s.doc()?.doc, id), + None => vec![], + }; + if let Some(&first) = story.first() { + let d = &s.doc()?.doc; + let holds_text = |f: &NodeId| matches!(d.node(*f).map(|n| &n.kind), Some(NodeKind::Text(t)) if t.runs.iter().any(|r| !r.text.is_empty())); + let first = story.iter().copied().find(holds_text).unwrap_or(first); + super::textedit::editing_range(s)?; + let ids: Vec = story.iter().map(|id| id.0).collect(); + s.set_tool_option("selectAll", &json!({ "story": ids, "editing": first.0 })); + let st = s.doc()?; + let selected = std::iter::successors(Some(first), |c| st.doc.parent_of(*c)).any(|c| st.selection.contains(c)); + if !selected { + s.select(|_, sel| sel.set([first]))?; + } + let end = match s.doc()?.doc.node(first).map(|n| &n.kind) { + Some(NodeKind::Text(t)) => t.plain_text().len(), + _ => 0, + }; + return Ok(json!({ "editing": first.0, "start": 0, "end": end, "story": ids })); + } s.set_tool_option("selectAll", &json!(true)); let editing = s.tool_options()["editing"].clone(); let id = editing.as_u64().map(NodeId); diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index ac0af58671..f0a331b0a7 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -21,7 +21,7 @@ pub fn specs() -> Vec { "Edit Text", [], None, - "{id, start: byte, end: byte, insert?: string, runs?: [{text, style}]} replace bytes start..end of the plain text (inserted text takes the replaced text's style unless styled `runs` are given) → {id, caret}", + "{id, start: byte, end: byte, insert?: string, runs?: [{text, style}], clear?: [id…] (other type objects whose whole text goes in the same edit, as when typing replaces a threaded story that Select All selected)} replace bytes start..end of the plain text (inserted text takes the replaced text's style unless styled `runs` are given) → {id, caret}", has_doc, edit_range ), @@ -39,7 +39,7 @@ pub fn specs() -> Vec { "Character", [], None, - "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", 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\", …], featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; 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; 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)} 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, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", 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\", …], featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; 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; 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)} 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 ), @@ -57,7 +57,7 @@ pub fn specs() -> Vec { "Get Text Range", [], None, - "{id, start?, end?, effective?: bool = false} → {text, runs: [{text, style}], length}; effective uses document-point size/leading/baseline shift and transformed horizontal scale; default returns stored local styles for rich-text copying", + "{id, start?, end?, effective?: bool = false, story?: bool = false (the whole text of the threaded story `id` is a frame of, its frames in thread order; no `start` or `end`)} → {text, runs: [{text, style}], length}; effective uses document-point size/leading/baseline shift and transformed horizontal scale; default returns stored local styles for rich-text copying", has_doc, get_range ), @@ -253,7 +253,16 @@ fn edit_range(s: &mut Session, p: &Value) -> Result { Some(v) => Some(serde_json::from_value(v.clone()).map_err(|e| bad(C, format!("bad `runs`: {e}")))?), }; let insert = str_param(p, "insert").unwrap_or("").to_string(); + let clear = clear_param(s, p, id, C)?; let caret = s.edit("Typing", |d, _| { + for other in &clear { + let t = text_mut(d, *other).ok_or(EngineError::NoNode(*other))?; + let len = edit::runs_len(&t.runs); + t.splice_paras(0, len, ""); + edit::replace_range(&mut t.runs, 0, len, ""); + t.ruby_after_replace(0, len, 0); + refresh_bounds(t); + } let t = text_mut(d, id).ok_or(EngineError::NoNode(id))?; // Paragraph styles follow the edit: a split paragraph's new one continues its style, a // merge keeps the first paragraph's. @@ -274,6 +283,30 @@ fn edit_range(s: &mut Session, p: &Value) -> Result { Ok(json!({"id": id.0, "caret": caret})) } +/// The `clear` param of `text.editRange`: other type objects whose text the edit removes, each +/// once. An error when it is not a list of ids of type objects other than `id`. +fn clear_param(s: &Session, p: &Value, id: NodeId, c: &str) -> Result> { + let ids = match p.get("clear") { + None | Some(Value::Null) => return Ok(vec![]), + Some(Value::Array(ids)) => ids, + Some(v) => return Err(bad(c, format!("`clear` must be a list of type object ids, not {v}"))), + }; + let mut out = vec![]; + for v in ids { + let other = v.as_u64().map(NodeId).ok_or_else(|| bad(c, format!("`clear` must be a list of type object ids, not {v}")))?; + if other == id { + return Err(bad(c, "`clear` must not list `id`")); + } + if !matches!(s.doc()?.doc.node(other).map(|n| &n.kind), Some(NodeKind::Text(_))) { + return Err(bad(c, format!("`clear` must list type objects; {} is not one", other.0))); + } + if !out.contains(&other) { + out.push(other); + } + } + Ok(out) +} + fn start_list(s: &mut Session, p: &Value) -> Result { const C: &str = "text.startList"; let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?; @@ -306,6 +339,9 @@ fn start_list(s: &mut Session, p: &Value) -> Result { fn get_range(s: &mut Session, p: &Value) -> Result { let id = id_param(p, "id").ok_or_else(|| bad("text.getRange", "missing `id`"))?; + if switch_or(p, "story", false, "text.getRange")? { + return get_story(s, p, id); + } let t = text_ref(s, id)?; let len = edit::runs_len(&t.runs); let (a, b) = range_of(p, len, "text.getRange")?; @@ -319,6 +355,31 @@ fn get_range(s: &mut Session, p: &Value) -> Result { Ok(json!({"text": text, "runs": runs, "length": len})) } +/// `text.getRange {id, story: true}`: the whole text of the story `id` is a frame of, its thread's +/// frames in order (`id` alone when it is in no thread). +fn get_story(s: &mut Session, p: &Value, id: NodeId) -> Result { + const C: &str = "text.getRange"; + if ["start", "end"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { + return Err(bad(C, "`story` takes the whole story: give no `start` or `end`")); + } + let effective = switch_or(p, "effective", false, C)?; + let story = super::threads::story_of(&s.doc()?.doc, id); + let frames = if story.is_empty() { vec![id] } else { story }; + let mut runs = vec![]; + for f in frames { + let t = text_ref(s, f)?; + for mut run in edit::slice_runs(&t.runs, 0, edit::runs_len(&t.runs)) { + if effective { + run.style = t.effective_char_style(&run.style).ok_or_else(|| bad(C, "text transform is collapsed or unrepresentable"))?; + } + runs.push(run); + } + } + let text: String = runs.iter().map(|r| r.text.as_str()).collect(); + let len = text.len(); + Ok(json!({"text": text, "runs": runs, "length": len})) +} + /// Keep `st`'s font style when its family has it, else take the family's closest one: a family /// whose styles are numbered (W3, W6) has no Regular (#4128). A family that isn't installed keeps /// the style as it is. @@ -913,37 +974,56 @@ fn set_range_style(s: &mut Session, p: &Value) -> Result { _ => return Err(bad(C, "missing `id`: give one, or select one type object")), }, }; - let mut change = CharChange::parse(p, C, &s.doc()?.doc.setup)?; - super::paint::check_keep_model(p, C)?; - change.store_colors(s, p); - if change.is_empty() { - return Err(bad(C, "nothing to change")); + let story = switch_or(p, "story", false, C)?; + if story && ["start", "end"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { + return Err(bad(C, "`story` styles the whole story: give no `start` or `end`")); } - let protect = s.prefs.missing_glyph_protection && (change.font.is_some() || change.style.is_some()); - let t = text_ref(s, id)?; - change.localize(&t, C)?; - let (a, b) = range_of(p, edit::runs_len(&t.runs), C)?; + let frames = match super::threads::story_of(&s.doc()?.doc, id) { + all if story && !all.is_empty() => all, + _ => vec![id], + }; + // Each frame's change (sizes are in its own text space) and range. + let mut parts = Vec::with_capacity(frames.len()); + for f in frames { + let mut change = CharChange::parse(p, C, &s.doc()?.doc.setup)?; + super::paint::check_keep_model(p, C)?; + change.store_colors(s, p); + if change.is_empty() { + return Err(bad(C, "nothing to change")); + } + let t = text_ref(s, f)?; + change.localize(&t, C)?; + let (a, b) = if story { (0, edit::runs_len(&t.runs)) } else { range_of(p, edit::runs_len(&t.runs), C)? }; + parts.push((f, change, a, b)); + } + let sets_font = parts.first().is_some_and(|(_, change, _, _)| change.font.is_some() || change.style.is_some()); + let protect = s.prefs.missing_glyph_protection && sets_font; // The fonts the styled characters are set in, for the warning. let mut set = std::collections::BTreeSet::new(); - let sets_font = change.font.is_some() || change.style.is_some(); let n = s.edit("Character", |d, _| { - let t = text_mut(d, id).ok_or(EngineError::NoNode(id))?; - if a == b && !t.plain_text().is_empty() { - // An empty range inside text styles nothing (Illustrator keeps it for the next typing). - return Ok(t.runs.len()); + let mut n = 0; + for (f, change, a, b) in &parts { + let (a, b) = (*a, *b); + let t = text_mut(d, *f).ok_or(EngineError::NoNode(*f))?; + if a == b && !t.plain_text().is_empty() { + // An empty range inside text styles nothing (Illustrator keeps it for the next typing). + n = if *f == id { t.runs.len() } else { n }; + continue; + } + let before = protect.then(|| t.runs.clone()); + edit::style_range(&mut t.runs, a, b, |st| change.apply(st)); + if let Some(before) = before { + protect_missing_glyphs(&before, &mut t.runs); + } + if sets_font { + // Empty text has one run, which the empty range styles. + let styled = if a == b { t.runs.clone() } else { edit::slice_runs(&t.runs, a, b) }; + set.extend(styled.iter().map(|r| super::fonts::font_of(&r.style))); + } + refresh_bounds(t); + n = if *f == id { t.runs.len() } else { n }; } - let before = protect.then(|| t.runs.clone()); - edit::style_range(&mut t.runs, a, b, |st| change.apply(st)); - if let Some(before) = before { - protect_missing_glyphs(&before, &mut t.runs); - } - if sets_font { - // Empty text has one run, which the empty range styles. - let styled = if a == b { t.runs.clone() } else { edit::slice_runs(&t.runs, a, b) }; - set.extend(styled.iter().map(|r| super::fonts::font_of(&r.style))); - } - refresh_bounds(t); - Ok(t.runs.len()) + Ok(n) })?; let mut out = json!({"id": id.0, "runs": n}); if let Some(w) = super::fonts::set_font_warning(set) { @@ -1317,8 +1397,20 @@ pub(crate) fn editing_range(s: &mut Session) -> Result Vec { + let o = s.tool_options(); + let Some(id) = o.get("editing").and_then(Value::as_u64).map(NodeId) else { return vec![] }; + if !o.get("story").and_then(Value::as_array).is_some_and(|ids| !ids.is_empty()) { + return vec![]; + } + s.active().map(|st| super::threads::story_of(&st.doc, id)).unwrap_or_default() +} + /// The text ranges a type shortcut changes: the range of `id`, else all the text of the type -/// objects in `ids`, else the text the Type tool has selected, else all the text of every selected +/// objects in `ids`, else the text the Type tool has selected (all the text of every frame of the +/// story after Select All in threaded text, [`editing_story`]), else all the text of every selected /// type object. At a caret, `at_caret` gives the range from the plain text and the caret's byte /// (None: nothing changes there). Each range comes with whether it came from a caret. pub(crate) fn type_ranges( @@ -1336,7 +1428,10 @@ pub(crate) fn type_ranges( Some(id) => vec![(id, Some(range_of(p, edit::runs_len(&text_ref(s, id)?.runs), c)?))], None => { let editing = editing_range(s)?.filter(|_| p.get("ids").filter(|v| !v.is_null()).is_none()); + let story = if editing.is_some() { editing_story(s) } else { vec![] }; match editing { + // Select All in threaded text: every frame's text. + Some(_) if !story.is_empty() => story.into_iter().map(|id| (id, None)).collect(), Some((id, a, b)) => vec![(id, Some((a.min(b), a.max(b))))], None => super::typecmd::text_targets(s, p, c)?.into_iter().map(|id| (id, None)).collect(), } diff --git a/crates/engine/src/cmd/threads.rs b/crates/engine/src/cmd/threads.rs index 537252dad0..61a21e506d 100644 --- a/crates/engine/src/cmd/threads.rs +++ b/crates/engine/src/cmd/threads.rs @@ -276,6 +276,14 @@ pub(crate) fn mark_continued(doc: &mut Document) { } } +/// The frames of the thread that `id` is a frame of, in thread order, each area type or type on a +/// path; empty when `id` is in no thread or the thread has fewer than two such frames. +pub(crate) fn story_of(d: &Document, id: NodeId) -> Vec { + let Some(thread) = d.text_threads.iter().find(|t| t.contains(&id)) else { return vec![] }; + let frames: Vec = thread.iter().copied().filter(|f| text_of(d, *f).is_some()).collect(); + if frames.len() >= 2 && frames.contains(&id) { frames } else { vec![] } +} + /// `ids` followed by the other frames of the threads they are in, each once, in thread order. pub(crate) fn with_threads(d: &Document, ids: &[NodeId]) -> Vec { let mut out = ids.to_vec(); diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index 30d0ff7f80..9e346bf657 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -1496,6 +1496,128 @@ fn select_all_and_cut_like_ui() { assert_eq!(s.execute("select.all", &json!({})).unwrap(), json!({"count": 2})); } +/// A story threaded from area type `a` into frame `b`, with the Type tool editing `b` at its start. +fn threaded_story_edited_in_its_second_frame() -> (Session, NodeId, NodeId, String) { + let mut s = session(); + let story = "The quick brown fox jumps over the lazy dog and keeps running far beyond the first frame. ".repeat(4); + let a = s.execute("text.create", &json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": 60}})).unwrap()["id"] + .as_u64() + .unwrap(); + let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 200})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + let (a, b) = (NodeId(a), NodeId(b)); + assert!(!obj(&s, a).plain_text().is_empty() && !obj(&s, b).plain_text().is_empty(), "the story runs through both frames"); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.select_tool("type", ViewInfo::default()).unwrap(); + s.set_tool_option("textSelection", &json!({"editing": b.0, "anchor": 0, "caret": 0})); + assert!(s.tool_wants_text()); + (s, a, b, story) +} + +#[test] +fn select_all_in_a_threaded_frame_selects_the_whole_story() { + let (mut s, a, b, story) = threaded_story_edited_in_its_second_frame(); + let a_len = obj(&s, a).plain_text().len(); + let o = s.execute("select.all", &json!({})).unwrap(); + assert_eq!(o, json!({"editing": a.0, "start": 0, "end": a_len, "story": [a.0, b.0]})); + assert_eq!(s.doc().unwrap().selection.objects, [a], "the first frame, which the tool edits, is selected"); + // Copy takes the whole story. + let r = s.execute("text.getRange", &json!({"id": o["editing"], "story": true})).unwrap(); + assert_eq!(r["text"], json!(story)); + assert_eq!(r["length"], json!(story.len())); + // The selection is highlighted in both frames. + let v = ViewInfo::default(); + let in_b = |o: &vectorcraft_tools::Overlay| matches!(o, vectorcraft_tools::Overlay::Highlight { quad, color: [60, 120, 255, 90] } if quad.iter().all(|p| p.x > 190.0)); + assert!(s.overlays(v).iter().any(in_b), "the text of the second frame is highlighted"); + // A fill reaches the text of both frames, as one undo step. + let steps = undo_labels(&s).len(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + assert_eq!(undo_labels(&s).len(), steps + 1); + let red = obj(&s, a).runs[0].style.fill.clone(); + for id in [a, b] { + assert!(obj(&s, id).runs.iter().all(|r| r.style.fill == red), "every character of frame {} is filled", id.0); + } + // So do a baseline shift step (Alt+Shift+Up) and a size step. + key(&mut s, ToolKey::Up, Mods { alt: true, shift: true, ..Mods::default() }); + for id in [a, b] { + assert!(obj(&s, id).runs.iter().all(|r| r.style.baseline_shift > 0.0), "every character of frame {} is raised", id.0); + } + let size = obj(&s, b).runs[0].style.size; + s.execute("type.step", &json!({"attribute": "size", "by": 1})).unwrap(); + for id in [a, b] { + assert!(obj(&s, id).runs.iter().all(|r| r.style.size > size), "every character of frame {} is larger", id.0); + } +} + +#[test] +fn select_all_edits_the_first_frame_that_holds_text() { + let mut s = session(); + // The first frame is too short for a line: the story starts in the second. + let a = + s.execute("text.create", &json!({"x": 10, "y": 10, "text": "One two three", "size": 12, "area": {"width": 150, "height": 4}})).unwrap()["id"] + .as_u64() + .unwrap(); + let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 200})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + let (a, b) = (NodeId(a), NodeId(b)); + assert_eq!((obj(&s, a).plain_text(), obj(&s, b).plain_text()), (String::new(), "One two three".to_string())); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.select_tool("type", ViewInfo::default()).unwrap(); + s.set_tool_option("textSelection", &json!({"editing": b.0, "anchor": 0, "caret": 0})); + let o = s.execute("select.all", &json!({})).unwrap(); + assert_eq!(o, json!({"editing": b.0, "start": 0, "end": 13, "story": [a.0, b.0]})); + key(&mut s, ToolKey::Delete, Mods::default()); + assert_eq!((obj(&s, a).plain_text(), obj(&s, b).plain_text()), (String::new(), String::new())); +} + +#[test] +fn the_eyedropper_styles_the_whole_story_that_select_all_selected() { + let (mut s, a, b, _) = threaded_story_edited_in_its_second_frame(); + let source = s.execute("text.create", &json!({"x": 400, "y": 250, "text": "Big", "size": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.set_tool_option("textSelection", &json!({"editing": b.0, "anchor": 0, "caret": 0})); + s.execute("select.all", &json!({})).unwrap(); + let r = s.execute("appearance.copyFrom", &json!({"source": source})).unwrap(); + assert_eq!(r, json!({"ids": [a.0, b.0]})); + for id in [a, b] { + assert!(obj(&s, id).runs.iter().all(|r| (r.style.size - 30.0).abs() < 1e-9), "every character of frame {} takes the size", id.0); + } +} + +#[test] +fn typing_over_the_whole_story_replaces_every_frames_text_in_one_step() { + let (mut s, a, b, story) = threaded_story_edited_in_its_second_frame(); + s.execute("select.all", &json!({})).unwrap(); + let steps = undo_labels(&s).len(); + key(&mut s, ToolKey::Delete, Mods::default()); + assert_eq!((obj(&s, a).plain_text(), obj(&s, b).plain_text()), (String::new(), String::new())); + s.tool_text("New", ViewInfo::default()).unwrap(); + key(&mut s, ToolKey::Escape, Mods::default()); + assert_eq!((obj(&s, a).plain_text(), obj(&s, b).plain_text()), ("New".to_string(), String::new())); + assert_eq!(undo_labels(&s).len(), steps + 1, "the delete and the typing are one step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), story); + assert!(!obj(&s, b).plain_text().is_empty()); +} + +#[test] +fn select_all_in_one_frame_selects_only_its_text_once_the_caret_moves() { + let (mut s, a, b, story) = threaded_story_edited_in_its_second_frame(); + s.execute("select.all", &json!({})).unwrap(); + let a_len = obj(&s, a).plain_text().len(); + // Shift+Left ends the story selection: the selection is the first frame's text but its last + // character, and Delete removes only that. + key(&mut s, ToolKey::Left, Mods { shift: true, ..Mods::default() }); + assert!(s.tool_options().get("story").is_none()); + key(&mut s, ToolKey::Delete, Mods::default()); + assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), story[a_len - 1..]); + assert!(s.execute("text.getRange", &json!({"id": a.0, "story": true, "start": 0})).is_err(), "`story` takes no range"); + assert!(s.execute("text.editRange", &json!({"id": a.0, "start": 0, "end": 0, "clear": [a.0]})).is_err()); + assert!(s.execute("text.editRange", &json!({"id": a.0, "start": 0, "end": 0, "clear": "x"})).is_err()); +} + #[test] fn a_frame_dragged_with_the_type_tools_is_the_dragged_rectangle() { for tool in ["type", "verticalType"] { diff --git a/crates/tools/src/text.rs b/crates/tools/src/text.rs index 2b5812cf8b..9dd96a1bf9 100644 --- a/crates/tools/src/text.rs +++ b/crates/tools/src/text.rs @@ -71,6 +71,9 @@ struct Typing { /// previewed span starts no later, so Return at a paragraph's end splits that paragraph (its /// style continues), not the next one. lo: usize, + /// The other frames of the story whose text the session removed: it began by replacing the + /// whole story that Select All selected ([`TypeTool::story`]). + clear: Vec, } /// IME marked text inside the typing session, not yet committed. @@ -171,6 +174,10 @@ pub struct TypeTool { /// Caret and selection anchor (byte offsets into the plain text). caret: usize, anchor: usize, + /// After Select All in a frame of threaded text: the story's frames in thread order, the edited + /// one included. While the selection is the edited frame's whole text, the text of the other + /// frames is selected too. Empty otherwise. + story: Vec, /// Horizontal position kept by Up/Down (text space). goal_x: Option, typing: Option, @@ -218,15 +225,22 @@ struct BeforePress { } impl TypeTool { - pub(super) fn step_attribute(&mut self, key: ToolKey, mods: Mods, a: usize, b: usize, vertical: bool) -> Option> { + pub(super) fn step_attribute(&mut self, cx: &ToolContext, key: ToolKey, mods: Mods, a: usize, b: usize, vertical: bool) -> Option> { if !mods.alt { return None; } let id = self.editing?; let (attribute, by) = plain::step_key(key, mods.shift, a == b, vertical)?; + let story = !self.story_others(cx).is_empty(); let mut out = self.commit(); let by = if mods.cmd { by * 5.0 } else { by }; - out.push(Action::Exec("type.step".into(), json!({"id": id.0, "start": a, "end": b, "attribute": attribute, "by": by}))); + // With the whole story selected, `type.step` steps the text of every frame of it. + let p = if story { + json!({"attribute": attribute, "by": by}) + } else { + json!({"id": id.0, "start": a, "end": b, "attribute": attribute, "by": by}) + }; + out.push(Action::Exec("type.step".into(), p)); Some(out) } pub fn new(id: &str) -> Self { @@ -375,6 +389,7 @@ impl TypeTool { out.push(Action::Exec("text.discardEmpty".into(), json!({"id": id.0}))); } self.editing = None; + self.story.clear(); self.selecting = false; self.goal_x = None; out @@ -388,8 +403,12 @@ impl TypeTool { return vec![]; }; let mut out = vec![]; + // The whole story is selected: the edit replaces it, so the other frames' text goes too, in + // a typing session of its own. + let others = self.story_others(cx); + self.story.clear(); // The document changed under us (undo, a panel edit): start a new session. - if self.typing.as_ref().is_some_and(|ty| ty.cur != t.runs) { + if self.typing.as_ref().is_some_and(|ty| ty.cur != t.runs || !others.is_empty()) { out.push(Action::Commit); self.typing = None; self.preedit = None; @@ -399,7 +418,7 @@ impl TypeTool { out.push(Action::Begin("Typing".into())); self.typing_ended = false; } - let ty = self.typing.get_or_insert_with(|| Typing { base: t.runs.clone(), cur: t.runs.clone(), lo: usize::MAX }); + let ty = self.typing.get_or_insert_with(|| Typing { base: t.runs.clone(), cur: t.runs.clone(), lo: usize::MAX, clear: others }); let len = edit::runs_len(&ty.cur); let (a, b) = (self.caret.min(self.anchor).min(len), self.caret.max(self.anchor).min(len)); ty.lo = ty.lo.min(a); @@ -416,11 +435,24 @@ impl TypeTool { let (p, s) = common_affixes(&base, &cur, ty.lo); let runs = edit::slice_runs(&ty.cur, p, cur.len() - s); let runs = if runs.is_empty() { json!([]) } else { serde_json::to_value(&runs).unwrap_or(json!([])) }; - out.push(Action::Preview("text.editRange".into(), json!({"id": id.0, "start": p, "end": base.len() - s, "runs": runs}))); + out.push(Action::Preview("text.editRange".into(), edit_range_params(id, p, base.len() - s, runs, &ty.clear))); self.note_edit(fresh, id, (&base, base.len() - s), (&cur, cur.len() - s)); out } + /// The other frames whose whole text is selected along with the edited frame's after Select + /// All in threaded text ([`Self::story`]): none once the selection is not all of the edited + /// frame's text. + fn story_others(&self, cx: &ToolContext) -> Vec { + let Some(id) = self.editing.filter(|id| self.story.contains(id)) else { return vec![] }; + let Some(t) = Self::text(cx, id) else { return vec![] }; + let (a, b) = self.sel(); + if a != 0 || b < edit::runs_len(&t.runs) { + return vec![]; + } + self.story.iter().copied().filter(|f| *f != id && Self::text(cx, *f).is_some()).collect() + } + /// Move the caret (Shift keeps the anchor). Moving ends the typing session. fn move_to(&mut self, byte: usize, extend: bool) -> Vec { let out = self.commit(); @@ -429,6 +461,7 @@ impl TypeTool { self.anchor = byte; } self.listed = None; + self.story.clear(); out } @@ -442,6 +475,7 @@ impl TypeTool { self.known = None; self.caret = caret; self.anchor = caret; + self.story.clear(); self.goal_x = None; self.typing = None; self.preedit = None; @@ -522,6 +556,7 @@ impl TypeTool { /// leaves the caret and the selection where they are, within the text. fn after_history_step(&mut self, cx: &ToolContext, undo: bool) { self.stepped = true; + self.story.clear(); let Some(id) = self.editing else { return }; let Some(text) = Self::text(cx, id).map(TextObject::plain_text) else { return }; match self.known.take() { @@ -621,6 +656,7 @@ impl TypeTool { fn select_word_or_para(&mut self, cx: &ToolContext, para: bool) { let s = self.plain(cx); let r = if para { edit::paragraph_at(&s, self.caret) } else { edit::word_at(&s, self.caret) }; + self.story.clear(); self.anchor = r.start; self.caret = r.end; } @@ -765,7 +801,7 @@ impl TypeTool { p.range.end = shift(p.range.end.min(len)); } self.goal_x = None; - let ty = self.typing.get_or_insert_with(|| Typing { base: t.runs.clone(), cur: t.runs.clone(), lo: usize::MAX }); + let ty = self.typing.get_or_insert_with(|| Typing { base: t.runs.clone(), cur: t.runs.clone(), lo: usize::MAX, clear: vec![] }); // Delete from the end so earlier offsets stay valid; each call floors to a char boundary // and the one Preview below still makes the whole session one undo step. for &(a, b) in sorted.iter().rev() { @@ -778,11 +814,21 @@ impl TypeTool { let (p, s) = common_affixes(&base, &cur, ty.lo); let runs = edit::slice_runs(&ty.cur, p, cur.len() - s); let runs = if runs.is_empty() { json!([]) } else { serde_json::to_value(&runs).unwrap_or(json!([])) }; - out.push(Action::Preview("text.editRange".into(), json!({"id": id.0, "start": p, "end": base.len() - s, "runs": runs}))); + out.push(Action::Preview("text.editRange".into(), edit_range_params(id, p, base.len() - s, runs, &ty.clear))); self.note_edit(fresh, id, (&base, base.len() - s), (&cur, cur.len() - s)); out } } +/// The params of a typing session's `text.editRange` preview: bytes `start..end` of `id` become +/// `runs`, and the text of the frames in `clear` goes. +fn edit_range_params(id: NodeId, start: usize, end: usize, runs: Value, clear: &[NodeId]) -> Value { + let mut p = json!({"id": id.0, "start": start, "end": end, "runs": runs}); + if !clear.is_empty() { + p["clear"] = json!(clear.iter().map(|f| f.0).collect::>()); + } + p +} + #[cfg(test)] mod tests; diff --git a/crates/tools/src/text/tool.rs b/crates/tools/src/text/tool.rs index 8c3ddf07c9..5634cf5a1f 100644 --- a/crates/tools/src/text/tool.rs +++ b/crates/tools/src/text/tool.rs @@ -201,7 +201,7 @@ impl Tool for TypeTool { self.anchor = self.anchor.min(len); let (a, b) = self.sel(); // Alt+arrows step the type by the Preferences › Type increments (Cmd/Ctrl too: five steps). - if let Some(out) = self.step_attribute(key, mods, a, b, t.vertical) { + if let Some(out) = self.step_attribute(cx, key, mods, a, b, t.vertical) { return out; } let word = mods.cmd || mods.alt; @@ -506,14 +506,14 @@ impl Tool for TypeTool { self.caret = t.map_or(0, |t| edit::runs_len(&t.runs)); } } - /// `{editing, start, end, caret, anchor, typing, composing}` — the Character panel styles - /// `start..end`. + /// `{editing, start, end, caret, anchor, typing, composing, story?}` — the Character panel styles + /// `start..end`; `story` lists the frames of a threaded story whose whole text Select All selected. fn options(&self) -> Value { match self.editing { Some(id) => { // Offsets may exceed the text after Select All; callers clamp to the text length. let (a, b) = self.sel(); - json!({ + let mut o = json!({ "editing": id.0, "start": a, "end": b, @@ -522,7 +522,12 @@ impl Tool for TypeTool { "typing": self.typing.is_some(), "composing": self.preedit.is_some(), "prevTool": self.prev_tool, - }) + }); + // After Select All in threaded text, the frames whose whole text is selected too. + if !self.story.is_empty() { + o["story"] = json!(self.story.iter().map(|f| f.0).collect::>()); + } + o } None => json!({"editing": null, "prevTool": self.prev_tool}), } @@ -551,7 +556,23 @@ impl Tool for TypeTool { self.preedit = None; self.typing_ended = true; } + // `{story: [id…], editing?: id}`: the frames of the threaded story being edited, in + // thread order. The tool edits frame `editing` of them (default: the first), and the + // whole story's text is selected. "selectAll" if self.editing.is_some() => { + let story: Vec = + v.get("story").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_u64).map(NodeId).collect(); + if story.len() >= 2 + && let Some(first) = story.first().copied() + { + let target = v.get("editing").and_then(Value::as_u64).map(NodeId).filter(|t| story.contains(t)).unwrap_or(first); + if self.editing != Some(target) { + self.start_editing(target, 0); + } + self.story = story; + } else { + self.story.clear(); + } self.anchor = 0; self.caret = usize::MAX / 4; } @@ -560,6 +581,7 @@ impl Tool for TypeTool { if let (Some(a), Some(b)) = (g("start"), g("end")) { self.anchor = a; self.caret = b; + self.story.clear(); } } "copy" => { @@ -571,6 +593,7 @@ impl Tool for TypeTool { self.typing = None; self.preedit = None; self.editing = None; + self.story.clear(); self.prev_tool = None; } _ => {} @@ -649,6 +672,14 @@ impl Tool for TypeTool { for q in vectorcraft_text::selection_quads(&lay, a, b) { o.push(Overlay::Highlight { quad: q.map(|p| t.xf * p), color: [60, 120, 255, 90] }); } + // The whole story is selected: the other frames' text is highlighted too. + for f in self.story_others(cx) { + let Some(other) = Self::text(cx, f) else { continue }; + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), other); + for q in vectorcraft_text::selection_quads(&lay, 0, edit::runs_len(&other.runs)) { + o.push(Overlay::Highlight { quad: q.map(|p| other.xf * p), color: [60, 120, 255, 90] }); + } + } } if let Some(id) = self.editing.filter(|id| shown && ported(cx.doc, *id).is_some()) { ports(cx, id, &t, lay.overflow, &mut o); diff --git a/crates/ui-egui/src/dialogs/justification.rs b/crates/ui-egui/src/dialogs/justification.rs index 5e8c5b6e66..d4f58602de 100644 --- a/crates/ui-egui/src/dialogs/justification.rs +++ b/crates/ui-egui/src/dialogs/justification.rs @@ -87,7 +87,11 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let mut targets = json!({}); if let Some((id, a, b)) = crate::panels::character::text_editing(app) { crate::panels::character::end_typing(app); - targets = json!({"ids": [id.0], "start": a, "end": b}); + targets = match crate::panels::character::text_story(app) { + // After Select All in threaded text: every paragraph of every frame. + Some(story) => json!({"ids": story.iter().map(|f| f.0).collect::>()}), + None => json!({"ids": [id.0], "start": a, "end": b}), + }; } let mut values = Map::new(); for (_, prefix, _) in ROWS { diff --git a/crates/ui-egui/src/font_menu.rs b/crates/ui-egui/src/font_menu.rs index e8fd10b4cc..7366cc1a37 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -1214,6 +1214,12 @@ fn font_command(app: &VectorcraftApp, family: &str, style: Option<&str>) -> (&'s if let Some(s) = style { p["style"] = json!(s); } + // After Select All in threaded text: every frame of the story. + if let Some(first) = crate::panels::character::text_story(app).and_then(|story| story.first().copied()) { + p["id"] = json!(first.0); + p["story"] = json!(true); + return ("text.setRangeStyle", p); + } match crate::panels::character::text_editing(app) { Some((id, a, b)) => { p["id"] = json!(id.0); diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index b9e289a494..da5c6d410e 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -141,7 +141,15 @@ fn shared_styles( let para = t.plain_text().get(..a).map_or(0, |s| s.bytes().filter(|&c| c == b'\n').count()); return f(t, t.para_at(para), &vectorcraft_text::edit::insertion_style(&t.runs, a, b), false); } - each_paragraph_run(t, Some((a, b)), |para, style, inline| acc.add(f(t, para, style, inline))); + match text_story(app) { + // After Select All in threaded text: all the text of every frame of the story. + Some(story) => { + for t in story.into_iter().filter_map(text) { + each_paragraph_run(t, None, |para, style, inline| acc.add(f(t, para, style, inline))); + } + } + None => each_paragraph_run(t, Some((a, b)), |para, style, inline| acc.add(f(t, para, style, inline))), + } } else { for n in st.selection.objects.iter().filter_map(|id| st.doc.node(*id)) { n.walk(&mut |c| { @@ -227,6 +235,9 @@ pub(crate) fn format(app: &mut VectorcraftApp, p: Value) { /// `text.setFormat` on the selected text objects. pub(crate) fn run_format(app: &mut VectorcraftApp, mut p: Value) -> Result { let Some((id, a, b)) = text_editing(app) else { return app.run("text.setFormat", p) }; + if let Some(first) = text_story(app).and_then(|story| story.first().copied()) { + return story_style(app, first, p); + } end_typing(app); p["id"] = json!(id.0); if b > a { @@ -451,6 +462,10 @@ pub(crate) fn toggle_underline(app: &mut VectorcraftApp) -> Result Option<(NodeId, usize, usize Some((id, g("start"), g("end"))) } +/// The frames of the threaded story whose whole text the Type tool has selected after Select All, +/// in thread order; `None` when its selection is in one type object. +pub(crate) fn text_story(app: &VectorcraftApp) -> Option> { + let o = app.session.tool_options(); + let st = app.session.active()?; + let ids: Vec = o + .get("story")? + .as_array()? + .iter() + .filter_map(Value::as_u64) + .map(NodeId) + .filter(|id| st.doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Text(_)))) + .collect(); + (ids.len() >= 2).then_some(ids) +} + +/// `text.setRangeStyle` with `p` on all the text of every frame of the story that `first` is a +/// frame of, as one undo step. +fn story_style(app: &mut VectorcraftApp, first: NodeId, mut p: Value) -> Result { + end_typing(app); + p["id"] = json!(first.0); + p["story"] = json!(true); + app.run("text.setRangeStyle", p) +} + /// Close the Type tool's typing session (one undo step) before another command edits the text. pub(crate) fn end_typing(app: &mut VectorcraftApp) { if app.session.tool_options().get("typing").and_then(Value::as_bool) == Some(true) { @@ -495,7 +535,9 @@ fn text_copy(app: &mut VectorcraftApp) -> bool { if a == b { return false; } - let Ok(r) = app.session.execute("text.getRange", &json!({"id": id.0, "start": a, "end": b})) else { return false }; + // After Select All in threaded text: the whole story. + let range = if text_story(app).is_some() { json!({"id": id.0, "story": true}) } else { json!({"id": id.0, "start": a, "end": b}) }; + let Ok(r) = app.session.execute("text.getRange", &range) else { return false }; let runs = r["runs"].clone(); app.session.set_tool_option("copy", &runs); *CLIP_RUNS.lock().unwrap_or_else(|e| e.into_inner()) = Some(runs.clone()); @@ -893,7 +935,11 @@ fn axes_cmd(app: &mut VectorcraftApp, axes: Value, phase: widgets::Live) { Some((id, a, b)) => { end_typing(app); let mut q = json!({"id": id.0, "fontAxes": axes}); - if b > a { + // After Select All in threaded text: every frame of the story. + if let Some(first) = text_story(app).and_then(|story| story.first().copied()) { + q["id"] = json!(first.0); + q["story"] = json!(true); + } else if b > a { q["start"] = json!(a); q["end"] = json!(b); } diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index 9f28427c16..7716c3bb4e 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -1171,3 +1171,45 @@ fn snap_to_glyph_options_show_from_the_menu_and_set_the_options() { toggle(&mut app, "Hide Snap to Glyph Options"); assert!(!section(&mut app).iter().any(|(t, _)| t == "Proximity Guides")); } + +/// After Select All in a frame of threaded text, the Character and Paragraph panels and Copy act on +/// the text of every frame of the story. +#[test] +fn select_all_in_threaded_text_formats_and_copies_the_whole_story() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 300})).unwrap(); + let story = "The quick brown fox jumps over the lazy dog and keeps running far beyond the first frame. ".repeat(4); + let area = json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": 60}}); + let a = app.run("text.create", area).unwrap()["id"].as_u64().unwrap(); + let b = app.run("shape.rectangle", json!({"x": 200, "y": 10, "width": 150, "height": 200})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + app.run("text.thread.create", json!({})).unwrap(); + app.run("select.set", json!({"ids": [b]})).unwrap(); + app.session.select_tool("type", Default::default()).unwrap(); + app.session.set_tool_option("textSelection", &json!({"editing": b, "anchor": 0, "caret": 0})); + app.run("select.all", json!({})).unwrap(); + assert_eq!(text_story(&app), Some(vec![NodeId(a), NodeId(b)])); + let frame = |app: &VectorcraftApp, id: u64| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("not text"), + }; + format(&mut app, json!({"size": 9})); + crate::panels::paragraph::run_on_paragraphs(&mut app, "text.setFormat", json!({"spaceBefore": 4})).unwrap(); + for id in [a, b] { + let t = frame(&app, id); + assert!(t.runs.iter().all(|r| (r.style.size - 9.0).abs() < 1e-9), "every character of frame {id} is 9 pt"); + assert!((t.para_at(0).space_before - 4.0).abs() < 1e-9, "frame {id}'s paragraphs take the space"); + } + assert!(intercept_text_command(&mut app, "edit.copy").is_some()); + let copied: Vec = app + .session + .clipboard + .nodes + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => Some(t.plain_text()), + _ => None, + }) + .collect(); + assert_eq!(copied, [story]); +} diff --git a/crates/ui-egui/src/panels/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index 91b804365b..b4aea639ad 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -156,10 +156,13 @@ fn set(app: &mut VectorcraftApp, f: OtFeatures) { /// Send `tags` as the `key` param (`features` or `featureChanges`) for the Type tool's range or /// caret, or else for the selected type. fn run_features(app: &mut VectorcraftApp, key: &str, tags: Vec) { - let (cmd, mut p) = match text_editing(app) { - Some((id, a, b)) if b > a => ("text.setRangeStyle", json!({ "id": id.0, "start": a, "end": b })), - Some((id, _, _)) => ("text.setRangeStyle", json!({ "id": id.0 })), - None => ("text.setStyle", json!({})), + // After Select All in threaded text: every frame of the story. + let story = super::character::text_story(app).and_then(|story| story.first().copied()); + let (cmd, mut p) = match (text_editing(app), story) { + (Some(_), Some(first)) => ("text.setRangeStyle", json!({ "id": first.0, "story": true })), + (Some((id, a, b)), None) if b > a => ("text.setRangeStyle", json!({ "id": id.0, "start": a, "end": b })), + (Some((id, _, _)), None) => ("text.setRangeStyle", json!({ "id": id.0 })), + (None, _) => ("text.setStyle", json!({})), }; p[key] = json!(tags); if let Err(e) = app.run(cmd, p) { diff --git a/crates/ui-egui/src/panels/paragraph.rs b/crates/ui-egui/src/panels/paragraph.rs index 1952de032c..66f907f92a 100644 --- a/crates/ui-egui/src/panels/paragraph.rs +++ b/crates/ui-egui/src/panels/paragraph.rs @@ -77,9 +77,15 @@ fn para_cmd(app: &mut VectorcraftApp, cmd: &str, p: Value) { pub(crate) fn run_on_paragraphs(app: &mut VectorcraftApp, cmd: &str, mut p: Value) -> Result { if let Some((id, a, b)) = super::character::text_editing(app) { super::character::end_typing(app); - p["ids"] = json!([id.0]); - p["start"] = json!(a); - p["end"] = json!(b); + match super::character::text_story(app) { + // After Select All in threaded text: every paragraph of every frame. + Some(story) => p["ids"] = json!(story.iter().map(|f| f.0).collect::>()), + None => { + p["ids"] = json!([id.0]); + p["start"] = json!(a); + p["end"] = json!(b); + } + } } app.run(cmd, p) } @@ -164,9 +170,33 @@ fn collect_text_alignment(text: &vectorcraft_doc::TextObject, range: Option<(usi record(index, &plain, start, end) // Includes empty text and the paragraph after a final newline. } +/// The frames of the threaded story whose whole text the Type tool has selected after Select All +/// ([`super::character::text_story`]), in thread order. +fn story_texts(app: &VectorcraftApp) -> Option> { + let st = app.session.active()?; + let story = super::character::text_story(app)?; + Some( + story + .into_iter() + .filter_map(|id| match st.doc.node(id).map(|n| &n.kind) { + Some(NodeKind::Text(t)) => Some(t.as_ref()), + _ => None, + }) + .collect(), + ) +} + /// Visit every paragraph the Paragraph panel acts on. fn visit_paragraphs(app: &VectorcraftApp, mut f: impl FnMut(&ParaStyle)) { let Some(st) = app.session.active() else { return }; + if let Some(texts) = story_texts(app) { + for t in texts { + for i in 0..t.paragraph_count() { + f(t.para_at(i)); + } + } + return; + } if let Some((id, a, b)) = super::character::text_editing(app) && let Some(NodeKind::Text(text)) = st.doc.node(id).map(|n| &n.kind) { @@ -288,6 +318,9 @@ fn selected_paragraph_direction(app: &VectorcraftApp, fallback: &ParaStyle) -> O let default = Some(resolved_rtl(app, fallback)); let Some(st) = app.session.active() else { return default }; let mut shared = None; + if let Some(texts) = story_texts(app) { + return if texts.into_iter().all(|t| collect_text_direction(t, None, &mut shared)) { shared.or(default) } else { None }; + } if let Some((id, a, b)) = super::character::text_editing(app) && let Some(NodeKind::Text(text)) = st.doc.node(id).map(|n| &n.kind) { @@ -322,6 +355,9 @@ fn selected_alignment(app: &VectorcraftApp, fallback: &ParaStyle) -> Option Value { fn apply(app: &mut VectorcraftApp, stops: &[TabStop]) -> bool { if let Some((id, a, b)) = super::character::text_editing(app) { super::character::end_typing(app); - app.run("text.tabs.set", json!({"stops": stops_json(stops), "ids": [id.0], "start": a, "end": b})).is_ok() + let p = match super::character::text_story(app) { + // After Select All in threaded text: every paragraph of every frame. + Some(story) => json!({"stops": stops_json(stops), "ids": story.iter().map(|f| f.0).collect::>()}), + None => json!({"stops": stops_json(stops), "ids": [id.0], "start": a, "end": b}), + }; + app.run("text.tabs.set", p).is_ok() } else { app.run("text.tabs.set", json!({"stops": stops_json(stops)})).is_ok() } diff --git a/crates/ui-egui/src/panels/text_styles.rs b/crates/ui-egui/src/panels/text_styles.rs index 1aca6039a1..8aaff6849a 100644 --- a/crates/ui-egui/src/panels/text_styles.rs +++ b/crates/ui-egui/src/panels/text_styles.rs @@ -191,6 +191,18 @@ fn target(app: &VectorcraftApp, kind: Kind, mut p: Value) -> Value { p } +/// [`target`] for applying a style: after Select All in threaded text, all the text of every +/// frame of the story. +fn apply_target(app: &VectorcraftApp, kind: Kind, mut p: Value) -> Value { + match super::character::text_story(app) { + Some(story) if text_editing(app).is_some() => { + p["ids"] = json!(story.iter().map(|f| f.0).collect::>()); + p + } + _ => target(app, kind, p), + } +} + /// Open New Character Style (`Kind::Para`: New Paragraph Style) to name a style made from the /// selected text: `ui.newCharStyle` and `ui.newParaStyle`. pub(crate) fn open_new(app: &mut VectorcraftApp, kind: Kind) -> Result { @@ -277,7 +289,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui, kind: Kind) { sel = super::swatches::click_selection(ui, kind.anchor_key(), sel, &listed, &name, m); // Shift and Cmd/Ctrl clicks only highlight, as in the Graphic Styles panel. if has_text && !(m.shift || m.command) { - let p = target(app, kind, json!({ "name": name, "clearOverrides": m.alt })); + let p = apply_target(app, kind, json!({ "name": name, "clearOverrides": m.alt })); app.run(&format!("{}.apply", kind.prefix()), p).ok(); } } @@ -364,7 +376,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui, kind: Kind) { if menu_item(ui, tl!("Clear Overrides"), sel.is_some() && has_text, false) && let Some(n) = &sel { - app.run(&format!("{p}.apply"), target(app, kind, json!({ "name": n, "clearOverrides": true }))).ok(); + app.run(&format!("{p}.apply"), apply_target(app, kind, json!({ "name": n, "clearOverrides": true }))).ok(); } if menu_item(ui, &crate::i18n::fmt(tl!("Redefine {kind} Style"), &[("kind", kind.what_label())]), sel.is_some() && has_text, false) && let Some(n) = &sel diff --git a/docs/mcp.md b/docs/mcp.md index 681eb58dcd..98e06b2457 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1179,7 +1179,7 @@ These commands refuse a string, a number or another value that is not true or fa `clockwise` in `shape.spiral`; `closed` in `shape.arc` and `path.create`; `vertical` and `placeholder` in `text.create` and `text.createInPath`; `underline`, `strikethrough`, `allCaps`, `proportionalMetrics`, `tateChuYoko`, `standardVerticalRoman` and `noBreak` in `text.setRangeStyle` and `text.setFormat`, which also checks `hyphenate`, `hyphenateCapitalized` and -`romanHangingPunctuation`; `effective` in `text.getRange`; `on` in `type.opticalMarginAlignment`, `type.systemLayout` +`romanHangingPunctuation`; `effective` and `story` in `text.getRange`; `story` in `text.setRangeStyle`; `on` in `type.opticalMarginAlignment`, `type.systemLayout` and `type.fractionalWidths`; `remove` and `overhang` in `type.ruby`; `expandInstances` in `symbol.delete`; `alt` in `symbol.spray` and `symbol.adjust`; `spot` and `global` in `swatch.new` and `swatch.edit`; `unlink` in `swatch.delete`; `fromArtwork`, `toGlobal` and `includeTints` in `swatch.newGroup`; `global` and `selection` in @@ -4881,7 +4881,13 @@ While the Type tool edits text (a click into type, `pointer_gesture` with `"tool `press_key {key: "A", mods: {cmd: true}}`) selects all of that text instead of the art, as in the reference app, and returns `{editing, start, end}` (the text's id and the selected byte range, which `text.getRange` and `text.setRangeStyle` take); the art selection stays as it is. Without text being edited it selects every object and -returns `{count}`. Text in threaded frames is selected one frame at a time. +returns `{count}`. In a frame of threaded text, `select.all` selects the whole story: the Type tool then edits the +thread's first frame that holds text (which is selected when it was not) with the text of every frame selected, and the reply adds +`story`, the frames in thread order. `text.getRange {id, story: true}` returns the story's text and runs, which Copy +and Cut take. Typing, Delete and Cut replace the whole story as one undo step (`text.editRange` with `clear`, the other +frames whose text goes), and a fill, stroke, `type.step` or Character or Paragraph panel change applies to the text of +every frame (the Character panel sends `text.setRangeStyle {id, story: true}`, which styles every frame's text in one +undo step). A caret move or a click ends the story selection. ```json {"name":"press_key","arguments":{"key":"A","mods":{"cmd":true}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index da687715a4..9e6728a38d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -680,7 +680,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Shift+Tab (`window.panels`) shows and hides the dock and the floating panels and leaves the toolbar and the Control bar as they are; hiding the panels with Tab or Shift+Tab also closes a panel popped out of the icon column. - The second Tab (`window.dock`) shows again only the bars the first Tab hid, after a restart too: a Control bar that was off stays off, a toolbar hidden with Window › Tools stays hidden, and panels shown with Shift+Tab in between stay shown. - The function key shortcuts for Brushes, Color, Layers, Info, Gradient, Stroke, Attributes, Graphic Styles, Appearance, Align, Transform, Pathfinder, Transparency, and Symbols activate a background tab on the first press, hide its expanded dock or floating group when that tab is in front, and restore the group with all its tabs together on the next press; in an icon column they open and close the flyout while keeping the icons. A reassigned chord keeps that behavior, and Window > a hidden sibling restores the group. - - Cmd/Ctrl+A follows the keyboard: in a panel, dialog or search field it selects the field's text, while the Type tool edits it selects all of that text (also `select.all` over MCP), and only otherwise every object. On macOS the menu bar's Select All, Cut, Copy and Paste (keys or clicks) act on a focused field too, and elsewhere the in-window menus' do: the field that had the keyboard when the menu opened gets them, with its selection, and the keyboard back (#516). Not yet: Select All across threaded frames (one frame's text is selected). + - Cmd/Ctrl+A follows the keyboard: in a panel, dialog or search field it selects the field's text, while the Type tool edits it selects all of that text (also `select.all` over MCP), and only otherwise every object. On macOS the menu bar's Select All, Cut, Copy and Paste (keys or clicks) act on a focused field too, and elsewhere the in-window menus' do: the field that had the keyboard when the menu opened gets them, with its selection, and the keyboard back (#516). In a frame of threaded text, Select All selects the whole story, highlighted in every frame: Copy and Cut take all of it, typing or Delete replaces it as one undo step, and a fill, a size step or a Character or Paragraph panel change applies to every frame's text (VectorCraft's own behavior; `textedit::select_all_in_a_threaded_frame_selects_the_whole_story`, `textedit::typing_over_the_whole_story_replaces_every_frames_text_in_one_step`). - While the Type tool edits text, a character typed with AltGr is typed and runs no command. Firefox on Windows reports AltGr as Ctrl and Alt held, so in the web build AltGr+L (ł on a Polish layout) does not also open Layer Options for a new layer, and AltGr+Q (@ on a German layout) does not also run Reset Tracking and Kerning. A Ctrl+Alt chord that types no character runs its command. - On a layout without Latin letters, a one-key shortcut goes by the position of the key that typed the character, in the web build too, where the character arrives before its key press: on a Russian layout the P key (`з`) chooses the Pen, and two keys pressed in one frame each run their own shortcut. - With the Artboard tool, Cmd/Ctrl+A after a click on a row of the Artboards panel selects every artboard, as the macOS menu bar's Select All does then; the active artboard stays active, and the art's selection does not change. After a press outside the panel's list, Cmd/Ctrl+A selects every object again. It used to select every object after a click in the panel too. Public reference: [Select artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/select-artboards.html). From a79ab627123403801a5d080e446dcf57912ab0cf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 15:13:32 +0700 Subject: [PATCH 033/513] Select: Same Symbol Instance takes its reference from an object that can be selected Squashed from #5511 onto main. --- crates/engine/src/cmd/docmenu.rs | 20 +++++++----- crates/engine/src/cmd/select.rs | 15 +++++---- crates/engine/src/tests/menucmds.rs | 47 +++++++++++++++++++++++++++++ docs/mcp.md | 9 +++--- docs/target-app-parity.md | 2 +- 5 files changed, 72 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index c34c3d35bd..f566f1635e 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -11,7 +11,7 @@ use vectorcraft_geom::Vec2; use super::edit::selected_roots; use super::pathops::Beside; -use super::select::{is_selectable, selectable_ids, walk_selectable}; +use super::select::{first_selectable, is_selectable, selectable_ids, walk_selectable}; use super::{ CommandSpec, EngineError, Point, Result, Session, bad, bool_or, checked_ids_param, cmd, f64_or, f64_req, has_doc, has_selection, id_param, ok, str_param, @@ -19,14 +19,18 @@ use super::{ pub fn specs() -> Vec { vec![ - cmd!("select.same.symbolInstance", "Symbol Instance", ["Select", "Same"], None, "{} → {count}", has_selection, |s, _| same( - s, + cmd!( "select.same.symbolInstance", - |a, b| match (&a.kind, &b.kind) { + "Symbol Instance", + ["Select", "Same"], + None, + "{} select the instances of the symbol of the first selected object that can be selected; objects that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard while nothing is isolated, or outside the isolated group or layer are passed over → {count}", + has_selection, + |s, _| same(s, "select.same.symbolInstance", |a, b| match (&a.kind, &b.kind) { (NodeKind::SymbolInstance { symbol: x, .. }, NodeKind::SymbolInstance { symbol: y, .. }) => x == y, _ => false, - } - )), + }) + ), cmd!( "select.same.linkBlockSeries", "Link Block Series", @@ -297,9 +301,9 @@ fn finish_same(s: &mut Session, cmd: &str, ids: Vec) -> Result { Ok(json!({ "count": st.selection.objects.len() })) } +/// The objects `eq` matches with the [`first_selectable`] selected object. fn same(s: &mut Session, cmd: &str, eq: fn(&Node, &Node) -> bool) -> Result { - let st = s.doc()?; - let r = st.selection.objects.first().and_then(|id| st.doc.node(*id)).cloned().ok_or_else(|| bad(cmd, "nothing selected"))?; + let r = first_selectable(s.doc()?).cloned().ok_or_else(|| bad(cmd, "nothing selected"))?; let ids = candidates(s, |n| eq(n, &r))?; finish_same(s, cmd, ids) } diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index a851660245..6cc8e3839a 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -267,6 +267,12 @@ pub(crate) fn is_selectable(d: &Document, iso: Option, locks: &LockedArt } } +/// The first selected object, in selection order, that [`is_selectable`] accepts. +pub(crate) fn first_selectable(st: &DocState) -> Option<&Node> { + let locks = st.doc.locked_artboards(); + st.selection.objects.iter().find(|id| is_selectable(&st.doc, st.isolation, &locks, **id)).and_then(|id| st.doc.node(*id)) +} + fn all(s: &mut Session, _: &Value) -> Result { // While the Type tool edits text, Select All takes all of that text and leaves the art // selection as it is (Illustrator: text cursor in a text object). @@ -718,14 +724,7 @@ fn paint_reported(d: &Document, n: &Node) -> bool { fn same_reference<'a>(st: &'a DocState, cmd: &str) -> Result<(&'a Node, bool)> { let compound = |n: &Node| matches!(n.kind, NodeKind::Compound { .. }); let members = st.isolation.and_then(|i| st.doc.ancestry(i)).is_some_and(|a| a.iter().any(|i| st.doc.node(*i).is_some_and(compound))); - let locks = st.doc.locked_artboards(); - let first = st - .selection - .objects - .iter() - .find(|id| is_selectable(&st.doc, st.isolation, &locks, **id)) - .and_then(|id| st.doc.node(*id)) - .ok_or_else(|| bad(cmd, "nothing selected"))?; + let first = first_selectable(st).ok_or_else(|| bad(cmd, "nothing selected"))?; let refn = match st.doc.parent_of(first.id).and_then(|p| st.doc.node(p)) { Some(p) if !members && compound(p) => p, _ => first, diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index e7750c058c..fe0783a135 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -2049,6 +2049,53 @@ fn select_same_font_takes_its_reference_from_the_isolated_group_on_a_selected_la assert!(!got.contains(&outside)); } +/// Select › Same › Symbol Instance takes its reference from the first selected object that can be +/// selected: an instance that is hidden, locked, on a template layer or outside the isolated group +/// is passed over. +#[test] +fn select_same_symbol_instance_skips_objects_that_cannot_be_selected() { + const C: &str = "select.same.symbolInstance"; + let mut s = session(); + let place = |s: &mut Session, name: &str, x: f64| id_of(&s.execute("symbol.place", &json!({"name": name, "x": x, "y": 200})).unwrap()); + rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let a1 = id_of(&s.execute("symbol.new", &json!({"name": "A"})).unwrap()); + rect(&mut s, 50.0, 0.0, 20.0, 20.0); + let b1 = id_of(&s.execute("symbol.new", &json!({"name": "B"})).unwrap()); + let a2 = place(&mut s, "A", 100.0); + let b2 = place(&mut s, "B", 200.0); + // A hidden or locked instance of A, selected first, is not the reference. + for (on, off) in [ + (json!({"id": a1.0, "visible": false}), json!({"id": a1.0, "visible": true})), + (json!({"id": a1.0, "locked": true}), json!({"id": a1.0, "locked": false})), + ] { + s.execute("layer.setProps", &on).unwrap(); + sel(&mut s, &[a1, b1]); + assert_eq!(s.execute(C, &json!({})).unwrap()["count"], 2, "{on}"); + assert_eq!(selected(&s), vec![b1, b2], "{on}"); + s.execute("layer.setProps", &off).unwrap(); + } + // An instance on a template layer, selected by id, is not the reference. + let l2 = id_of(&s.execute("layer.new", &json!({"top": true})).unwrap()); + let on_template = place(&mut s, "A", 300.0); + s.execute("layer.setProps", &json!({"id": l2.0, "template": true})).unwrap(); + sel(&mut s, &[on_template, b1]); + s.execute(C, &json!({})).unwrap(); + assert_eq!(selected(&s), vec![b1, b2]); + // An instance outside the isolated group is not the reference. + sel(&mut s, &[b1, b2]); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + sel(&mut s, &[a2, b1]); + s.execute(C, &json!({})).unwrap(); + assert_eq!(selected(&s), vec![b1, b2]); + s.execute("object.exitIsolation", &json!({})).unwrap(); + // A selection whose only objects cannot be selected has no reference. + s.execute("layer.setProps", &json!({"id": a1.0, "visible": false})).unwrap(); + sel(&mut s, &[a1, on_template]); + assert!(s.execute(C, &json!({})).is_err()); + assert_eq!(selected(&s), vec![a1, on_template]); +} + /// Select › Same › Text Fill & Stroke Color selects the type with characters whose fill and stroke /// both match the first character of the selected type: the same fill with another stroke, or the /// same stroke with another fill, is left out, and in type with several runs one run has to match diff --git a/docs/mcp.md b/docs/mcp.md index 98e06b2457..7a0d981e57 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1465,10 +1465,11 @@ inside a hidden or locked group or layer, on a template layer, or outside the is selection holds no other type, they return the error "select a text object". `select.same.fillColor`, `strokeColor`, `fillAndStroke`, `strokeWeight`, `opacity`, `blendingMode`, `appearance`, -`shapeType`, `graphicStyle` and `appearanceAttribute` compare the other objects with the first selected object, in -selection order, that these commands could select. A selected object that is hidden or locked, inside a hidden or -locked group or layer, on a template layer, or outside the isolated group is passed over. When the selection holds no other -object, they return the error "nothing selected". +`shapeType`, `graphicStyle`, `appearanceAttribute` and `symbolInstance` compare the other objects with the first +selected object, in selection order, that these commands could select. A selected object that is hidden or locked, +inside a hidden or locked group or layer, on a template layer, on a locked artboard while nothing is isolated, or +outside the isolated group is passed over. When the selection holds no other object, they return the error "nothing +selected". ## Shaper Groups diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9e6728a38d..d1c57dadf9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -928,7 +928,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Select › Same › Link Block Series selects every frame of the threads of the selected type; type in no thread selects itself (`select.same.linkBlockSeries`). The menu entry is listed in [Select objects by characteristics](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects-by-characteristics.html); selecting several threads at once and type in no thread selecting itself are VectorCraft's own behavior. Select › Same › Text Fill & Stroke Color selects the type whose characters match both the fill and the stroke of the selected type (`select.same.textFillAndStrokeColor`). The menu entry is listed in [Select objects by characteristics](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects-by-characteristics.html); requiring one run of characters to match both is VectorCraft's own behavior. The Select › Same font and text color commands take the type to match from the selected type that can be selected: type that is hidden or locked, on a template layer, or outside the isolated group is passed over. This is VectorCraft's own behavior. - Select › Same › Fill Color, Stroke Color, Fill & Stroke, Stroke Weight, Opacity, Blending Mode, Appearance, Shape, Graphic Style and Appearance Attribute compare the other objects with the first selected object that can be selected: an object that is hidden or locked, on a template layer, or outside the isolated group is passed over. This is VectorCraft's own behavior. + Select › Same › Fill Color, Stroke Color, Fill & Stroke, Stroke Weight, Opacity, Blending Mode, Appearance, Shape, Graphic Style, Appearance Attribute and Symbol Instance compare the other objects with the first selected object that can be selected: an object that is hidden or locked, on a template layer, on a locked artboard while nothing is isolated, or outside the isolated group is passed over. This is VectorCraft's own behavior. Object › Flatten Transparency takes a frame of threaded text out of the thread in the same way when Convert All Text to Outlines outlines it or when the frame becomes flat regions or an image, and the other frames keep the text they hold. New Symbol and Redefine Symbol on a frame of threaded text take it out of the thread with the text it shows, which the symbol's art holds, and the other frames keep the text they hold. When the last frame goes into the symbol, the text it has no room for goes after the text of the last frame that stays. When every frame of a thread goes into the symbol, the copy of the last frame keeps all its text. With Optical Margin Alignment on, or Roman Hanging Punctuation on in the first paragraph, the glyphs at the ends of left-to-right type on a path hang outside its brackets, measured along the path. The type hangs at the start bracket when its line is placed there, hangs at the end bracket when the line is placed there, and hangs at both when it is centered. Glyphs that hang past the end bracket do not make the type overflow, and a hang stops at an open path's end. SVG export writes such type as outlines. From 146d30502a558e7fbf3cd0809f4fbebf1cbd7b6f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 21:31:47 -0800 Subject: [PATCH 034/513] Expand: selected symbol instances become their art, as Break Link places it Object > Expand with Object on now turns each symbol instance in the selection, including one in a selected group or in a placed document's art, into its art, as Break Link to Symbol places it. It goes one level deep: the instances in that art stay instances. The art keeps the instance's id and place in the stacking order, and Expand stays one undo step. - Instances with effects stay instances, and Expand Appearance bakes them as before. Instances with an effect on a fill or stroke, instances in perspective, and those in blends, repeats and Intertwine groups stay instances. - The art keeps the instance's opacity mask, as Break Link gives it. - A hidden or locked instance's art stays hidden or locked. - A placed document in an instance's art is expanded too. - When the instances' art would make more than 1,000,000 objects, they stay instances, the limit Break Link uses. - The Fill and Stroke options (object.expand.info, and the Expand dialog) count the fills, strokes and gradients in the art of those instances, with a dynamic instance's own changes applied. The info reports under symbolArt which of them only that art holds, and the dialog enables those options only while Object is on. --- crates/engine/src/cmd/brushsym.rs | 4 +- crates/engine/src/cmd/brushsym/symbols.rs | 59 ++++- crates/engine/src/cmd/expand.rs | 124 ++++++--- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/expand_symbols.rs | 286 +++++++++++++++++++++ crates/engine/src/tests/placed_document.rs | 18 ++ crates/ui-egui/src/dialogs/expand.rs | 36 ++- docs/control-protocol.md | 4 +- docs/mcp.md | 10 +- docs/target-app-parity.md | 4 +- 10 files changed, 503 insertions(+), 43 deletions(-) create mode 100644 crates/engine/src/tests/expand_symbols.rs diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index f34ae619d6..f5da40e7b4 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -35,7 +35,9 @@ use brushes::{ }; use dynamic::{symbol_instance_reset, symbol_instance_set_appearance}; use symbols::selected_instances; -pub(crate) use symbols::{instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol}; +pub(crate) use symbols::{ + expand_instances_under, expandable_instances, instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol, +}; use symbols::{ symbol_adjust, symbol_break_link, symbol_delete, symbol_duplicate, symbol_list, symbol_new, symbol_options, symbol_place, symbol_replace, symbol_select_instances, symbol_set_current, symbol_spray, symbol_unused, symbol_update, diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 534b51506e..3bc167ffa1 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -412,7 +412,64 @@ fn break_links(d: &mut Document, ids: &[NodeId], own: bool) -> Result