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/196] 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/196] 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/196] 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 64312427e9795550d110c55ac62db0b1060c0d45 Mon Sep 17 00:00:00 2001 From: datatimp <12644819+datatimp@users.noreply.github.com> Date: Wed, 4 Nov 2026 13:03:25 -0500 Subject: [PATCH 004/196] Color Halftone: convert radii in brush definitions and Shaper edits (#3260) --- crates/doc/src/halftone_radii.rs | 81 ++++++++++++++++++++++++++++++-- 1 file changed, 77 insertions(+), 4 deletions(-) diff --git a/crates/doc/src/halftone_radii.rs b/crates/doc/src/halftone_radii.rs index 5828f543e6..a96707c48e 100644 --- a/crates/doc/src/halftone_radii.rs +++ b/crates/doc/src/halftone_radii.rs @@ -14,6 +14,9 @@ use crate::{Appearance, Document, Effect, Node}; const PIXEL_RADII_SINCE: u32 = 3; const HALFTONE: &str = "pixelate.colorHalftone"; const RADIUS: &str = "maxRadius"; +/// The key of `Document::unknown` that holds the brush definitions (`vectorcraft-brush`'s +/// `DOC_KEY`), whose art can carry effects. +const BRUSHES: &str = "brushes"; /// 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. @@ -49,7 +52,8 @@ impl Document { } /// `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. + /// designs, opacity masks, Shaper edits, graphic styles and brush definitions 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); @@ -71,6 +75,25 @@ impl Document { appearance(&mut s.appearance, fix); } } + if let Some(b) = self.unknown.get_mut(BRUSHES) { + brushes(b, fix); + } + } +} + +/// `fix` each Color Halftone in JSON `v` (brush definitions): every object whose `id` is +/// [`HALFTONE`] is a serialized [`Effect`] (object ids are numbers). +fn brushes(v: &mut Value, fix: &mut dyn FnMut(&mut Effect)) { + match v { + Value::Object(m) if m.get("id").and_then(Value::as_str) == Some(HALFTONE) => { + let params = m.get("params").cloned().unwrap_or(Value::Null); + let mut e = Effect { id: HALFTONE.into(), params, visible: true }; + fix(&mut e); + m.insert("params".into(), e.params); + } + Value::Object(m) => m.values_mut().for_each(|v| brushes(v, fix)), + Value::Array(a) => a.iter_mut().for_each(|v| brushes(v, fix)), + _ => {} } } @@ -98,14 +121,24 @@ fn appearance(a: &mut Appearance, fix: &mut dyn FnMut(&mut Effect)) { } } -/// Fix the effects of `n`'s subtree and its opacity masks (copying only what changes). +/// Fix the effects of `n`'s subtree, its opacity masks and its Shaper edits (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(x) = n.extras_if_any() { + if let Some(m) = x.mask.as_mut() { + node(&mut m.art, fix); + } + // A Shaper Group's face and edge edits paint with appearances of their own. + if let Some(s) = x.shaper.as_mut() { + let faces = s.faces.iter_mut().filter_map(|f| f.paint.as_mut()); + for p in faces.chain(s.edges.iter_mut().filter_map(|e| e.paint.as_mut())) { + appearance(p, fix); + } + } } if let Some(ch) = n.children_mut() { for c in ch { @@ -185,6 +218,46 @@ mod tests { assert!((r(&d, 0) - 100.0).abs() < 1e-9, "{}", r(&d, 0)); } + /// Shaper face and edge edits paint with appearances of their own, and brush definitions keep + /// their art as JSON: their radii convert both ways too. + #[test] + fn shaper_edits_and_brushes_are_converted_both_ways() { + use crate::shaper::{FaceEdit, FaceSelector, ShaperSpec}; + let mut d = Document::new(100.0, 100.0); + d.raster_effects_ppi = 300.0; + d.version = 1; + let mut look = Appearance::default_art(); + look.effects = vec![halftone(Some(8.0))]; + let face = FaceEdit { + selector: FaceSelector { sources: vec![0], anchor: vectorcraft_geom::Point::ZERO }, + erase: false, + erase_edges: false, + paint_source: None, + merge: None, + paint: Some(look), + }; + let mut shaper = Node::group(d.alloc_id(), vec![]); + shaper.extras_mut().shaper = Some(Box::new(ShaperSpec { faces: vec![face], edges: vec![] })); + let l = d.layers[0].id; + d.insert(Some(l), 0, shaper).unwrap(); + let effect = serde_json::to_value(halftone(Some(8.0))).unwrap(); + d.unknown.insert(BRUSHES.into(), json!([{"name": "B", "art": {"id": 99, "appearance": {"effects": [effect]}}}])); + let radii = |d: &Document| { + let shaper = d.layers[0].children().and_then(|c| c.first()).cloned().unwrap(); + let paint = shaper.extras().shaper.as_ref().and_then(|s| s.faces[0].paint.clone()).unwrap(); + let brush = d.unknown[BRUSHES][0]["art"]["appearance"]["effects"][0]["params"][RADIUS].as_f64().unwrap(); + (radius(&paint.effects[0]), brush) + }; + d.migrate_halftone_radii(); + let (face, brush) = radii(&d); + assert!((face - 33.333333333333336).abs() < 1e-9, "the face edit: {face}"); + assert!((brush - 33.333333333333336).abs() < 1e-9, "the brush: {brush}"); + assert_eq!(d.unknown[BRUSHES][0]["art"]["appearance"]["effects"][0]["params"]["channel1"], json!(108.0)); + d.halftone_radii_to_points(); + let (face, brush) = radii(&d); + assert!((face - 8.0).abs() < 1e-9 && (brush - 8.0).abs() < 1e-9, "back in points: {face}, {brush}"); + } + #[test] fn the_pattern_being_edited_is_converted_as_it_was() { let mut d = Document::new(100.0, 100.0); From ce4f16369e5bdf25c0b41675fb799945efe011a3 Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Wed, 4 Nov 2026 21:05:43 -0500 Subject: [PATCH 005/196] PDF import: a DeviceN gradient of a spot ink over process plates keeps the ink and the plates, and PDF export writes it as DeviceN again (#3235) --- crates/color/src/gradient.rs | 11 ++++- crates/engine/src/cmd/gradient.rs | 19 ++++++++- crates/engine/src/tests/linked_stops.rs | 21 +++++++++ crates/eps/src/scene.rs | 7 ++- crates/eps/src/tests.rs | 10 +++++ crates/pdf/src/export/paint.rs | 11 +++-- crates/pdf/src/import_color.rs | 35 +++++++++++++++ crates/pdf/src/import_shading.rs | 33 ++++++++------ crates/pdf/src/tests/import_color.rs | 57 ++++++++++++++++++++++++- crates/tools/src/params.rs | 3 ++ docs/file-format-parity.md | 3 +- docs/target-app-parity.md | 5 ++- 12 files changed, 189 insertions(+), 26 deletions(-) diff --git a/crates/color/src/gradient.rs b/crates/color/src/gradient.rs index 794f92aeea..8e947c1436 100644 --- a/crates/color/src/gradient.rs +++ b/crates/color/src/gradient.rs @@ -151,16 +151,23 @@ pub struct GradientStop { /// Tint of the linked swatch (0..1; 1 without a link), as on a solid paint. #[serde(default = "crate::full_tint", skip_serializing_if = "crate::is_full_tint")] pub tint: f32, + /// Process inks (C, M, Y, K, 0..1) printed together with the linked spot swatch's tint: a + /// DeviceN colour of a file that mixes a spot ink with process plates. `color` is how the mix + /// looks; separations print the spot ink at `tint` and these plates. `None`: the ink alone. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub plates: Option<[f32; 4]>, } impl GradientStop { /// An opaque, unlinked stop of `color` at `offset` with a centred midpoint. pub fn new(offset: f32, color: Color) -> Self { - Self { offset, color, opacity: 1.0, midpoint: 0.5, swatch: None, tint: 1.0 } + Self { offset, color, opacity: 1.0, midpoint: 0.5, swatch: None, tint: 1.0, plates: None } } - /// Give the stop `color`, linked to `link` (a global swatch and tint) or unlinked. + /// Give the stop `color`, linked to `link` (a global swatch and tint) or unlinked, without + /// process plates. pub fn set_color(&mut self, color: Color, link: Option<(String, f32)>) { self.color = color; + self.plates = None; (self.swatch, self.tint) = match link { Some((n, t)) => (Some(n), t), None => (None, 1.0), diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index f777628f20..47989a29c0 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -197,7 +197,8 @@ pub(crate) fn with_stored_stops<'a>(g: &'a Value, old: &Paint, stored: &StopColo /// Parse `stops` params: at least two, each with a numeric `offset` (clamped to 0..1) and a valid /// `color`; `opacity` is 0..1 (values above 1 are percentages) and `midpoint` is clamped to the /// diamond's range; `swatch` and `tint` (%) keep a stop's link as given (resolve them first with -/// [`link_stops`]). The result is sorted by offset. +/// [`link_stops`]), and `plates` (C, M, Y, K, 0..1) the process inks a linked stop prints with its +/// spot ink. The result is sorted by offset. pub(crate) fn parse_stops(v: &Value) -> Parsed> { let arr = v.as_array().ok_or("`stops` must be an array")?; if arr.len() < 2 { @@ -213,6 +214,10 @@ pub(crate) fn parse_stops(v: &Value) -> Parsed> { let opacity = num("opacity")?.map(|o| if o > 1.0 { o / 100.0 } else { o }).unwrap_or(1.0); let swatch = str_param(st, "swatch").map(str::to_string); let tint = num("tint")?.filter(|_| swatch.is_some()).map_or(1.0, |t| (t / 100.0).clamp(0.0, 1.0) as f32); + let plates = match st.get("plates").filter(|_| swatch.is_some()) { + None | Some(Value::Null) => None, + Some(p) => Some(plates_param(p).ok_or_else(|| format!("stop {i}: `plates` must be four numbers from 0 to 1 (C, M, Y, K)"))?), + }; Ok(GradientStop { offset: offset.clamp(0.0, 1.0) as f32, color, @@ -220,6 +225,7 @@ pub(crate) fn parse_stops(v: &Value) -> Parsed> { midpoint: num("midpoint")?.unwrap_or(0.5).clamp(0.13, 0.87) as f32, swatch, tint, + plates, }) }) .collect::>>()?; @@ -227,6 +233,17 @@ pub(crate) fn parse_stops(v: &Value) -> Parsed> { Ok(out) } +/// A stop's `plates` param: the process inks (C, M, Y, K, 0..1) printed with its spot swatch. +fn plates_param(v: &Value) -> Option<[f32; 4]> { + let a = v.as_array().filter(|a| a.len() == 4)?; + let mut out = [0.0f32; 4]; + for (o, x) in out.iter_mut().zip(a) { + let x = x.as_f64().filter(|x| x.is_finite())?; + *o = x.clamp(0.0, 1.0) as f32; + } + Some(out) +} + /// Parse a gradient paint object (the `gradient` param of `paint.setFill`). Lossless for everything /// `vectorcraft_tools::params::gradient_params` writes. pub(crate) fn parse_gradient(g: &Value) -> Parsed { diff --git a/crates/engine/src/tests/linked_stops.rs b/crates/engine/src/tests/linked_stops.rs index eb4712cfce..951a9ec31a 100644 --- a/crates/engine/src/tests/linked_stops.rs +++ b/crates/engine/src/tests/linked_stops.rs @@ -192,6 +192,27 @@ fn spot_gradients_mixed_with_other_inks_export_as_device_n_shadings() { assert!(!warnings.iter().any(|w| w.contains("spot")), "{warnings:?}"); } +#[test] +fn spot_stops_with_process_plates_export_both_in_device_n_shadings() { + // #3235: Ink 0 % to 100 % over a constant 30 % cyan plate, as a DeviceN gradient imported + // from a PDF has it. + let (mut s, id) = setup(); + let cyan = json!({"c": 0.3, "m": 0, "y": 0, "k": 0}); + run(&mut s, "paint.editGradient", json!({"stops": [{"offset": 0, "color": cyan}, {"offset": 1, "swatch": "Ink", "plates": [0.3, 0, 0, 0]}]})); + let (pdf, warnings) = pdf_of(&s); + assert!(pdf.contains("/DeviceN[/Cyan/Ink]/DeviceCMYK"), "a DeviceN shading of Cyan and Ink"); + assert!(pdf.contains("/C0[0.3 0]/C1[0.3 1]"), "the cyan plate runs under the whole gradient"); + assert!(!warnings.iter().any(|w| w.contains("spot")), "{warnings:?}"); + let stops = gradient(&s, id).gradient.stops; + assert_eq!((stops[1].swatch.as_deref(), stops[1].plates), (Some("Ink"), Some([0.3, 0.0, 0.0, 0.0])), "{stops:?}"); + // The plates are part of the stop's params, so moving the vector keeps them. + run(&mut s, "paint.editGradient", json!({"angle": 45})); + assert_eq!(gradient(&s, id).gradient.stops[1].plates, Some([0.3, 0.0, 0.0, 0.0])); + // An unlinked stop has none. + run(&mut s, "paint.editGradient", json!({"stops": [{"offset": 0, "color": cyan}, {"offset": 1, "color": "#ffffff", "plates": [0.3, 0, 0, 0]}]})); + assert_eq!(gradient(&s, id).gradient.stops[1].plates, None); +} + #[test] fn radial_spot_gradients_mixed_with_other_inks_export_as_device_n_shadings() { let (mut s, _) = setup(); diff --git a/crates/eps/src/scene.rs b/crates/eps/src/scene.rs index 64c5da6d4d..1c3143f3f6 100644 --- a/crates/eps/src/scene.rs +++ b/crates/eps/src/scene.rs @@ -751,7 +751,8 @@ impl<'a> Scene<'a> { /// The stops of a gradient with a spot ink as tints of its inks: a Separation space when every /// stop is a tint of one spot ink or paper white, else (at Level 3) a DeviceN space of the /// process inks the stops use, in CMYK order, and the spot inks, in the order the stops name - /// them. Paper white adds no ink and a gray stop is black ink. An off-center midpoint is a stop + /// them. Paper white adds no ink, a gray stop is black ink, and a spot stop's process plates + /// print with its ink. An off-center midpoint is a stop /// with the inks halfway between its two stops. `None` for a gradient without a spot ink, and, /// with a warning, for one whose inks can't be kept or that is mixed by the Perceptual method; /// it is then written in process colors. @@ -799,6 +800,10 @@ impl<'a> Scene<'a> { if let Some(i) = names.iter().position(|m| *m == n) { v[4 + i] = unit(s.tint); } + // Process plates printed with the spot ink (a DeviceN mix from a file). + if let Some(p) = s.plates { + v[..4].copy_from_slice(&p.map(unit)); + } } None if paper(&s.color) => {} None => match self.process(&s.color) { diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs index 2067a7d9c2..2a59f99df2 100644 --- a/crates/eps/src/tests.rs +++ b/crates/eps/src/tests.rs @@ -352,6 +352,16 @@ fn gradients_mixing_spot_inks_with_other_inks_are_device_n_shadings() { assert!(page.contains("/C0 [0 0 1] /C1 [0.6 0 0]") && page.contains("/C0 [0.6 0 0] /C1 [0 0.4 0]"), "{page}"); assert!(!out.warnings.iter().any(|w| w.contains("spot")), "{:?}", out.warnings); + // Gold Ink 0% to 100% over a constant 30% cyan plate (a DeviceN gradient read from a PDF, + // #3235): Cyan and Gold Ink. + let mut over = spot_stop(1.0, "Gold Ink", GOLD, 1.0); + over.plates = Some([0.3, 0.0, 0.0, 0.0]); + let plated = spot_gradient_doc(vec![GradientStop::new(0.0, Color::cmyk(0.3, 0.0, 0.0, 0.0)), over]); + let out = export(&plated, &opts(&plated), None, None).unwrap(); + let ps = text(&out); + assert!(ps.contains("/VCdn0 [/DeviceN [/Cyan (Gold Ink) cvn ] /DeviceCMYK {2 array astore"), "{ps}"); + assert!(checked_page(&ps).contains("/C0 [0.3 0] /C1 [0.3 1]"), "{ps}"); + // Read back as bands, the tint transforms give each ink's CMYK equivalent. for (d, end) in [(&two, [0.5, 0.0, 0.5, 0.0]), (&mixed, [0.0, 0.0, 0.0, 0.4])] { let out = export(d, &EpsOptions { compatible_gradients: true, ..opts(d) }, None, None).unwrap(); diff --git a/crates/pdf/src/export/paint.rs b/crates/pdf/src/export/paint.rs index 379ebbd506..3138484ebd 100644 --- a/crates/pdf/src/export/paint.rs +++ b/crates/pdf/src/export/paint.rs @@ -92,7 +92,8 @@ impl Exporter<'_> { .stops .iter() .map(|s| match s.swatch.as_deref() { - Some(n) if n == ink => Some(s.tint), + // A stop that also prints process plates needs a DeviceN space. + Some(n) if n == ink && s.plates.is_none() => Some(s.tint), _ if self.paper_stop(s) => Some(0.0), _ => None, }) @@ -119,7 +120,8 @@ impl Exporter<'_> { /// a DeviceN space of the process inks the stops use (in CMYK order) and the spot inks (in /// the order the stops name them), with midpoints as explicit stops (the tints and opacity /// there are halfway), or for a Perceptual gradient the stops on its curve - /// ([`vectorcraft_color::Gradient::ink_mixes`]). Paper white adds no ink. `None`, with a + /// ([`vectorcraft_color::Gradient::ink_mixes`]). Paper white adds no ink; a spot stop with + /// process plates ([`vectorcraft_color::GradientStop::plates`]) prints them too. `None`, with a /// warning, when a stop is written in RGB or Lab or the spot inks can't share a DeviceN space; /// the gradient is then written in the colors of its stops. fn device_n_stops(&mut self, g: &vectorcraft_color::Gradient) -> Option> { @@ -145,6 +147,9 @@ impl Exporter<'_> { Some(n) => { let i = spots.iter().position(|(m, _)| *m == n)?; v[4 + i] = s.tint; + if let Some(p) = s.plates { + v[..4].copy_from_slice(&p.map(|t| t.clamp(0.0, 1.0))); + } } None if self.paper_stop(s) => {} None => match self.page_color(&s.color) { @@ -379,7 +384,7 @@ impl Exporter<'_> { fn one_spot_ink<'g>(&self, g: &'g vectorcraft_color::Gradient) -> Option<&'g str> { let spot = |s: &'g vectorcraft_color::GradientStop| s.swatch.as_deref().filter(|n| self.doc.swatch(n).is_some_and(|w| w.spot)); let ink = g.stops.iter().find_map(spot)?; - g.stops.iter().all(|s| spot(s) == Some(ink) || self.paper_stop(s)).then_some(ink) + g.stops.iter().all(|s| (spot(s) == Some(ink) && s.plates.is_none()) || self.paper_stop(s)).then_some(ink) } /// Can every stop of `g` be inks of a DeviceN space ([`Self::device_n_stops`]): is a stop diff --git a/crates/pdf/src/import_color.rs b/crates/pdf/src/import_color.rs index 2362634edb..b7e033b6ce 100644 --- a/crates/pdf/src/import_color.rs +++ b/crates/pdf/src/import_color.rs @@ -323,6 +323,41 @@ impl<'p> Colors<'p> { } } + /// A gradient stop's colour that paints one spot ink together with process plates (a + /// DeviceN colour of an ink and process colorants): the ink's swatch (marked used), its tint + /// and the process plates (C, M, Y, K). `None` for any other colour ([`Colors::native`] takes + /// it). + pub fn ink_with_plates(&mut self, space: Space, comps: &[f32]) -> Option<(String, f32, [f32; 4])> { + let Space::Inks(i) = space else { return None }; + let colorants = &self.spaces.get(i)?.colorants; + let mut cmyk = [0.0f32; 4]; + let mut ink = None; + for (c, t) in colorants.iter().zip(comps) { + let t = round3(t.clamp(0.0, 1.0)); + match *c { + Colorant::Unknown => return None, + Colorant::None => {} + Colorant::Process(ch) => { + if let Some(v) = cmyk.get_mut(ch) { + *v = v.max(t); + } + } + // A second ink (or every plate) painting too can't be one stop. + Colorant::Ink(_) | Colorant::All if t > 0.0 && ink.is_some() => return None, + Colorant::All if t > 0.0 => return None, + Colorant::Ink(k) if t > 0.0 => ink = Some((k, t)), + Colorant::Ink(_) | Colorant::All => {} + } + } + let (k, t) = ink?; + if cmyk.iter().all(|v| *v <= 0.0) { + return None; + } + let ink = self.inks.get_mut(k)?; + ink.used = true; + Some((ink.name.clone(), t, cmyk)) + } + /// Mark each ink that components `comps` of `space` paint with (a tint above 0) as used, so it /// becomes a spot swatch; nothing for a space with a colorant that can't be read. pub fn mark_inks(&mut self, space: Space, comps: &[f32]) { diff --git a/crates/pdf/src/import_shading.rs b/crates/pdf/src/import_shading.rs index a8a8b25eaa..c80b2a29b4 100644 --- a/crates/pdf/src/import_shading.rs +++ b/crates/pdf/src/import_shading.rs @@ -17,7 +17,7 @@ use vectorcraft_doc::{AppearanceItem, Node, NodeKind, OpacityMask}; use vectorcraft_geom::PathData; use crate::import::{closed_subpaths, round3}; -use crate::import_color::{Colors, Native}; +use crate::import_color::{Colors, Native, Space}; use crate::import_mask::{contains, is_rectangle, luminance}; /// The most mesh patches (or triangles) imported per shading: past it, the shading is a flat @@ -51,14 +51,8 @@ pub(crate) fn shading_gradient(sp: &ShadingPattern, colors: &mut Colors<'_>, ink } } let ts: Vec = linear_keep(&pts).iter().filter_map(|&k| pts.get(k)).map(|p| p.0).collect(); - let mut stop_at = |t: f32, offset: f32| -> GradientStop { - let rgb = sample(t).unwrap_or(Color::BLACK); - match at(t).and_then(|v| colors.native(space, &v)) { - Some(Native { color, link: Some((name, tint)) }) => GradientStop { swatch: Some(name), tint, ..GradientStop::new(offset, color) }, - Some(Native { color, link: None }) => GradientStop::new(offset, color), - None => GradientStop::new(offset, rgb), - } - }; + let mut stop_at = + |t: f32, offset: f32| -> GradientStop { shading_stop(colors, space, at(t).as_deref(), offset, sample(t).unwrap_or(Color::BLACK)) }; let c = |x: f32, y: f32| m * Point::new(x as f64, y as f64); let (kind, geom, stops) = if *axial { let geom = GradientGeom { start: c(coords[0], coords[1]), end: c(coords[2], coords[3]), aspect: 1.0, focal: None }; @@ -81,6 +75,21 @@ pub(crate) fn shading_gradient(sp: &ShadingPattern, colors: &mut Colors<'_>, ink Some((g, *extend)) } +/// A shading's stop at `offset` of components `comps` of `space` in their own model, linked to +/// its spot swatch at its tint (with the process plates it prints with, looking like `rgb`, the +/// colour the file gives it); `rgb` when the components can't be read or kept. +fn shading_stop(colors: &mut Colors<'_>, space: Space, comps: Option<&[f32]>, offset: f32, rgb: Color) -> GradientStop { + let Some(v) = comps else { return GradientStop::new(offset, rgb) }; + if let Some((name, tint, plates)) = colors.ink_with_plates(space, v) { + return GradientStop { swatch: Some(name), tint, plates: Some(plates), ..GradientStop::new(offset, rgb) }; + } + match colors.native(space, v) { + Some(Native { color, link: Some((name, tint)) }) => GradientStop { swatch: Some(name), tint, ..GradientStop::new(offset, color) }, + Some(Native { color, link: None }) => GradientStop::new(offset, color), + None => GradientStop::new(offset, rgb), + } +} + /// The samples of `pts` (offset, RGB; at least one) a gradient keeps as stops: the first, the /// last, and each one that linear interpolation between its neighbouring stops doesn't reproduce. fn linear_keep(pts: &[(f32, [f32; 3])]) -> Vec { @@ -299,11 +308,7 @@ fn function_gradient(sp: &ShadingPattern, colors: &mut Colors<'_>, inks: Option< for k in linear_keep(&pts) { let Some(&(offset, read, c)) = piece.get(k) else { continue }; let rgb = Color::rgb(round3(c[0]), round3(c[1]), round3(c[2])); - out.push(match value(read).and_then(|v| colors.native(space, &v)) { - Some(Native { color, link: Some((name, tint)) }) => GradientStop { swatch: Some(name), tint, ..GradientStop::new(offset, color) }, - Some(Native { color, link: None }) => GradientStop::new(offset, color), - None => GradientStop::new(offset, rgb), - }); + out.push(shading_stop(colors, space, value(read).as_deref(), offset, rgb)); } } if out.len() > MAX_FUNCTION_STOPS { diff --git a/crates/pdf/src/tests/import_color.rs b/crates/pdf/src/tests/import_color.rs index e26697858f..011f298eea 100644 --- a/crates/pdf/src/tests/import_color.rs +++ b/crates/pdf/src/tests/import_color.rs @@ -178,12 +178,65 @@ fn a_spot_ink_mixed_with_a_process_plate_keeps_its_swatch() { for (what, page) in [("fill", fill), ("shading", sh)] { let r = import_with_report(&pdf_with(&[page], &[func], None), &ImportOptions::default()).unwrap(); let d = &r.document; - assert!(r.warnings.iter().any(|w| w.contains("several inks")), "{what}: {:?}", r.warnings); - assert!(links(d).iter().all(Option::is_none), "{what}: the art stays RGB"); let gold = d.swatch("Gold").unwrap_or_else(|| panic!("{what}: no Gold swatch")); assert!(gold.spot && gold.global, "{what}: Gold is a spot swatch"); assert!(near(gold.paint.color().unwrap(), Color::cmyk(0.0, 0.0, 1.0, 0.0)), "{what}: {gold:?}"); assert_eq!(d.swatches.iter().filter(|s| s.spot).count(), 1, "{what}: Cyan is a process plate"); + if what == "fill" { + // A solid paint can't link to an ink and process plates together. + assert!(r.warnings.iter().any(|w| w.contains("several inks")), "{what}: {:?}", r.warnings); + assert!(links(d).iter().all(Option::is_none), "{what}: the art stays RGB"); + } + } +} + +/// A gradient stop of `d`'s only gradient, in paint order. +fn gradient_stops(d: &Document) -> Vec { + let mut out = vec![]; + d.walk(|n: &Node| { + for i in &n.appearance.items { + if let Paint::Gradient(g) = i.paint() { + out.extend(g.gradient.stops.iter().cloned()); + } + } + }); + out +} + +#[test] +fn a_device_n_gradient_of_a_spot_ink_over_a_process_plate_keeps_both_inks() { + // #3235: an axial shading in [/DeviceN [/Gold /Cyan] /DeviceCMYK …], Gold 0 to 1 over Cyan + // at 0.3 (ISO 32000-1:2008, 8.6.6.5 and 8.7.4.5.3). Its stops link to Gold, with the cyan + // plate kept, and PDF export (PDF/X-4 too) writes it again as a DeviceN shading of both inks. + let space = format!("[/DeviceN [/Gold /Cyan] /DeviceCMYK {} 0 R]", first_extra(1)); + let func = "<< /FunctionType 4 /Domain [0 1 0 1] /Range [0 1 0 1 0 1 0 1] /Length 17 >>\nstream\n{ exch 0 exch 0 }\nendstream"; + let shading = format!( + "<< /ShadingType 2 /ColorSpace {space} /Coords [0 0 50 0] /Function << /FunctionType 2 /Domain [0 1] /C0 [0 0.3] /C1 [1 0.3] /N 1 >> /Extend [true true] >>" + ); + let page = PdfPage { resources: format!("/Shading << /Sh0 {shading} >>"), ..PdfPage::new(100.0, 50.0, "q 0 0 50 50 re W n /Sh0 sh Q") }; + let r = import_with_report(&pdf_with(&[page], &[func], None), &ImportOptions::default()).unwrap(); + assert!(!r.warnings.iter().any(|w| w.contains("several inks")), "{:?}", r.warnings); + let d = &r.document; + let stops = gradient_stops(d); + let (Some(first), Some(last)) = (stops.first(), stops.last()) else { panic!("no gradient: {stops:?}") }; + // Gold at 0 % is cyan alone; Gold at 100 % keeps the cyan plate. + assert_eq!((first.swatch.as_deref(), first.plates), (None, None), "{first:?}"); + assert!(near(first.color, Color::cmyk(0.3, 0.0, 0.0, 0.0)), "{first:?}"); + assert_eq!(last.swatch.as_deref(), Some("Gold"), "{last:?}"); + assert!((last.tint - 1.0).abs() < 1e-3, "{last:?}"); + let plates = last.plates.unwrap_or_else(|| panic!("no plates: {last:?}")); + assert!((plates[0] - 0.3).abs() < 1e-3 && plates[1..].iter().all(|p| *p == 0.0), "{plates:?}"); + // The stop looks as the file draws it: cyan and yellow, a green. + let [r_, g_, b_] = last.color.to_rgb(); + assert!(g_ > r_ && g_ > b_, "{:?}", last.color); + for standard in [Standard::None, Standard::PdfX4] { + let mut o = PdfOptions::uncompressed(); + (o.settings.standard, o.settings.compatibility) = (standard, standard.version()); + let text = String::from_utf8_lossy(&export(d, &o).unwrap()).into_owned(); + assert!(text.contains("/DeviceN [/Cyan /Gold]") || text.contains("/DeviceN[/Cyan/Gold]"), "{standard:?}: no DeviceN space of Cyan and Gold"); + assert!(text.contains("/Separation /Gold") || text.contains("/Separation/Gold"), "{standard:?}: Gold has no Separation colorant"); + assert!(text.contains("/C0 [0.3 0]") || text.contains("/C0[0.3 0]"), "{standard:?}: the first stop is cyan alone"); + assert!(text.contains("/C1 [0.3 1]") || text.contains("/C1[0.3 1]"), "{standard:?}: the last stop is cyan and Gold"); } } diff --git a/crates/tools/src/params.rs b/crates/tools/src/params.rs index 8c3565ba2a..49a5a9a3c1 100644 --- a/crates/tools/src/params.rs +++ b/crates/tools/src/params.rs @@ -25,6 +25,9 @@ pub fn stops_json(stops: &[GradientStop]) -> Value { if let Some(n) = &s.swatch { v["swatch"] = json!(n); v["tint"] = json!(s.tint * 100.0); + if let Some(p) = s.plates { + v["plates"] = json!(p); + } } v }) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 206f368016..2ccf281a1e 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (native format: dynamic symbols, #4938) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (PDF import: DeviceN gradients of a spot ink over process plates, #3235) · **Target:** Adobe Illustrator 2026 (30.x) Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`, `OPEN_EXTS`, `PLACE_EXTS` in `crates/engine/src/cmd/fileio/formats.rs`). Illustrator's list comes from its public @@ -169,6 +169,7 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri | Date | Change | Summary | |---|---|---| +| 2026-11-05 | minor | PDF import: the stops of an axial or radial shading in a DeviceN space of one spot ink and process plates link to the ink's swatch and keep the plates (`GradientStop.plates` in the native format); PDF and EPS export write them in a DeviceN space again (#3235) | | 2026-11-01 | minor | Native format: a symbol's Symbol Type (`dynamic`) and a dynamic symbol instance's appearance changes to objects of its art (`symbol_overrides`) round-trip; both are left out when unset, so other documents save unchanged (#4938). `.ai` reading and writing of dynamic symbols remains. | | 2026-11-01 | minor | Exports draw each artboard's background color behind its art (#4937): PNG, JPEG, GIF, TIFF, WebP, BMP, Targa and PSD (a layer of its own; on a transparent background too), PDF, SVG and EPS pages, a `.ai` file's PDF pages and PostScript and PDF print; `includeArtboardFill: false` leaves it out. Files with editing data (Preserve Editing, `.ai`, EPS, native) keep it as the artboard's color and reopen without extra art. Not read from the reference app's own `.ai` data, nor written to it. DXF, EMF and WMF leave it out | | 2026-10-31 | minor | PDF import finds an installed font whose PDF name holds hyphens (`Noto-Sans-Bold` is Noto Sans, Bold: the longest part before a hyphen that names an installed family) and a composite font by its CIDFont's name rather than its base name, which ends in the CMap's (`Name-Identity-H`, [ISO 32000-1 §9.7.6.1](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf)); a missing font is split only before a style part (`Helvetica-BoldOblique`), so it is reported as `MS PGothic`, not `MS`; scores unchanged (estimated) | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c75c85b765..d3315bf5ac 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-05 · **Change:** minor (Transform Each: Relative and Absolute scaling and the documented panel order; 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-05 · **Change:** minor (PDF import keeps DeviceN gradients of a spot ink over process plates, #3235; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -24,6 +24,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| | 2026-11-04 | minor | Transform Each's Scale has the documented Relative and Absolute radio buttons (`object.transformEach` `relative`: percentages of each object's size, or the width and height it becomes, measured on each object's own bounds) and the link that keeps the two scales in proportion; the panel lists Scale, Move, Rotate, the Options in two columns, the Reference Point and Preview (level with Copy, Cancel and OK) in the documented order. Scores and estimates unchanged. | +| 2026-11-05 | minor | PDF import: a DeviceN gradient of a spot ink over process plates keeps the ink and the plates, and PDF export writes it as a DeviceN shading again (#3235); scores unchanged | | 2026-11-05 | minor | Optical kerning moves each pair part of the way toward the font's own stem spacing, with a minimum gap and tighter limits, and leaves ideographs, kana, fullwidth forms and dashes on the font's spacing, so text is no longer squeezed (#5336). Scores and estimates unchanged. | | 2026-11-04 | minor | Type core: a Type-range Copy or Cut publishes styled art alongside plain text, so canvas Paste keeps font family, size and color after editing ends (#5636); scores and estimates unchanged. | | 2026-11-04 | minor | Selection Tools add-on: Select by Artboards selects the objects overlapping, fully inside or fully outside several chosen artboards, from a dialog that lists, searches and multi-selects the artboards and fits one in the window on double-click (#5525, #5548, #5549, a VectorCraft addition); scores and estimates unchanged. | @@ -1134,7 +1135,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Files (M4):** - PDF export and print composition use the optional shared guarded writer ([pdf-backend.md](pdf-backend.md)); app drawing and output policy and desktop printer submission remain in their existing layers. The shared reader keeps the app-owned import adapter; synthetic tests cover layer and overprint state across windows, long operands, inline images, failed decoding, document limits and incomplete tails. Empty and populated metadata key presence is regression-tested, and CI checks the immutable backend source. Invisible text in a PDF (rendering mode 3, which carries a scanned page's recognized text over the scan) opens as type with no fill or stroke, a run of its own beside visible text on the same line; text that can't come in as type (opened as outlines, Type 3 fonts) is left out with a warning. PDF export, and printing, write characters with no fill or stroke as real text in rendering mode 3, so they draw nothing but stay selectable and searchable, also in PDF/X-1a and PDF/A-2b (#2675, `pdf/src/tests/import_fidelity.rs`, `pdf/src/tests/realtext.rs`). - A PDF, or a `.ai` read through its PDF part, whose spot inks have the same values but different names opens with a spot swatch for each ink. The solid fills and strokes of paths and type, and the stops of gradients on paths, link to the swatch of the ink they are painted in, the points of a gradient mesh in one of these inks keep the ink's color, and PDF export writes each of these inks as its own separation (`pdf/src/tests/import_color.rs`). Paint in these inks inside pattern cells, soft masks and type 3 glyphs, and gradients on type in these inks, still import as RGB. Type in one of these inks can also import as RGB when type in another Separation or DeviceN ink is shown with no path drawn between them. + A PDF, or a `.ai` read through its PDF part, whose spot inks have the same values but different names opens with a spot swatch for each ink. The solid fills and strokes of paths and type, and the stops of gradients on paths, link to the swatch of the ink they are painted in, the points of a gradient mesh in one of these inks keep the ink's color, and PDF export writes each of these inks as its own separation (`pdf/src/tests/import_color.rs`). Paint in these inks inside pattern cells, soft masks and type 3 glyphs, and gradients on type in these inks, still import as RGB. Type in one of these inks can also import as RGB when type in another Separation or DeviceN ink is shown with no path drawn between them. The stops of an axial or radial shading in a DeviceN space that mixes one spot ink with process plates (a spot ink over a constant cyan, for example) link to the ink's swatch at its tint and keep the process plates, and PDF and EPS (Level 3) export write those stops in a DeviceN space of the ink and those plates, so the spot plate is not lost (#3235, `import_color::a_device_n_gradient_of_a_spot_ink_over_a_process_plate_keeps_both_inks`). Solid fills that mix a spot ink with process plates, and stops that mix several spot inks, still import as RGB, with the spot inks kept as swatches. PDF export writes a linear or radial gradient that mixes a spot color with process colors, or two spot colors, as a DeviceN shading of the spot inks and the process inks its stops use, so each spot ink prints on its own plate; an off-center midpoint is written as a stop with the inks halfway between its two stops. A gradient that mixes a spot color with RGB or Lab colors is still written without the spot ink, with a warning. A Perceptual gradient of spot inks is written as a Separation or DeviceN shading of the stops on its curve; a dithered gradient fill, and a Perceptual gradient with RGB or Lab stops other than white or more than 4,096 stops on its curve, are written as images in process colors, with a warning. A Lab spot color in such a shading is named by the same Separation space, with the Lab alternate, as its flat fills (`engine/src/tests/linked_stops.rs`, `engine/src/tests/labspots.rs`). PDF export writes a spot color named All or None (in a Separation space, the names of every plate and of no plate: [ISO 32000-1:2008](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf), 8.6.6.4) as the ink All Spot or None Spot (All Spot 2 and on when a spot swatch already has that name) in its fills, strokes, gradients, colorized images and Lab alternates; Registration still prints on every plate (`pdf/src/tests/output.rs`). - `.vectorcraft` (lossless JSON, compressed, atomic saves, save down to v1), Save As with a format chooser, Save a Copy, Revert, templates, Data Recovery after a crash (browser tabs hold their copies with Web Locks too, so a background tab's copies are never taken for a crash's, and a tab repairs copies another removed when it resumes: #367), background save and export. The desktop app writes its warnings and errors (graphics adapter, a lost graphics device, panics the guard recovered from) to standard error and to `logs/vectorcraft.log` next to the preferences, the two previous runs kept and each file capped at 16 MiB, so a launch without a terminal still leaves something to attach to a bug report (#465). Native documents with a lot of path data (traced or generated art, in layers, symbols or patterns) are saved as compact JSON, about a fifth of the size; small documents stay pretty-printed (#1492). Saving to a network drive on macOS falls back to a plain fsync when the share refuses a full flush (#1625, part of #1620; not confirmed on a real share), and a save still succeeds when a folder refuses the temporary file, the rename over the document or copying permissions: the content is written elsewhere first and copied in, and a failed copy keeps the temporary file and names it (#1649, part of #1620). A document opened by a relative path finds its relatively linked images, and `vectorcraft-cli convert` lists what reading the input left out as `importWarnings` (#1606, fixes #1604). From 23bcef97c7d1ebac7af2ca3941ec1ce7dd164fe0 Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Wed, 4 Nov 2026 21:20:51 -0500 Subject: [PATCH 006/196] Isolation mode: a locked or hidden layer keeps the isolated art from clicks and marquees (#5309) Locking or hiding the layer (or a group) around the isolated object left its art selectable with the Selection tool: the isolation branch of the hit test only checked for a locked artboard, and the marquee's checked nothing. Both now pass over isolated art that isn't editable. --- crates/doc/src/hit.rs | 8 ++++-- crates/engine/src/tests/compound_shape.rs | 32 +++++++++++++++++++++++ docs/ui-parity.md | 5 ++-- 3 files changed, 41 insertions(+), 4 deletions(-) diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index cb972b94f8..8b498fd3d7 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -508,8 +508,9 @@ fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(No && let Some(isolated) = doc.node(scope) && let Some(mut chain) = doc.ancestry(scope) { - // Isolated before its artboard was locked: nothing in it hits. - if locks.holds_id(scope) { + // Isolated before its artboard, or its layer or a group around it, was locked or hidden: + // nothing in it hits (#5309). + if !doc.is_editable_with(&locks, scope) { return None; } if isolated.is_container() { @@ -893,6 +894,9 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh let mut out = Vec::new(); // `tops` pairs each object with the part of `r` in which the marquee can touch it. let tops: Vec<(&std::sync::Arc, Rect)> = match scope.and_then(|s| doc.node(s)) { + // Isolated art whose layer, or a group around it, was locked or hidden afterwards: the + // marquee touches none of it, as clicks don't (#5309). + Some(s) if !doc.is_editable(s.id) => vec![], Some(s) => match (s.children(), marquee_in(s, r)) { (Some(c), Some(r)) => c.iter().enumerate().filter(|(i, _)| !shaper_hides(s, *i, scope)).map(|(_, c)| (c, r)).collect(), (Some(_), None) => vec![], diff --git a/crates/engine/src/tests/compound_shape.rs b/crates/engine/src/tests/compound_shape.rs index 2de8a35b95..7455fbfa5a 100644 --- a/crates/engine/src/tests/compound_shape.rs +++ b/crates/engine/src/tests/compound_shape.rs @@ -664,3 +664,35 @@ fn expanded(s: &mut Session, id: NodeId) -> f64 { let made = run(s, "object.compoundShape.expand", json!({})); node_area(&node(s, NodeId(made["ids"][0].as_u64().unwrap()))) } + +/// Locking (or hiding) the layer of an isolated compound shape locks its members too: a click or +/// a marquee with the Selection tool selects none of them, as outside isolation mode (#5309). +#[test] +fn a_locked_or_hidden_layer_keeps_the_isolated_compound_shape_from_clicks() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + for (prop, value) in [("locked", true), ("visible", false)] { + let (mut s, back, _front) = two_squares(); + let id = NodeId(run(&mut s, "object.compoundShape.make", json!({}))["id"].as_u64().unwrap()); + run(&mut s, "object.isolate", json!({"id": id.0})); + let layer = s.doc().unwrap().doc.parent_of(id).unwrap(); + let v = ViewInfo::default(); + s.select_tool("selection", v).unwrap(); + let click = |s: &mut Session, x: f64, y: f64| { + for k in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(k, x, y), v).unwrap(); + } + }; + click(&mut s, 25.0, 50.0); + assert_eq!(selected(&s), vec![back], "isolated, a click selects a member"); + run(&mut s, "select.none", json!({})); + run(&mut s, "layer.setProps", json!({"id": layer.0, prop: value})); + click(&mut s, 25.0, 50.0); + assert!(selected(&s).is_empty(), "{prop}: the layer's art isn't selected by a click"); + for (k, x, y) in + [(PointerKind::Down, -10.0, -10.0), (PointerKind::Drag, 60.0, 60.0), (PointerKind::Drag, 120.0, 120.0), (PointerKind::Up, 120.0, 120.0)] + { + s.pointer(&PointerEvent::new(k, x, y), v).unwrap(); + } + assert!(selected(&s).is_empty(), "{prop}: nor by a marquee"); + } +} diff --git a/docs/ui-parity.md b/docs/ui-parity.md index df62d6dd29..50cda9a086 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (Transform Each: Relative and Absolute scaling and the documented panel order; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (isolation mode: a locked or hidden layer keeps the isolated art from clicks and marquees; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) ## Feature submission evidence @@ -30,6 +30,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | Isolation mode: once the layer, or a group, around the isolated object is locked or hidden, a click or a marquee with the Selection tool no longer selects the isolated art (part of #5309); scores and estimates unchanged | | 2026-11-04 | minor | Transform Each's Scale has the documented Relative and Absolute radio buttons: percentages of each object's size, or the width and height it becomes (`object.transformEach` `relative`); the two scales have the link that keeps them in proportion (`__constrain`, as the shape dialogs'), and the panel lists Scale, Move, Rotate, the Options in two columns, the Reference Point and Preview (level with Copy, Cancel and OK) in the documented order; scores and estimates unchanged | | 2026-11-04 | minor | Cmd+Space pressed during an active drawing drag keeps that tool's cursor; clarify that Space can move an in-progress shape or anchor. Scores and estimates unchanged. | | 2026-11-04 | minor | Selection Tools add-on: Select by Artboards selects the objects overlapping, fully inside or fully outside several chosen artboards, from a dialog that lists, searches and multi-selects the artboards and fits one in the window on double-click (#5525, #5548, #5549, a VectorCraft addition); scores and estimates unchanged. | @@ -157,7 +158,7 @@ tools, never checked side by side) isn't captured row by row. | Live Corners widgets (radius readout, Alt-click cycles kind, double-click the Corners dialog) | done | a Direct Selection click on a widget selects its corner (#1239); a press-and-drag on a widget of a path selected whole still rounds every corner (#908), and adding widgets to the selection by Shift-click (#1232) is missing; the bounding box hides while a widget is dragged with the Selection tool (#1229); a round corner next to a curved side curves smoothly instead of sticking out of the shape (#1512); a corner rounds until its cut reaches its neighbours' cuts, so one corner of a square alone reaches the whole side (#2332) | | Corners between curved sides (#1144), Relative rounding | done | #1144 closed; Relative rounding in the Corners dialog (Relative / Absolute, radius as a percentage of each corner's maximum, kept as the shape is resized; `object.setLiveShape` `relativeRadii`, #3091, `tests_livecorners::relative_corner_rounding_keeps_fraction_on_resize`) | | Pie widgets on a live ellipse: drag one to set Pie Start or End Angle, double-click one to make the ellipse whole | done | Selection tool, with the bounding box showing | -| Isolation mode by double-click (groups and single objects), breadcrumbs, Esc to exit | done | Single paths, compound paths, images, meshes and placed files isolate too ([helpx: Isolate objects](https://helpx.adobe.com/africa/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)) | +| Isolation mode by double-click (groups and single objects), breadcrumbs, Esc to exit | done | Single paths, compound paths, images, meshes and placed files isolate too ([helpx: Isolate objects](https://helpx.adobe.com/africa/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)); locking or hiding the layer (or a group) around the isolated object afterwards keeps clicks and marquees off it, as outside isolation mode (#5309) | | "Magnetic" moves of selected anchors with a modifier (#955 request) | missing | not a feature of the reference app as documented; under discussion | | Coinciding anchors of overlapping objects: the selected object's anchor is taken, also under another object | done | #1508 | From e82fd3d5ca7bd962e5df9d847eddd23355fba946 Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Wed, 4 Nov 2026 21:36:54 -0500 Subject: [PATCH 007/196] Numeric fields: a decimal comma works in arithmetic next to a number with a point (#5684) A numeric field read a comma as a decimal point only when the text had no point at all. A field shows its value with a point (100.5 pt), so typing -20,5 after it gave 100.5 pt-20,5, which kept its comma and was refused. Each number now reads its own separator: commas become points unless the text reads as thousands (1,000, as before). A number written with both separators (1.234,5, 1,000.5) ends up with two points and is still refused rather than guessed at. --- crates/ui-egui/src/panels/tests_constrain.rs | 15 +++++++++++++++ crates/ui-egui/src/widgets.rs | 15 ++++++++++++--- crates/ui-egui/src/widgets/numeric.rs | 8 +++++--- 3 files changed, 32 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/panels/tests_constrain.rs b/crates/ui-egui/src/panels/tests_constrain.rs index 8fa4c6e028..a90f2b55d1 100644 --- a/crates/ui-egui/src/panels/tests_constrain.rs +++ b/crates/ui-egui/src/panels/tests_constrain.rs @@ -256,6 +256,21 @@ fn a_thousands_comma_in_a_percentage_is_refused_in_a_size_field() { } } +/// Arithmetic with a decimal comma works in W (#5684), also after a value shown with a point; a +/// number with both separators is refused and leaves the size as it was. +#[test] +fn arithmetic_with_a_decimal_comma_works_in_a_size_field() { + let surfaces: [(&str, Draw); 3] = + [("Transform panel", transform::show), ("Properties", properties::transform_section), ("Control bar", crate::chrome::control_bar)]; + for (name, draw) in surfaces { + for (text, want) in [("100,5-20,5", 80.0), ("90-0,5*20", 80.0), ("10,5*2", 21.0), ("100.5 pt-20,5", 80.0), ("1.234,5", 100.0)] { + let mut app = rect_app(); + set_field(&mut app, draw, "100 pt", text, End::Enter(Modifiers::NONE)); + assert_eq!(size(&app), (want, 50.0), "{name}, {text}"); + } + } +} + /// A length field of the New Document dialog keeps the focus on Ctrl/Cmd+Enter, and the dialog /// creates no document. #[test] diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index ce798eef68..b5bc1991bd 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -441,9 +441,9 @@ mod step_to_multiple_tests { mod decimal_point_tests { use super::*; - /// A decimal comma reads as a point, in a length, with arithmetic and in a percentage; text - /// with a point keeps its commas and is refused as before, and so does a thousands comma - /// (#3837). + /// A decimal comma reads as a point, in a length, with arithmetic and in a percentage, next to + /// numbers written with a point too (#5684); a number with both separators is refused, and so + /// is a thousands comma (#3837). #[test] fn a_decimal_comma_reads_as_a_point() { let mm = |s: &str| Unit::Millimeters.parse(&decimal_point(s)).map(|pt| Unit::Millimeters.from_pt(pt)); @@ -460,6 +460,15 @@ mod decimal_point_tests { let got = mm(text).unwrap_or(f64::NAN); assert!((got - want).abs() < 1e-9, "{text} is a decimal: {got}"); } + // Each number reads its own separator: a comma typed after a value shown with a point + // (#5684). A number with both separators is refused. + for (text, want) in [("100,5-20", 80.5), ("100-0,5", 99.5), ("10,5*2", 21.0), ("100.5 mm-0,5", 100.0), ("0,5+100.25", 100.75)] { + let got = mm(text).unwrap_or(f64::NAN); + assert!((got - want).abs() < 1e-9, "{text}: {got}"); + } + for both in ["1.234,5", "1,234.5", "1.5,5-2"] { + assert_eq!(mm(both), None, "{both}: a point and a comma in one number"); + } assert_eq!(share_of("12,5%", 200.0), Some(25.0)); assert_eq!(share_of("1,000%", 200.0), None, "1,000% reads as thousands: refused, not 1%"); } diff --git a/crates/ui-egui/src/widgets/numeric.rs b/crates/ui-egui/src/widgets/numeric.rs index dfa68ac12f..ed1f257eeb 100644 --- a/crates/ui-egui/src/widgets/numeric.rs +++ b/crates/ui-egui/src/widgets/numeric.rs @@ -20,10 +20,12 @@ pub(crate) fn typed_unit(ctx: &egui::Context, unit: Unit) -> Unit { } /// `text` typed in a numeric field, with a decimal comma read as a point: `0,1 mm` is `0.1 mm` -/// (#3837). Text with a point keeps its commas, so `1,000.5` is still refused rather than read -/// with two decimal separators, and so does a number that reads as thousands ([`thousands`]). +/// (#3837), and each number of a sum reads its own separator, so `100.5 mm-0,5` (a comma typed +/// after the value the field shows) is 100 mm (#5684). A number written with both separators has +/// two points once read, so `1,000.5` and `1.234,5` are refused rather than guessed at; so is a +/// number that reads as thousands ([`thousands`]). pub(super) fn decimal_point(text: &str) -> std::borrow::Cow<'_, str> { - if text.contains(',') && !text.contains('.') && !thousands(text) { text.replace(',', ".").into() } else { text.into() } + if text.contains(',') && !thousands(text) { text.replace(',', ".").into() } else { text.into() } } /// Is `text` a number written with a thousands comma, as `1,000` or `12,500 mm`: one to three From 231e43a4901b53cb1e326878369b4ebe85e0f2ef Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Wed, 4 Nov 2026 21:45:06 -0500 Subject: [PATCH 008/196] Effects: Expand Appearance makes each copy of a path's Transform effect an object of its own (#5612) A path or compound path whose Transform effect made copies expanded to one compound path of every copy. It now expands to a group of one object per copy, each painted as the path, as gradient copies already did; a second Transform effect's copies nest in a group per copy of the first. Drawing is unchanged. # Conflicts: # docs/effects-parity.md --- crates/effects/src/lib.rs | 4 +- crates/effects/src/reshape.rs | 75 +++++++++++++++++++----- crates/engine/src/cmd/effectcmd.rs | 8 ++- crates/engine/src/cmd/effectcmd/tests.rs | 47 +++++++++++++++ docs/effects-parity.md | 5 +- 5 files changed, 119 insertions(+), 20 deletions(-) diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 313476c01a..8835d769f7 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -79,8 +79,8 @@ pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks}; pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace}; pub use raster::{RASTERIZE, RasterFx, Rasterize, color_param, outset, raster_effects}; pub use reshape::{ - SYMBOL_ART_MAX_NODES, expand_outlined, has_gradient_copies, has_item_geometry, has_transform_art, has_transform_options, image_paint, - needs_outline, outline_art, outline_text, reshape, + SYMBOL_ART_MAX_NODES, expand_outlined, has_gradient_copies, has_item_geometry, has_transform_art, has_transform_copies, has_transform_options, + image_paint, needs_outline, outline_art, outline_text, reshape, }; pub use revolve::{REVOLVE, has_revolve, revolve_art, revolve_options, validate_revolve}; pub use solids::{ diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index fa77c5702e..38d79c125e 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -39,8 +39,13 @@ pub fn needs_outline(n: &Node) -> bool { /// in a fill or stroke? Such an object is drawn through its art ([`outline_art`]) so that each copy /// paints its gradient by itself ([`copy_leaf`]), as a group's copies do. pub fn has_gradient_copies(n: &Node) -> bool { + (n.appearance.has_unplaced_gradient() || n.appearance.has_placed_gradient()) && has_transform_copies(n) +} + +/// Is `n` a path or compound path with a visible Transform effect that makes copies? Expand +/// Appearance makes each copy an object of its own ([`expand_outlined`]). +pub fn has_transform_copies(n: &Node) -> bool { matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. }) - && (n.appearance.has_unplaced_gradient() || n.appearance.has_placed_gradient()) && geometry_effects(n) .iter() .any(|e| e.id == "distort.transform" && crate::distort::transform_map(Rect::ZERO, &merged_params(&e.id, &e.params), 0).1 > 0) @@ -249,11 +254,20 @@ fn with_id(art: &Node, id: NodeId) -> Node { /// through the guides could hold more than [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects. A Repeat counts the Repeats in the art of /// `doc`'s symbols that its instances show toward its instance budget. pub fn outline_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option { - outline_art_with(doc, n, symbol_art, &outline_text, &SymbolNodes::default()) + outline_art_with(doc, n, symbol_art, &outline_text, &SymbolNodes::default(), false) } -/// [`outline_art`] with live objects evaluated through `outline` ([`evaluated_with`]). -fn outline_art_with(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>, outline: OutlineHook, nodes: &SymbolNodes) -> Option { +/// [`outline_art`] with live objects evaluated through `outline` ([`evaluated_with`]); with +/// `apart`, also a path or compound path whose Transform effect makes copies +/// ([`has_transform_copies`]), as the one piece the copies are made from. +fn outline_art_with( + doc: Option<&Document>, + n: &Node, + symbol_art: Option<&Node>, + outline: OutlineHook, + nodes: &SymbolNodes, + apart: bool, +) -> Option { let mut art = match &n.kind { NodeKind::Text(_) => outline_text(n)?, NodeKind::SymbolInstance { symbol, xf } => { @@ -268,7 +282,7 @@ fn outline_art_with(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>, Node::group(n.id, vec![Arc::new(a)]) } // The object as the one piece the copies of its Transform effect are made from. - _ if has_transform_art(n) => { + _ if has_transform_art(n) || (apart && has_transform_copies(n)) => { let mut one = n.clone(); one.opacity = 1.0; one.blend = Default::default(); @@ -429,10 +443,12 @@ pub fn reshape(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> O /// geometry effects, else type with fills or strokes of its own outlined, or an image with fills /// or strokes of its own that paint a shape, in the same form. `None` when it has none of these. pub fn expand_outlined(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option { - // A path whose Transform effect copies it with a gradient, or scales its strokes or moves its - // patterns: each copy an object of its own. - if has_transform_art(n) { - return as_art(doc, n, symbol_art); + // A path whose Transform effect copies it, or scales its strokes or moves its patterns: each + // copy an object of its own with the path's fills and strokes, the copies of each Transform + // effect in a group of their own (copies of copies nest), as the reference app expands them + // (#5612). + if has_transform_art(n) || has_transform_copies(n) { + return as_art_opts(doc, n, symbol_art, &outline_text, &SymbolNodes::default(), true); } let own_paint = match n.kind { NodeKind::Text(_) => !n.appearance.items.is_empty(), @@ -451,6 +467,12 @@ pub(crate) fn as_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node> /// [`as_art`] with live objects evaluated through `outline` ([`evaluated_with`]). pub(crate) fn as_art_with(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>, outline: OutlineHook, nodes: &SymbolNodes) -> Option { + as_art_opts(doc, n, symbol_art, outline, nodes, false) +} + +/// [`as_art_with`]; with `apart`, a path's or compound path's Transform effects make each copy an +/// object of its own ([`copy_leaf`]) rather than one path of every copy. +fn as_art_opts(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>, outline: OutlineHook, nodes: &SymbolNodes, apart: bool) -> Option { let fx = geometry_effects(n); let mut art = match &n.kind { NodeKind::Image(im) => { @@ -478,9 +500,12 @@ pub(crate) fn as_art_with(doc: Option<&Document>, n: &Node, symbol_art: Option<& Node::group(n.id, rows(below).into_iter().chain([Arc::new(image)]).chain(rows(above)).collect()) } } - _ => outline_art_with(doc, n, symbol_art, outline, nodes)?, + _ => outline_art_with(doc, n, symbol_art, outline, nodes, apart)?, }; - reshape_leaves(&mut art, &fx); + reshape_leaves_apart(&mut art, &fx, Budget::EFFECTS, apart); + if apart { + hoist_copies(&mut art); + } transform_items(&mut art); // Type and symbols in perspective: the art projected onto their plane. if let Some(h) = n.projection() { @@ -546,6 +571,28 @@ pub(crate) fn reshape_leaves(art: &mut Node, fx: &[&Effect]) { /// [`reshape_leaves`] whose paths keep to `budget` together, or to what they cost. pub(crate) fn reshape_leaves_within(art: &mut Node, fx: &[&Effect], budget: Budget) { + reshape_leaves_apart(art, fx, budget, false); +} + +/// `art`, the group of the one piece a path's copies are made from ([`outline_art_with`]), holding +/// the group of its copies ([`copy_leaf`]) as its only member: the copies become its members, so +/// the expanded path is one group of its copies rather than a group in a group. +fn hoist_copies(art: &mut Node) { + let id = art.id; + let Some(children) = art.children_mut() else { return }; + let [only] = children.as_slice() else { return }; + if only.id != id || !matches!(only.kind, NodeKind::Group { clip: false, .. }) { + return; + } + let copies = only.children().cloned().unwrap_or_default(); + if !copies.is_empty() { + *children = copies; + } +} + +/// [`reshape_leaves_within`]; with `apart`, a Transform effect's copies of each path are objects +/// of their own ([`copy_leaf`]) whatever paints them, as Expand Appearance makes them. +fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: bool) { if fx.is_empty() { return; } @@ -588,14 +635,14 @@ pub(crate) fn reshape_leaves_within(art: &mut Node, fx: &[&Effect], budget: Budg if let Some((m, copies, options, map)) = transform { // Transform Patterns and Scale Strokes & Effects change each copy's fills and // strokes; a gradient paints each copy by itself, not the one piece the copies - // make together. - let gradient = copies > 0 && (leaf.appearance.has_unplaced_gradient() || leaf.appearance.has_placed_gradient()); + // make together; and Expand Appearance (`apart`) makes each copy an object. + let separate = copies > 0 && (apart || leaf.appearance.has_unplaced_gradient() || leaf.appearance.has_placed_gradient()); if options.reach_appearance() { let made = transform_leaf(leaf, &path, map, copies, options, room); used = used.minus(before).plus(made); return; } - if gradient { + if separate { let made = copy_leaf(leaf, &path, m, copies, vectorcraft_doc::Scaling::default(), room); used = used.minus(before).plus(made); return; diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 8718e725fc..1fcd4602ed 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -758,11 +758,15 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br members = expand_pieces(d, &mut m, false, brushes, &mut stroke_art); m }) - } else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && !effects::has_transform_art(&v) { + } else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) + && !effects::has_transform_art(&v) + && !effects::has_transform_copies(&v) + { effects::expand_leaf(d, &v, &mut stroke_art) } else { // Type, images, symbol instances, live objects (and paths whose Transform effect copies - // them with a gradient or changes their fills and strokes): through their outlines. + // them, each copy an object of its own, or changes their fills and strokes): through + // their outlines. let symbol = match &n.kind { NodeKind::SymbolInstance { symbol, .. } => { d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_render::instance_art(&s.art, &n)) diff --git a/crates/engine/src/cmd/effectcmd/tests.rs b/crates/engine/src/cmd/effectcmd/tests.rs index 7e44e07726..639fe44edc 100644 --- a/crates/engine/src/cmd/effectcmd/tests.rs +++ b/crates/engine/src/cmd/effectcmd/tests.rs @@ -474,6 +474,53 @@ fn expand_appearance_gives_each_copy_of_a_transform_its_own_gradient() { assert_eq!(boxes, vec![100.0; 3], "three squares, each with its own gradient"); } +/// Expand Appearance on a solid-filled path whose Transform effect makes copies gives a group of +/// one path per copy, each with the path's fill, not one compound path (#5612); a second Transform +/// effect's copies of those copies nest, a group per copy of the first. +#[test] +fn expand_appearance_makes_each_copy_of_a_transform_an_object() { + use vectorcraft_color::{Color, Paint}; + let fill = |n: &vectorcraft_doc::Node| n.appearance.fill_paint().color(); + let (mut s, id) = session_with_rect(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("effect.apply", &json!({"effect":"distort.transform","ids":[id.0],"item":null})).unwrap(); + s.execute("effect.setParams", &json!({"index":0,"params":{"moveH":150,"copies":2},"ids":[id.0],"item":null})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap(); + let n = node(&s, id); + assert!(matches!(n.kind, NodeKind::Group { clip: false, .. }), "{}", n.kind_label()); + assert!(n.appearance.effects.is_empty()); + let copies = n.children().unwrap(); + assert_eq!(copies.len(), 3, "the path and its two copies"); + let xs: Vec = copies.iter().map(|c| c.geometric_bounds().unwrap().x0).collect(); + assert_eq!(xs, vec![100.0, 250.0, 400.0]); + for c in copies { + assert!(matches!(c.kind, NodeKind::Path { .. }), "{}", c.kind_label()); + assert_eq!(fill(c), Some(Color::rgb(1.0, 0.0, 0.0))); + assert!((c.geometric_bounds().unwrap().width() - 100.0).abs() < 1e-9); + } + let mut ids: Vec = vec![]; + n.walk(&mut |c| ids.push(c.id)); + ids.sort(); + ids.dedup(); + assert_eq!(ids.len(), 4, "the group and each copy have ids of their own"); + // Two Transform effects: three columns, each a group of the column's two copies. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(*s.doc().unwrap().doc, *before); + s.execute("effect.apply", &json!({"effect":"distort.transform","ids":[id.0],"item":null})).unwrap(); + s.execute("effect.setParams", &json!({"index":1,"params":{"moveV":150,"copies":1},"ids":[id.0],"item":null})).unwrap(); + s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap(); + let columns = node(&s, id).children().unwrap().to_vec(); + assert_eq!(columns.len(), 3); + for (col, x) in columns.iter().zip([100.0, 250.0, 400.0]) { + let cells = col.children().unwrap_or_else(|| panic!("a column is a group: {}", col.kind_label())); + let ys: Vec<(f64, f64)> = cells.iter().map(|c| (c.geometric_bounds().unwrap().x0, c.geometric_bounds().unwrap().y0)).collect(); + assert_eq!(ys, vec![(x, 100.0), (x, 250.0)]); + assert!(cells.iter().all(|c| matches!(c.appearance.fill_paint(), Paint::Solid { .. }))); + } +} + /// The object's own effect ids, in order. fn object_effects(s: &Session, id: NodeId) -> Vec { node(s, id).appearance.effects.iter().map(|e| e.id.clone()).collect() diff --git a/docs/effects-parity.md b/docs/effects-parity.md index 17b70253c8..2878c56825 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-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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Expand Appearance makes each copy of a path's Transform effect an object of its own (#5612); previously: Pixelate › Color Halftone: Max Radius in pixels of the Document Raster Effects resolution, 4–127 px, with older documents converted on opening and radii written back in points for older app versions (#3260); Effect dialogs clamp bounded length inputs immediately on commit and flash rejection on invalid input (#4638); previously: Drop Shadow Darkness uses fixed RGB subtraction and CMYK black addition; scores unchanged; Pathfinder › Trap: the Pathfinder panel's Trap… and Effect › Pathfinder › Trap… add an overprinting strip of the lighter colour where two solid colours meet; recounted with Hard Mix (#3061) and Soft Mix already in the catalogue: Pathfinder 13/13, Illustrator effects 49/50) · **Target:** Adobe Illustrator 2026 (30.x) Every entry of Illustrator's Effect menu, by its public feature name, against VectorCraft's effects catalogue (`effect_catalog()` in `crates/effects/src/lib.rs`) and the Effect menu built from it @@ -22,7 +22,7 @@ Part of [target-app-parity.md](target-app-parity.md); open work is in [gaps.md]( |---|---|---:|---| | Convert to Shape | Rectangle, Rounded Rectangle, Ellipse | 3/3 | — | | Crop Marks | Crop Marks | 1/1 | — | -| Distort & Transform | Free Distort, Pucker & Bloat, Roughen, Transform, Tweak, Twist, Zig Zag | 7/7 | Free Distort's dialog has a handle on each corner of the object's bounds, moved by dragging or with the arrow keys; Zig Zag's ridges are evenly spaced along each segment (#1558), and Smooth points make a continuous wave whose peaks and valleys have handles along the path (#2343); Roughen with Smooth keeps turn-backs smooth instead of cusps that draw as spikes (#1646) | +| Distort & Transform | Free Distort, Pucker & Bloat, Roughen, Transform, Tweak, Twist, Zig Zag | 7/7 | Free Distort's dialog has a handle on each corner of the object's bounds, moved by dragging or with the arrow keys; Zig Zag's ridges are evenly spaced along each segment (#1558), and Smooth points make a continuous wave whose peaks and valleys have handles along the path (#2343); Roughen with Smooth keeps turn-backs smooth instead of cusps that draw as spikes (#1646); Expand Appearance of a path whose Transform effect makes copies gives a group of one object per copy, each painted as the path, and a second Transform effect's copies nest in a group per copy of the first (#5612) | | Path | Offset Path, Outline Object, Outline Stroke | 3/3 | With Use Preview Bounds on, Align, Distribute and the Transform panel still measure type that carries Outline Object by its layout box (preview bounds leave out effects) | | Pathfinder | Add, Intersect, Exclude, Subtract, Minus Back, Divide, Trim, Merge, Crop, Outline, Hard Mix, Soft Mix, Trap | 13/13 | Trap traps only solid fills (gradients and patterns hide what is below them but don't trap) and spreads each colour's visible area as a whole; the public page gives no default values, so Trap's 0.25 pt, 100% and 40% are VectorCraft's own | | Rasterize | Rasterize… (as a live effect) | 1/1 | — | @@ -193,6 +193,7 @@ angular cut caps, exact visibility, 3D Classic, Turntable, 3D export) is 25–45 | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | Expand Appearance of a path or compound path whose Transform effect makes copies gives a group of one object per copy, each with the path's fills and strokes, instead of one compound path of every copy; copies of copies nest (#5612). Counts unchanged. | | 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 versions 1 and 2) 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`. | From d62c90f41ee1b22e232ec54a96bebec5b08e80be Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 5 Nov 2026 10:01:10 +0700 Subject: [PATCH 009/196] Tests: Expand Appearance of a Transform's copies makes a group of them --- crates/engine/src/cmd/effectcmd/tests.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/effectcmd/tests.rs b/crates/engine/src/cmd/effectcmd/tests.rs index 639fe44edc..ce8f511834 100644 --- a/crates/engine/src/cmd/effectcmd/tests.rs +++ b/crates/engine/src/cmd/effectcmd/tests.rs @@ -366,14 +366,16 @@ fn expand_appearance_bakes_geometry() { assert!(s.execute("effect.expandAppearance", &json!({})).is_err()); } +/// Each copy is an object of its own (#5612). #[test] -fn expand_transform_copies_makes_compound() { +fn expand_transform_copies_makes_a_group_of_the_copies() { let (mut s, id) = session_with_rect(); s.execute("paint.setStroke", &json!({"none": true})).unwrap(); s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"moveH": 120, "copies": 1}})).unwrap(); s.execute("effect.expandAppearance", &json!({})).unwrap(); let n = node(&s, id); - assert!(matches!(n.kind, NodeKind::Compound { .. })); + assert!(matches!(n.kind, NodeKind::Group { .. }), "{}", n.kind_label()); + assert_eq!(n.children().map(|c| c.len()), Some(2)); let b = n.geometric_bounds().unwrap(); assert!((b.x1 - 320.0).abs() < 1e-6, "{b:?}"); } From 0f9839f7f60b1914b18348cf477c026d4d6fb99e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 18:20:25 -0800 Subject: [PATCH 010/196] Layers: heavy type, symbols, meshes and images get their first thumbnail off the UI thread The Layers panel decided whether to make a row's first thumbnail on the UI thread by counting path anchors and type frames only, so point type, symbol instances, gradient meshes, images and placed documents counted as one object with no anchors, and a heavy one was rendered on the UI thread. - small_node takes the row's document. Each glyph of type counts as 4 anchors, each mesh point as 1 and every 100 image pixels as 1, against the same 2,000-anchor limit; glyphs are counted only up to the limit. - A symbol instance and an inline graphic count their symbol's art, and a placed document counts its file's art once the file has been read; one not read yet goes to the thumbnail thread. - Symbols and placed documents nested more than 8 deep go to the thumbnail thread, so a symbol holding an instance of itself is counted to an end. - The painted fallback thumbnail counts as before. --- crates/ui-egui/src/panels/layers/thumbs.rs | 262 +++++++++++++++++++-- docs/target-app-parity.md | 1 + 2 files changed, 238 insertions(+), 25 deletions(-) diff --git a/crates/ui-egui/src/panels/layers/thumbs.rs b/crates/ui-egui/src/panels/layers/thumbs.rs index dea908ea07..f86efc034c 100644 --- a/crates/ui-egui/src/panels/layers/thumbs.rs +++ b/crates/ui-egui/src/panels/layers/thumbs.rs @@ -76,9 +76,25 @@ const LIGHT_THUMB_MS: f64 = 4.0; const LIGHT_THUMB_NODES: usize = 200; /// A node whose paths have more anchors than this in all has its first thumbnail made on the -/// worker. +/// worker. Type's glyphs, mesh points and image pixels count against it too, each as the anchors +/// that take about as long to render: [`GLYPH_ANCHORS`], [`MESH_POINT_ANCHORS`] and +/// [`IMAGE_PIXELS_PER_ANCHOR`]. const LIGHT_THUMB_ANCHORS: usize = 2_000; +/// Anchors one glyph of type counts as. +const GLYPH_ANCHORS: usize = 4; + +/// Anchors one point of a gradient mesh counts as. +const MESH_POINT_ANCHORS: usize = 1; + +/// Pixels of an image that count as one anchor. +const IMAGE_PIXELS_PER_ANCHOR: usize = 100; + +/// The most symbols and placed documents counted inside one another: a node holding them deeper +/// (a symbol whose art holds an instance of itself, for one) has its first thumbnail made on the +/// worker. +const MAX_THUMB_NESTING: usize = 8; + /// At most this long (ms) and this many thumbnails are rendered on the UI thread in a pass; the /// rest go to the worker, or wait for the next pass where there is none. const THUMB_BUDGET_MS: f64 = 8.0; @@ -93,8 +109,40 @@ pub(crate) fn thumb_options() -> vectorcraft_render::RenderOptions { /// Has `n` at most `nodes` objects inside it, and at most `anchors` anchors in its paths and the /// paths inside it, the frames of area type and the paths of type on a path included (counting /// stops at either limit)? With `masks`, the art of the opacity masks that are not disabled, and -/// the objects and anchors inside it, count as well. -fn small_node(n: &Node, nodes: usize, anchors: usize, masks: bool) -> bool { +/// the objects and anchors inside it, count as well. With `doc` (the document `n` is in), type's +/// glyphs, mesh points and image pixels count as anchors too ([`LIGHT_THUMB_ANCHORS`]), and a +/// symbol instance and a placed document count the objects and anchors of the art they show: the +/// symbol's art in `doc`, and the placed file's art when it has been read (a placed document whose +/// file has not been read, or art nested deeper than [`MAX_THUMB_NESTING`], is not small). +fn small_node(n: &Node, nodes: usize, anchors: usize, masks: bool, doc: Option<&Document>) -> bool { + /// What may still be counted. + struct Left { + nodes: usize, + anchors: usize, + masks: bool, + } + impl Left { + /// Count `anchors` more: false past the limit. + fn take(&mut self, anchors: usize) -> bool { + match self.anchors.checked_sub(anchors) { + Some(left) => { + self.anchors = left; + true + } + None => false, + } + } + /// Count one more object: false past the limit. + fn object(&mut self) -> bool { + match self.nodes.checked_sub(1) { + Some(left) => { + self.nodes = left; + true + } + None => false, + } + } + } fn own_anchors(n: &Node) -> usize { match &n.kind { NodeKind::Text(t) => match &t.kind { @@ -104,23 +152,41 @@ fn small_node(n: &Node, nodes: usize, anchors: usize, masks: bool) -> bool { _ => n.path_data().map_or(0, PathData::anchor_count), } } - fn count(n: &Node, nodes: &mut usize, anchors: &mut usize, masks: bool) -> bool { - let Some(left) = anchors.checked_sub(own_anchors(n)) else { return false }; - *anchors = left; - let mask = n.extras().mask.as_deref().filter(|m| masks && !m.disabled).map(|m| &m.art); - for c in n.children().into_iter().flatten().chain(mask) { - if *nodes == 0 { - return false; - } - *nodes -= 1; - if !count(c, nodes, anchors, masks) { - return false; - } - } - true + /// Count `art`, drawn in place of an object (`doc` its document), one level deeper. + fn inside(art: &Node, doc: &Document, left: &mut Left, depth: usize) -> bool { + depth < MAX_THUMB_NESTING && left.object() && count(art, Some(doc), left, depth + 1) } - let (mut nodes, mut anchors) = (nodes, anchors); - count(n, &mut nodes, &mut anchors, masks) + /// Count symbol `name` of `doc` (one that doesn't exist draws nothing). + fn symbol(name: &str, doc: &Document, left: &mut Left, depth: usize) -> bool { + doc.symbols.iter().find(|s| s.name == name).is_none_or(|s| inside(&s.art, doc, left, depth)) + } + /// Count what `n` draws besides its children. + fn own(n: &Node, doc: Option<&Document>, left: &mut Left, depth: usize) -> bool { + if !left.take(own_anchors(n)) { + return false; + } + let Some(doc) = doc else { return true }; + match &n.kind { + // Glyphs are counted only up to one past what the anchors left allow. + NodeKind::Text(t) => t.runs.iter().all(|r| { + let glyphs = r.text.chars().take(left.anchors / GLYPH_ANCHORS + 1).count(); + left.take(glyphs.saturating_mul(GLYPH_ANCHORS)) && r.inline.as_ref().is_none_or(|a| symbol(&a.symbol, doc, left, depth)) + }), + NodeKind::SymbolInstance { symbol: name, .. } => symbol(name, doc, left, depth), + NodeKind::Mesh(m) => left.take(m.points.len().saturating_mul(MESH_POINT_ANCHORS)), + NodeKind::Image(im) => left.take((im.width as usize).saturating_mul(im.height as usize) / IMAGE_PIXELS_PER_ANCHOR), + NodeKind::PlacedDocument(p) => vectorcraft_doc::placed_document::read_cached(p).is_some_and(|e| inside(&e.art, &e.doc, left, depth)), + _ => true, + } + } + fn count(n: &Node, doc: Option<&Document>, left: &mut Left, depth: usize) -> bool { + if !own(n, doc, left, depth) { + return false; + } + let mask = n.extras().mask.as_deref().filter(|m| left.masks && !m.disabled).map(|m| &m.art); + n.children().into_iter().flatten().chain(mask).all(|c| left.object() && count(c, doc, left, depth)) + } + count(n, doc, &mut Left { nodes, anchors, masks }, 0) } /// The thumbnail of `n` (`px` pixels square) as `r` renders it, on the UI thread or the worker. @@ -209,9 +275,10 @@ impl Thumbs { let in_budget = self.spent.1 < THUMB_BUDGET_MS && self.spent.2 < THUMB_BUDGET_COUNT; // A row drawn before is light when its last thumbnail was quick to render, unless its // object now has more anchors than the limit. + let doc = Some(src.doc.as_ref()); let light = match light { - Some(quick) => quick && small_node(n, usize::MAX, LIGHT_THUMB_ANCHORS, true), - None => small_node(n, LIGHT_THUMB_NODES, LIGHT_THUMB_ANCHORS, true), + Some(quick) => quick && small_node(n, usize::MAX, LIGHT_THUMB_ANCHORS, true, doc), + None => small_node(n, LIGHT_THUMB_NODES, LIGHT_THUMB_ANCHORS, true, doc), } && in_budget; if !light && let Some(w) = &self.worker { let (doc, node) = (src.doc.clone(), n.clone()); @@ -263,7 +330,7 @@ pub(crate) fn real_thumb(ui: &Ui, src: &ThumbSource, n: &Arc, r: egui::Rec /// more than [`LIGHT_THUMB_ANCHORS`] anchors paints nothing, since this runs on every frame and /// measuring its bounds takes time in proportion to its anchor count. pub(super) fn thumb(ui: &Ui, n: &Node, r: egui::Rect) { - if !small_node(n, usize::MAX, LIGHT_THUMB_ANCHORS, false) { + if !small_node(n, usize::MAX, LIGHT_THUMB_ANCHORS, false, None) { return; } let Some(b) = n.visual_bounds() else { return }; @@ -293,7 +360,7 @@ pub(super) fn thumb(ui: &Ui, n: &Node, r: egui::Rect) { mod tests { use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, CharStyle, LayerColor, NodeKind, OpacityMask, TextKind, TextObject}; - use vectorcraft_geom::{Point, SubPath}; + use vectorcraft_geom::{Affine, Point, SubPath}; use super::*; @@ -330,7 +397,12 @@ mod tests { } fn small(n: &Node) -> bool { - small_node(n, LIGHT_THUMB_NODES, LIGHT_THUMB_ANCHORS, true) + small_node(n, LIGHT_THUMB_NODES, LIGHT_THUMB_ANCHORS, true, None) + } + + /// Is `n`, an object of `doc`, small? + fn small_in(doc: &Document, n: &Node) -> bool { + small_node(n, LIGHT_THUMB_NODES, LIGHT_THUMB_ANCHORS, true, Some(doc)) } /// `n` with an opacity mask of `art`, disabled or not. @@ -350,7 +422,7 @@ mod tests { assert!(!small(&masked(rect(1), inner, false)), "a mask holding a long path"); let child = Node::group(NodeId(1), vec![Arc::new(masked(rect(4), long(), false))]); assert!(!small(&child), "a group holding an object with a long mask"); - assert!(small_node(&masked(rect(1), long(), false), usize::MAX, LIGHT_THUMB_ANCHORS, false), "masks left out"); + assert!(small_node(&masked(rect(1), long(), false), usize::MAX, LIGHT_THUMB_ANCHORS, false, None), "masks left out"); } #[test] @@ -373,6 +445,124 @@ mod tests { assert!(!small(&both), "a path and an area frame whose anchors together pass the limit"); } + /// Point type `id` of `glyphs` glyphs. + fn glyphs(id: u64, glyphs: usize) -> Node { + let t = TextObject::point(Point::ZERO, &"a".repeat(glyphs), CharStyle::default()); + Node::new(NodeId(id), NodeKind::Text(Box::new(t))) + } + + /// A gradient mesh `id` of `rows` x `rows` patches. + fn mesh(id: u64, rows: u32) -> Node { + let m = vectorcraft_doc::GradientMesh::from_surface(rows, rows, &|u, v| Point::new(u * 100.0, v * 100.0), &|_, _| Color::BLACK); + Node::new(NodeId(id), NodeKind::Mesh(m)) + } + + /// An image `id` of `w` x `h` pixels. + fn image(id: u64, w: u32, h: u32) -> Node { + let im = vectorcraft_doc::ImageObject { + key: "im".into(), + width: w, + height: h, + xf: Affine::IDENTITY, + link: None, + placement: Default::default(), + pixels: None, + }; + Node::new(NodeId(id), NodeKind::Image(Box::new(im))) + } + + /// An instance `id` of symbol `name`. + fn instance(id: u64, name: &str) -> Node { + Node::new(NodeId(id), NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY }) + } + + /// A document whose symbol `name` is `art`. + fn with_symbol(name: &str, art: Node) -> Document { + let mut doc = Document::new(200.0, 200.0); + doc.symbols.push(vectorcraft_doc::Symbol { name: name.into(), art: Arc::new(art), dynamic: false }); + doc + } + + /// A placed document `id` showing file `key`, read already when `art` is given. + fn placed(id: u64, key: &str, art: Option) -> Node { + let p = vectorcraft_doc::PlacedDocument { + link: vectorcraft_doc::LinkInfo::new("/art/placed.vectorcraft"), + key: key.into(), + bounding: false, + page_box: Default::default(), + width: 100.0, + height: 100.0, + xf: Affine::IDENTITY, + placement: Default::default(), + }; + if let Some(art) = art { + let frame = vectorcraft_geom::Rect::new(0.0, 0.0, 100.0, 100.0); + vectorcraft_doc::placed_document::prime(&p, Arc::new(key.as_bytes().to_vec()), (Document::new(100.0, 100.0), art, frame)); + } + Node::new(NodeId(id), NodeKind::PlacedDocument(Box::new(p))) + } + + #[test] + fn type_meshes_and_images_count_their_work_as_anchors() { + let doc = Document::new(200.0, 200.0); + let limit = LIGHT_THUMB_ANCHORS / GLYPH_ANCHORS; + assert!(small_in(&doc, &glyphs(1, limit)), "type of as many glyphs as the limit"); + assert!(!small_in(&doc, &glyphs(1, limit + 1)), "type of more glyphs"); + assert!(!small_in(&doc, &glyphs(1, 5_000)), "long type"); + let beside = Node::group(NodeId(1), vec![Arc::new(glyphs(2, limit / 2)), Arc::new(path(3, LIGHT_THUMB_ANCHORS / 2 + 1))]); + assert!(!small_in(&doc, &beside), "type and a path that together pass the limit"); + // (rows + 1)² points: 1,936 and 2,025. + assert!(small_in(&doc, &mesh(1, 43)), "a small mesh"); + assert!(!small_in(&doc, &mesh(1, 44)), "a mesh of more points"); + let px = (LIGHT_THUMB_ANCHORS * IMAGE_PIXELS_PER_ANCHOR) as u32; + assert!(small_in(&doc, &image(1, px / 100, 100)), "an image of as many pixels as the limit"); + assert!(!small_in(&doc, &image(1, px / 100, 101)), "a larger image"); + assert!(!small_in(&doc, &image(1, 4_000, 3_000)), "a photo"); + // Without the document only paths and frames count, as the painted thumbnail needs. + assert!(small(&glyphs(1, 5_000)) && small(&mesh(1, 100)) && small(&image(1, 4_000, 3_000))); + } + + #[test] + fn a_symbol_instance_and_a_placed_document_count_the_art_they_show() { + let doc = with_symbol("Long", path(10, LIGHT_THUMB_ANCHORS + 1)); + assert!(!small_in(&doc, &instance(1, "Long")), "an instance of a symbol of a long path"); + assert!(small(&instance(1, "Long")), "without the document"); + assert!(small_in(&doc, &instance(1, "Missing")), "an instance of a symbol that doesn't exist"); + let doc = with_symbol("Short", path(10, LIGHT_THUMB_ANCHORS)); + assert!(small_in(&doc, &instance(1, "Short")), "an instance of a symbol of a path at the limit"); + let two = Node::group(NodeId(1), vec![Arc::new(instance(2, "Short")), Arc::new(instance(3, "Short"))]); + assert!(!small_in(&doc, &two), "two instances whose art together passes the limit"); + let many = with_symbol("Group", Node::group(NodeId(10), (0..LIGHT_THUMB_NODES).map(|i| Arc::new(rect(i as u64 + 11))).collect())); + assert!(!small_in(&many, &instance(1, "Group")), "a symbol of more objects than the limit"); + // Inline graphics in type draw their symbol too. + let mut t = TextObject::point(Point::ZERO, "a", CharStyle::default()); + t.runs[0].inline = Some(vectorcraft_doc::InlineArt { symbol: "Long".into(), scale: 1.0, baseline_shift: 0.0, bounds: None }); + let long = with_symbol("Long", path(10, LIGHT_THUMB_ANCHORS + 1)); + assert!(!small_in(&long, &Node::new(NodeId(1), NodeKind::Text(Box::new(t)))), "type showing a long symbol inline"); + + let doc = Document::new(200.0, 200.0); + assert!(small_in(&doc, &placed(1, "thumbs-small-placed", Some(path(10, LIGHT_THUMB_ANCHORS)))), "a placed file of a short path"); + assert!(!small_in(&doc, &placed(1, "thumbs-long-placed", Some(path(10, LIGHT_THUMB_ANCHORS + 1)))), "a placed file of a long path"); + assert!(!small_in(&doc, &placed(1, "thumbs-unread-placed", None)), "a placed file not read yet"); + } + + #[test] + fn a_symbol_that_holds_itself_is_not_small_and_is_counted_to_an_end() { + let doc = with_symbol("Loop", Node::group(NodeId(10), vec![Arc::new(rect(11)), Arc::new(instance(12, "Loop"))])); + assert!(!small_in(&doc, &instance(1, "Loop"))); + assert!(!small_node(&instance(1, "Loop"), usize::MAX, usize::MAX, true, Some(&doc)), "without limits on objects and anchors"); + // Nested as deep as counted, the art is small. + let mut doc = with_symbol("S0", rect(10)); + for i in 1..MAX_THUMB_NESTING { + let art = Node::group(NodeId(10 + i as u64), vec![Arc::new(instance(100 + i as u64, &format!("S{}", i - 1)))]); + doc.symbols.push(vectorcraft_doc::Symbol { name: format!("S{i}"), art: Arc::new(art), dynamic: false }); + } + assert!(small_in(&doc, &instance(1, &format!("S{}", MAX_THUMB_NESTING - 1))), "symbols as deep as counted"); + let art = Node::group(NodeId(9), vec![Arc::new(instance(99, &format!("S{}", MAX_THUMB_NESTING - 1)))]); + doc.symbols.push(vectorcraft_doc::Symbol { name: "Deeper".into(), art: Arc::new(art), dynamic: false }); + assert!(!small_in(&doc, &instance(1, "Deeper")), "one level deeper"); + } + #[test] fn the_painted_thumbnail_leaves_out_a_long_path() { let ctx = egui::Context::default(); @@ -435,6 +625,28 @@ mod tests { assert!(thumbs.pending.is_empty()); } + #[test] + fn an_instance_of_a_long_symbols_thumbnail_is_made_on_the_worker_and_matches_one_made_here() { + let ctx = egui::Context::default(); + let Some(worker) = ThumbWorker::start(&ctx, "test") else { return }; + let mut thumbs = Thumbs { worker: Some(worker), worker_started: true, ..Default::default() }; + let mut doc = with_symbol("Long", path(900, 50_000)); + let layer = doc.layers.first().map(|l| l.id); + let id = doc.alloc_id(); + doc.insert(layer, usize::MAX, instance(id.0, "Long")).unwrap(); + let doc = Arc::new(doc); + let n = node_arc(&doc, id).unwrap(); + let src = ThumbSource { uid: 1, revision: 1, doc: &doc, busy: false }; + assert!(thumbs.texture(&ctx, &src, &n, 24).is_none(), "nothing is shown until it is made"); + assert_eq!(thumbs.renders, 0, "not made on this thread"); + assert!(thumbs.pending.contains_key(&(1, n.id)), "sent to the worker"); + let done = thumbs.worker.as_ref().and_then(ThumbWorker::wait).expect("the worker finishes it"); + let there = done.img.as_ref().expect("the worker draws the symbol"); + let here = render_thumb(&mut vectorcraft_render::Renderer::new(), &doc, &n, 24).expect("this thread draws the symbol"); + assert!(here.pixels.chunks(4).any(|p| p[3] > 0), "the thumbnail shows the symbol's art"); + assert_eq!((there.width, there.height, &there.pixels), (here.width, here.height, &here.pixels), "the same pixels"); + } + #[test] fn a_row_whose_object_becomes_a_long_path_is_drawn_again_on_the_worker() { let ctx = egui::Context::default(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8194787833..12fc7894b3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1274,6 +1274,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Delete, Cut, Group, Ungroup, Make and Release Compound Path, Make Clipping Mask, Send to Current Layer, Duplicate, Copy in the Move, Rotate, Scale, Reflect and Shear dialogs, Transform Each with Copy and each move of an Alt-drag take time in proportion to the size of the document (#1429). In the web build the status bar's render and UI times are measured with the browser's `performance.now()`, and the Layers panel stops rendering row thumbnails in a frame once they have taken 8 ms. On the desktop, the Layers panel renders a row's thumbnail on its thumbnail thread when the row's paths, and the paths of its opacity masks that are not disabled, hold more than 2,000 anchors in all. It already did this for the first thumbnail of a row of more than 200 objects. Until its first thumbnail is ready, the row shows boxes at the bounds of up to 41 of its paths, each in its path's solid fill or stroke color or in gray, when its own paths, without its opacity masks, hold at most 2,000 anchors in all, and an empty white box otherwise. With one path of 200,000 anchors, the first frame after the panel opens takes 2.4 ms instead of 393 ms (release build, median of three runs). + The same 2,000-anchor limit counts each glyph of type as 4 anchors, each point of a gradient mesh as 1 and every 100 pixels of an image as 1, and a symbol instance or a placed document counts the objects and anchors of the art it shows. A placed document whose file has not been read yet, or a symbol nested more than 8 deep (one that holds an instance of itself, for example), gets its first thumbnail on the thumbnail thread. The first frame after the panel opens takes 2.5 ms instead of 23.4 ms with 5,000 glyphs of point type, 2.1 ms instead of 346 ms with one instance of a symbol of a 200,000-anchor path, 1.7 ms instead of 11.7 ms with a 100 × 100 mesh, and 2.3 ms instead of 273 ms with a placed document of a 200,000-anchor path (release build, median of three runs). In the web build, while a pan, zoom or rotation changes the view of a document whose last canvas render took more than 8 ms, the canvas draws the last frame moved with the view, and it renders the art again once the view has been still for 0.2 s. An Alt-drag with the Selection, Direct Selection, Group Selection, Rotate, Scale, Reflect or Shear tool copies the selection on its first move, and the moves after it transform those copies; the previews of the Move, Rotate, Scale, Reflect and Shear dialogs with Copy and Preview on copy the selection once in the same way (#1429). An Alt-drag of objects in perspective with the Perspective Selection tool, and an Alt-drag of a plane widget with that tool or the Perspective Grid tool, copy the objects on the first move, and the moves after it move those copies (#1429). From 5baf83f1dea316e37310ff835e4d08eb9dd93cc9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 18:44:39 -0800 Subject: [PATCH 011/196] Layers: counting a row's art for its first thumbnail stops after 20,000 steps A row drawn before was counted with no limit on its objects, so symbols that each hold many instances of the next made the count grow with the product of the instances, and the Layers panel could stall on such a file. - Counting stops after 20,000 steps: each object, subpath, text run and symbol looked at is one step, and every 64 bytes of a symbol or placed file name looked up is one more. A row that needs more gets its thumbnail on the thumbnail thread, and the painted thumbnail draws nothing for it. - A row drawn before counts at most 20,000 objects. --- crates/ui-egui/src/panels/layers/thumbs.rs | 146 ++++++++++++++++++--- docs/target-app-parity.md | 2 +- 2 files changed, 126 insertions(+), 22 deletions(-) diff --git a/crates/ui-egui/src/panels/layers/thumbs.rs b/crates/ui-egui/src/panels/layers/thumbs.rs index f86efc034c..db303a11c8 100644 --- a/crates/ui-egui/src/panels/layers/thumbs.rs +++ b/crates/ui-egui/src/panels/layers/thumbs.rs @@ -95,6 +95,12 @@ const IMAGE_PIXELS_PER_ANCHOR: usize = 100; /// worker. const MAX_THUMB_NESTING: usize = 8; +/// The most steps counting a node takes: each object, subpath, text run and symbol looked at is +/// one step, and so is every 64 bytes of a symbol or placed file name looked up. A node that +/// needs more has its thumbnail made on the worker, and the painted thumbnail draws nothing for +/// it. A row drawn before counts at most this many objects too. +const THUMB_COUNT_STEPS: usize = 20_000; + /// At most this long (ms) and this many thumbnails are rendered on the UI thread in a pass; the /// rest go to the worker, or wait for the next pass where there is none. const THUMB_BUDGET_MS: f64 = 8.0; @@ -113,12 +119,19 @@ pub(crate) fn thumb_options() -> vectorcraft_render::RenderOptions { /// glyphs, mesh points and image pixels count as anchors too ([`LIGHT_THUMB_ANCHORS`]), and a /// symbol instance and a placed document count the objects and anchors of the art they show: the /// symbol's art in `doc`, and the placed file's art when it has been read (a placed document whose -/// file has not been read, or art nested deeper than [`MAX_THUMB_NESTING`], is not small). +/// file has not been read, or art nested deeper than [`MAX_THUMB_NESTING`], is not small). A node +/// that takes more than [`THUMB_COUNT_STEPS`] steps to count is not small. fn small_node(n: &Node, nodes: usize, anchors: usize, masks: bool, doc: Option<&Document>) -> bool { + weigh(n, nodes, anchors, masks, doc).0 +} + +/// [`small_node`], and the steps counting took. +fn weigh(n: &Node, nodes: usize, anchors: usize, masks: bool, doc: Option<&Document>) -> (bool, usize) { /// What may still be counted. struct Left { nodes: usize, anchors: usize, + steps: usize, masks: bool, } impl Left { @@ -132,6 +145,20 @@ fn small_node(n: &Node, nodes: usize, anchors: usize, masks: bool, doc: Option<& None => false, } } + /// Take `steps` more: false past the limit. + fn step(&mut self, steps: usize) -> bool { + match self.steps.checked_sub(steps) { + Some(left) => { + self.steps = left; + true + } + None => false, + } + } + /// Look up `name`: false past the step limit. + fn look_up(&mut self, name: &str) -> bool { + self.step(1 + name.len() / 64) + } /// Count one more object: false past the limit. fn object(&mut self) -> bool { match self.nodes.checked_sub(1) { @@ -142,14 +169,9 @@ fn small_node(n: &Node, nodes: usize, anchors: usize, masks: bool, doc: Option<& None => false, } } - } - fn own_anchors(n: &Node) -> usize { - match &n.kind { - NodeKind::Text(t) => match &t.kind { - TextKind::Area { frame: p } | TextKind::OnPath { path: p, .. } => p.anchor_count(), - TextKind::Point => 0, - }, - _ => n.path_data().map_or(0, PathData::anchor_count), + /// Count the anchors of `p`, a step for each subpath. + fn path(&mut self, p: &PathData) -> bool { + p.subpaths.iter().all(|s| self.step(1) && self.take(s.anchors.len())) } } /// Count `art`, drawn in place of an object (`doc` its document), one level deeper. @@ -158,11 +180,26 @@ fn small_node(n: &Node, nodes: usize, anchors: usize, masks: bool, doc: Option<& } /// Count symbol `name` of `doc` (one that doesn't exist draws nothing). fn symbol(name: &str, doc: &Document, left: &mut Left, depth: usize) -> bool { - doc.symbols.iter().find(|s| s.name == name).is_none_or(|s| inside(&s.art, doc, left, depth)) + for s in &doc.symbols { + if !left.look_up(name) { + return false; + } + if s.name == name { + return inside(&s.art, doc, left, depth); + } + } + true } /// Count what `n` draws besides its children. fn own(n: &Node, doc: Option<&Document>, left: &mut Left, depth: usize) -> bool { - if !left.take(own_anchors(n)) { + let path = match &n.kind { + NodeKind::Text(t) => match &t.kind { + TextKind::Area { frame: p } | TextKind::OnPath { path: p, .. } => Some(p), + TextKind::Point => None, + }, + _ => n.path_data(), + }; + if !path.is_none_or(|p| left.path(p)) { return false; } let Some(doc) = doc else { return true }; @@ -170,23 +207,38 @@ fn small_node(n: &Node, nodes: usize, anchors: usize, masks: bool, doc: Option<& // Glyphs are counted only up to one past what the anchors left allow. NodeKind::Text(t) => t.runs.iter().all(|r| { let glyphs = r.text.chars().take(left.anchors / GLYPH_ANCHORS + 1).count(); - left.take(glyphs.saturating_mul(GLYPH_ANCHORS)) && r.inline.as_ref().is_none_or(|a| symbol(&a.symbol, doc, left, depth)) + left.step(1) + && left.take(glyphs.saturating_mul(GLYPH_ANCHORS)) + && r.inline.as_ref().is_none_or(|a| symbol(&a.symbol, doc, left, depth)) }), NodeKind::SymbolInstance { symbol: name, .. } => symbol(name, doc, left, depth), NodeKind::Mesh(m) => left.take(m.points.len().saturating_mul(MESH_POINT_ANCHORS)), NodeKind::Image(im) => left.take((im.width as usize).saturating_mul(im.height as usize) / IMAGE_PIXELS_PER_ANCHOR), - NodeKind::PlacedDocument(p) => vectorcraft_doc::placed_document::read_cached(p).is_some_and(|e| inside(&e.art, &e.doc, left, depth)), + NodeKind::PlacedDocument(p) => { + left.look_up(&p.key) && vectorcraft_doc::placed_document::read_cached(p).is_some_and(|e| inside(&e.art, &e.doc, left, depth)) + } _ => true, } } fn count(n: &Node, doc: Option<&Document>, left: &mut Left, depth: usize) -> bool { - if !own(n, doc, left, depth) { + if !(left.step(1) && own(n, doc, left, depth)) { return false; } let mask = n.extras().mask.as_deref().filter(|m| left.masks && !m.disabled).map(|m| &m.art); n.children().into_iter().flatten().chain(mask).all(|c| left.object() && count(c, doc, left, depth)) } - count(n, doc, &mut Left { nodes, anchors, masks }, 0) + let mut left = Left { nodes, anchors, steps: THUMB_COUNT_STEPS, masks }; + let small = count(n, doc, &mut left, 0); + (small, THUMB_COUNT_STEPS - left.steps) +} + +/// Is row `n` (an object of `doc`) light enough to make its thumbnail on the UI thread? `quick`: +/// whether its last thumbnail was quick to render, if it has one. +fn light_row(n: &Node, quick: Option, doc: &Document) -> bool { + match quick { + Some(quick) => quick && small_node(n, THUMB_COUNT_STEPS, LIGHT_THUMB_ANCHORS, true, Some(doc)), + None => small_node(n, LIGHT_THUMB_NODES, LIGHT_THUMB_ANCHORS, true, Some(doc)), + } } /// The thumbnail of `n` (`px` pixels square) as `r` renders it, on the UI thread or the worker. @@ -275,11 +327,7 @@ impl Thumbs { let in_budget = self.spent.1 < THUMB_BUDGET_MS && self.spent.2 < THUMB_BUDGET_COUNT; // A row drawn before is light when its last thumbnail was quick to render, unless its // object now has more anchors than the limit. - let doc = Some(src.doc.as_ref()); - let light = match light { - Some(quick) => quick && small_node(n, usize::MAX, LIGHT_THUMB_ANCHORS, true, doc), - None => small_node(n, LIGHT_THUMB_NODES, LIGHT_THUMB_ANCHORS, true, doc), - } && in_budget; + let light = light_row(n, light, src.doc) && in_budget; if !light && let Some(w) = &self.worker { let (doc, node) = (src.doc.clone(), n.clone()); let job: ThumbJob = (key, Arc::downgrade(n), px); @@ -327,7 +375,8 @@ pub(crate) fn real_thumb(ui: &Ui, src: &ThumbSource, n: &Arc, r: egui::Rec } /// Tiny vector thumbnail painted with egui (fallback when rendering isn't possible). A node with -/// more than [`LIGHT_THUMB_ANCHORS`] anchors paints nothing, since this runs on every frame and +/// more than [`LIGHT_THUMB_ANCHORS`] anchors, or that takes more than [`THUMB_COUNT_STEPS`] steps +/// to count, paints nothing, since this runs on every frame and /// measuring its bounds takes time in proportion to its anchor count. pub(super) fn thumb(ui: &Ui, n: &Node, r: egui::Rect) { if !small_node(n, usize::MAX, LIGHT_THUMB_ANCHORS, false, None) { @@ -563,6 +612,61 @@ mod tests { assert!(!small_in(&doc, &instance(1, "Deeper")), "one level deeper"); } + /// A document of symbols `L0` to `L{levels}`: `L0` is an empty group, and each one above it a + /// group of `fan` instances of the one below. + fn fan_out(levels: usize, fan: usize) -> Document { + let mut doc = with_symbol("L0", Node::group(NodeId(10), vec![])); + let mut id = 100; + for level in 1..=levels { + let below = format!("L{}", level - 1); + let kids = (0..fan) + .map(|_| { + id += 1; + Arc::new(instance(id, &below)) + }) + .collect(); + id += 1; + doc.symbols.push(vectorcraft_doc::Symbol { name: format!("L{level}"), art: Arc::new(Node::group(NodeId(id), kids)), dynamic: false }); + } + doc + } + + #[test] + fn symbols_that_each_hold_many_instances_are_counted_within_the_step_limit() { + // 40 instances on each of 4 levels: 40⁴ (2,560,000) empty groups, and no anchors. + let doc = fan_out(4, 40); + let top = instance(1, "L4"); + assert!(!light_row(&top, Some(true), &doc), "a row drawn before, quick to render"); + assert!(!light_row(&top, None, &doc), "a row not drawn yet"); + let (small, steps) = weigh(&top, THUMB_COUNT_STEPS, usize::MAX, true, Some(&doc)); + assert!(!small && steps <= THUMB_COUNT_STEPS, "{steps} steps"); + let (small, steps) = weigh(&top, usize::MAX, usize::MAX, true, Some(&doc)); + assert!(!small && steps <= THUMB_COUNT_STEPS, "{steps} steps without a limit on objects"); + // 5 instances on each of 3 levels stay light once drawn quickly. + let doc = fan_out(3, 5); + assert!(light_row(&instance(1, "L3"), Some(true), &doc)); + assert!(!light_row(&instance(1, "L3"), Some(false), &doc), "drawn slowly"); + } + + #[test] + fn empty_subpaths_text_runs_and_symbol_lookups_take_steps() { + let doc = Document::new(200.0, 200.0); + let style = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + let empty = Node::path(NodeId(1), PathData::new(vec![SubPath::default(); THUMB_COUNT_STEPS]), style.clone()); + assert!(!small_in(&doc, &empty), "a path of many empty subpaths"); + let fewer = Node::path(NodeId(1), PathData::new(vec![SubPath::default(); 100]), style); + assert!(small_in(&doc, &fewer), "a path of a few"); + let mut t = TextObject::point(Point::ZERO, "", CharStyle::default()); + t.runs = vec![vectorcraft_doc::TextRun::new("", CharStyle::default()); THUMB_COUNT_STEPS]; + assert!(!small_in(&doc, &Node::new(NodeId(2), NodeKind::Text(Box::new(t)))), "type of many empty runs"); + let mut doc = with_symbol("S", rect(10)); + for i in 0..THUMB_COUNT_STEPS { + doc.symbols.push(vectorcraft_doc::Symbol { name: format!("Other {i}"), art: Arc::new(rect(11)), dynamic: false }); + } + assert!(small_in(&doc, &instance(1, "S")), "the first of many symbols"); + assert!(!small_in(&doc, &instance(1, &format!("Other {}", THUMB_COUNT_STEPS - 1))), "the last of many symbols"); + } + #[test] fn the_painted_thumbnail_leaves_out_a_long_path() { let ctx = egui::Context::default(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 12fc7894b3..ae219584b7 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1274,7 +1274,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Delete, Cut, Group, Ungroup, Make and Release Compound Path, Make Clipping Mask, Send to Current Layer, Duplicate, Copy in the Move, Rotate, Scale, Reflect and Shear dialogs, Transform Each with Copy and each move of an Alt-drag take time in proportion to the size of the document (#1429). In the web build the status bar's render and UI times are measured with the browser's `performance.now()`, and the Layers panel stops rendering row thumbnails in a frame once they have taken 8 ms. On the desktop, the Layers panel renders a row's thumbnail on its thumbnail thread when the row's paths, and the paths of its opacity masks that are not disabled, hold more than 2,000 anchors in all. It already did this for the first thumbnail of a row of more than 200 objects. Until its first thumbnail is ready, the row shows boxes at the bounds of up to 41 of its paths, each in its path's solid fill or stroke color or in gray, when its own paths, without its opacity masks, hold at most 2,000 anchors in all, and an empty white box otherwise. With one path of 200,000 anchors, the first frame after the panel opens takes 2.4 ms instead of 393 ms (release build, median of three runs). - The same 2,000-anchor limit counts each glyph of type as 4 anchors, each point of a gradient mesh as 1 and every 100 pixels of an image as 1, and a symbol instance or a placed document counts the objects and anchors of the art it shows. A placed document whose file has not been read yet, or a symbol nested more than 8 deep (one that holds an instance of itself, for example), gets its first thumbnail on the thumbnail thread. The first frame after the panel opens takes 2.5 ms instead of 23.4 ms with 5,000 glyphs of point type, 2.1 ms instead of 346 ms with one instance of a symbol of a 200,000-anchor path, 1.7 ms instead of 11.7 ms with a 100 × 100 mesh, and 2.3 ms instead of 273 ms with a placed document of a 200,000-anchor path (release build, median of three runs). + The same 2,000-anchor limit counts each glyph of type as 4 anchors, each point of a gradient mesh as 1 and every 100 pixels of an image as 1, and a symbol instance or a placed document counts the objects and anchors of the art it shows. A placed document whose file has not been read yet, or a symbol nested more than 8 deep (one that holds an instance of itself, for example), gets its first thumbnail on the thumbnail thread, and so does a row whose art takes more than 20,000 steps to count (each object, subpath, text run and symbol looked at is one step). The first frame after the panel opens takes 2.4 ms instead of 19.8 ms with 5,000 glyphs of point type, 1.8 ms instead of 343 ms with one instance of a symbol of a 200,000-anchor path, 2.0 ms instead of 11.0 ms with a 100 × 100 mesh, and 2.1 ms instead of 274 ms with a placed document of a 200,000-anchor path (release build, median of three runs). In the web build, while a pan, zoom or rotation changes the view of a document whose last canvas render took more than 8 ms, the canvas draws the last frame moved with the view, and it renders the art again once the view has been still for 0.2 s. An Alt-drag with the Selection, Direct Selection, Group Selection, Rotate, Scale, Reflect or Shear tool copies the selection on its first move, and the moves after it transform those copies; the previews of the Move, Rotate, Scale, Reflect and Shear dialogs with Copy and Preview on copy the selection once in the same way (#1429). An Alt-drag of objects in perspective with the Perspective Selection tool, and an Alt-drag of a plane widget with that tool or the Perspective Grid tool, copy the objects on the first move, and the moves after it move those copies (#1429). From 26c27b8b85d36c78c266446aa8a667d41b30581d Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Wed, 4 Nov 2026 21:53:09 -0500 Subject: [PATCH 012/196] Artboards: Shift- and Ctrl/Cmd-click in the Artboards panel select several artboards with any tool, and Fill applies to all of them (#5698) --- crates/ui-egui/src/panels/artboards.rs | 9 ++++++++- crates/ui-egui/src/panels/artboards/tests.rs | 16 +++++++++++++--- crates/ui-egui/src/panels/properties.rs | 7 +++++-- crates/ui-egui/src/panels/properties/tests.rs | 19 +++++++++++++++++++ docs/target-app-parity.md | 4 ++-- docs/ui-parity.md | 5 +++-- 6 files changed, 50 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/panels/artboards.rs b/crates/ui-egui/src/panels/artboards.rs index 77023bacb1..deff9d8723 100644 --- a/crates/ui-egui/src/panels/artboards.rs +++ b/crates/ui-egui/src/panels/artboards.rs @@ -5,7 +5,8 @@ //! Artboard duplicates its artboard (as Duplicate Artboards does, with //! its art when the Artboard tool's Move/Copy Artwork with Artboard is on). The highlighted row is the active artboard, the one the status bar's navigator shows and //! Fit Artboard in Window fits: clicking a row makes it active, double-clicking its number also -//! fits it in the window. The options icon at a row's right end opens Artboard Options: a click on +//! fits it in the window. Shift-click selects a range of artboards and Ctrl/Cmd-click adds or +//! removes one, with any tool: another tool gives way to the Artboard tool first (#5698). The options icon at a row's right end opens Artboard Options: a click on //! the active artboard's icon, or a double-click on another row's icon. The lock column left of it //! shows a lock on a locked artboard, and a click there locks or unlocks the artboard //! (`artboard.setProps` with `locked`); Delete leaves locked artboards. @@ -488,6 +489,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } let m = ui.input(|inp| inp.modifiers); + // A Shift- or Ctrl/Cmd-click selects several artboards with any tool: it first + // switches to the Artboard tool, which holds the selection, so Properties and the + // Control bar then show the controls that change every selected artboard. + if resp.clicked() && (m.shift || m.command) && app.session.tool_id() != "artboard" { + app.select_tool("artboard"); + } let tool = app.session.tool_id() == "artboard"; row_clicked |= resp.clicked(); if resp.clicked() && tool && m.shift { diff --git a/crates/ui-egui/src/panels/artboards/tests.rs b/crates/ui-egui/src/panels/artboards/tests.rs index edae3a32e2..bf2b470503 100644 --- a/crates/ui-egui/src/panels/artboards/tests.rs +++ b/crates/ui-egui/src/panels/artboards/tests.rs @@ -156,10 +156,20 @@ fn shift_clicking_rows_selects_several_artboards() { frame(&mut app, 9.0, click(4, egui::Modifiers::NONE)); assert_eq!(picked(&app, 4), [3]); assert_eq!(highlighted(frame(&mut app, 10.0, vec![])), 1); - // With another tool, a Shift-click makes the row's artboard active, as a plain click does. + // With another tool, a plain click makes the row's artboard active and keeps the tool. app.select_tool("selection"); - frame(&mut app, 11.0, click(2, egui::Modifiers::SHIFT)); - assert_eq!((picked(&app, 4), selected(&app, 4)), (vec![1], 1)); + frame(&mut app, 11.0, click(2, egui::Modifiers::NONE)); + assert_eq!((app.session.tool_id(), selected(&app, 4)), ("selection", 1)); + // A Shift-click switches to the Artboard tool and selects the range (#5698). + frame(&mut app, 12.0, click(4, egui::Modifiers::SHIFT)); + assert_eq!(app.session.tool_id(), "artboard"); + assert_eq!((picked(&app, 4), selected(&app, 4)), (vec![1, 2, 3], 3)); + // So does a Ctrl/Cmd-click, adding one artboard to the one active. + app.select_tool("selection"); + frame(&mut app, 13.0, click(1, egui::Modifiers::NONE)); + frame(&mut app, 14.0, click(3, egui::Modifiers::COMMAND)); + assert_eq!(app.session.tool_id(), "artboard"); + assert_eq!((picked(&app, 4), selected(&app, 4)), (vec![0, 2], 2)); } /// Double-clicking a row's number goes to its artboard and its name renames it; a click on diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index b8a42e9285..79632f4004 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -462,7 +462,7 @@ fn multi_color(app: &mut VectorcraftApp, ctx: &egui::Context) -> bool { /// Edit Artboards (the Artboard tool): the active artboard's name, which can be edited to rename /// it, and the Artboard Options icon; its position and size, its preset and /// orientation (#671) (with Scale Artwork with Artboard on, a new size scales its art, #602; a new -/// W or H, preset or orientation goes to every selected artboard, in one undo step), its Fill (background color), Move +/// W or H, preset or orientation goes to every selected artboard, in one undo step), its Fill (background color, also for every selected artboard), Move /// and Scale Artwork with Artboard, New Artboard and Delete Artboard, and Quick Actions: Rearrange All (#681) and /// Exit back to the Selection tool (#530). fn artboard_sections(app: &mut VectorcraftApp, ui: &mut Ui) { @@ -681,8 +681,11 @@ fn artboard_fill_row(app: &mut VectorcraftApp, ui: &mut Ui, i: usize, color: Opt None => {} } }); + // A Fill chosen from the list goes to every selected artboard, in one undo step (#5698). if let Some(c) = set { - app.run("artboard.setProps", json!({"index": i, "color": c.as_ref().map(super::color_json)})).ok(); + let color = c.as_ref().map(super::color_json); + let indices = super::artboards::renamed_with(app, i); + super::artboards::set_props(app, &indices, json!({}), |j, _| Some(json!({"index": j, "color": color}))).ok(); } if pick { app.run("ui.colorPicker", json!({"artboard": i})).ok(); diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 30ac3cd455..7c5e69e119 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -665,6 +665,25 @@ fn edit_artboards_fill_sets_the_background_color() { assert_eq!(app.ui.dialog.as_ref().map(|d| d.fields.get("artboard")), Some(Some(&json!(1))), "the chip opens it too"); } +/// #5698: with Artboards 1 and 3 selected, a Fill chosen in Edit Artboards goes to both, in one +/// command and one undo step; Artboard 2 keeps none. +#[test] +fn edit_artboards_fill_sets_every_selected_artboard() { + let mut app = two_selected_artboards(); + let colors = |app: &VectorcraftApp| app.session.doc().unwrap().doc.artboards.iter().map(|a| a.color).collect::>(); + let undo = app.session.doc().unwrap().history.undo.len(); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let texts = frame(&mut app, &ctx, vec![]); + click(&mut app, &ctx, &texts, "None"); + let texts = frame(&mut app, &ctx, vec![]); + let commands = app.run_count; + click(&mut app, &ctx, &texts, "Black"); + assert_eq!(app.run_count.wrapping_sub(commands), 1, "one command"); + assert_eq!(colors(&app), [Some(Color::BLACK), None, Some(Color::BLACK)]); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); +} + fn artboard_deletion_app(count: usize) -> VectorcraftApp { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 200, "height": 100, "artboards": count})).unwrap(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ae219584b7..3042e2fd33 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-05 · **Change:** minor (PDF import keeps DeviceN gradients of a spot ink over process plates, #3235; 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-05 · **Change:** minor (Artboards panel multi-select with any tool, Fill for every selected artboard; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -567,7 +567,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Contextual controls in Properties:** the [Properties panel overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/properties-panel-overview.html) lists controls that appear for particular selections and tools; Properties has them, each running the existing command. Quick Actions has Blend Options for one selected blend, with the Blend tool or any other, as the [blending page](https://helpx.adobe.com/illustrator/using/blending-objects.html) describes (#4817) (the Blend Options dialog, OK one undo step) and Merge Live Paint when a Live Paint group is selected with more paths and nothing Live Paint refuses (`livePaint.merge`). Appearance has the stroke's Variable Width Profile list, the Control bar's, with the Width tool or when the stroke has a variable width (`stroke.set {profile}`), and beside fx the Delete icon: with one effect on the one selected object (its own or a fill's or stroke's) its name and an icon that removes it (`effect.remove`), with several an icon that opens the Appearance panel, as the overview describes. With Direct Selection and corners of one path selected, Corner and Corner Radius set the kind and radius of those corners (`object.setLiveShape`); a live rectangle's and polygon's own rows already do. Each edit is one undo step. The overview's Variable Font icon was already in Character. Not checked against the reference app: whether Merge needs two Live Paint groups (the overview speaks of several selected groups; `livePaint.merge` takes a group and paths), and where exactly each control sits in its section. Evidence: `panels::properties::tests::{blend_options_is_a_quick_action_for_one_blend_with_the_blend_tool, merge_live_paint_is_a_quick_action_for_a_live_paint_group_and_more, the_width_profile_shows_for_a_variable_width_or_the_width_tool, direct_selected_corners_show_their_kind_and_radius, one_effect_has_a_delete_icon_in_appearance}`. - **Edit Artboards in Properties:** the active artboard's name is a field. Typing a new name and pressing Enter or clicking elsewhere renames that artboard in one undo step, as the Artboards panel's rename does (`artboard.setProps {index, name}`); pressing Escape or leaving the field empty keeps the old name. A click on the Artboard Options icon beside the field opens Artboard Options for the active artboard, as double-clicking the Artboard tool's button does (`tool.options {tool: "artboard"}`). Pointer and key tests in `panels/properties.rs` cover both. Public references: [Resize artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/resize-artboards.html) and [Create and add new artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/add-new-artboards.html). - **Artboard background colors:** each artboard can have a background color (`artboard.setProps {index, color}`, `color: null` removes it). With the Artboard tool, Properties has a Fill row: its list sets None, White or Black, and its chip and its Color Picker… item open the Color Picker for the artboard. Artboard Options has a Background Color row with a list that sets None, White or Black, and a color button. The canvas draws the artboard's paper in the color, multiplied with the paper color while Simulate Colored Paper is on, and the transparency grid still covers it. The native format saves the color, and a document without colors saves as before. Exports draw it behind each exported artboard's art, inside the artboard and in the color's own model: raster formats (on a transparent background too), PDF, SVG and EPS pages, `.ai` files' PDF pages, Export for Screens and print, whose preview shows it; files with editing data keep it as the artboard's color, not as art. Export for Screens has Include Artboard Fill beside Include Bleed (on by default and remembered; `includeArtboardFill: false`, which `document.export` and `file.print` take too, leaves it out) (#4937). Not done: `.ai` files the reference app reads keep it only in VectorCraft's editing data, and `.ai`/PDF import doesn't read a background color from the reference app's own data. Engine, canvas, Properties, Color Picker, Artboard Options, export (`fileio::tests_artboard_fill`) and Export for Screens dialog tests cover it. Public reference: [Apply colors to artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/add-background-color-to-artboards.html). -- **Resizing several artboards:** with several artboards selected with the Artboard tool, a new W or H in Properties, the Transform panel or the Control bar, a preset or an orientation in Properties or the Control bar, and a new Width or Height in Artboard Options resize every selected artboard in one undo step (`artboard.setProps {artboards}`); with Scale Artwork with Artboard on, Properties, the Transform panel and the Control bar scale each object once, with the artboard it was inside before the change. The Transform panel, the Control bar and Artboard Options resize each one about its own reference point, a preset sizes each one in its own orientation, and X and Y still move the active artboard alone. Pointer and key tests in `panels/properties.rs`, dialog tests in `dialogs/tests.rs` and an engine test in `tests/xform.rs` cover them. Public references: [Artboard Enhancements In Illustrator CC](https://blog.adobe.com/en/publish/2017/11/10/artboard-enhancements-in-illustrator-cc) (a height and a width entered once resize every selected artboard) and [Using multiple artboards](https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (2019). +- **Resizing several artboards:** with several artboards selected with the Artboard tool, a new W or H in Properties, the Transform panel or the Control bar, a preset or an orientation in Properties or the Control bar, and a new Width or Height in Artboard Options resize every selected artboard in one undo step (`artboard.setProps {artboards}`), and a Fill chosen in Properties colors each of them (#5698); a Shift- or Ctrl/Cmd-click on an Artboards panel row with another tool in use switches to the Artboard tool and selects as it does; with Scale Artwork with Artboard on, Properties, the Transform panel and the Control bar scale each object once, with the artboard it was inside before the change. The Transform panel, the Control bar and Artboard Options resize each one about its own reference point, a preset sizes each one in its own orientation, and X and Y still move the active artboard alone. Pointer and key tests in `panels/properties.rs`, dialog tests in `dialogs/tests.rs` and an engine test in `tests/xform.rs` cover them. Public references: [Artboard Enhancements In Illustrator CC](https://blog.adobe.com/en/publish/2017/11/10/artboard-enhancements-in-illustrator-cc) (a height and a width entered once resize every selected artboard) and [Using multiple artboards](https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (2019). - **Artboard Escape routing:** Escape leaves Artboard editing for Selection; during a drag it first cancels the gesture. Headless egui key events cover idle Escape, active-drag cancellation and a subsequent Escape in `tests/distortkeys.rs`. - **Escape in the distort tools:** Escape during a Puppet Warp pin drag or turn, a Perspective Grid tool handle or plane widget drag, a Perspective Selection move, resize or plane widget drag, or a Liquify stroke cancels it: the art goes back to how the press found it, no undo step is added, and the tool stays chosen. Puppet Warp also selects again the pins selected before the press, and Escape during a Liquify Alt-drag puts the brush size back. Regression tests: `escape_cancels_*` in `crates/tools/src/distort/puppet.rs`, `perspective.rs` and `liquify.rs`, and `escape_cancels_a_puppet_warp_perspective_or_liquify_drag` in `tests/distortkeys.rs`. - **Shift with the Artboard tool:** a Shift-click adds an artboard to the selection or takes it out when the button comes up. A Shift-drag inside an artboard draws a new artboard there, and a Shift-drag on the pasteboard is a marquee that toggles the artboards it touches, as the [default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) (a Shift-drag draws an artboard within an existing one) and [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (archived copy) describe. Shift no longer keeps an artboard move at 45° steps or a drawn artboard square. Escape during a marquee or while a new artboard is being drawn cancels it and keeps the Artboard tool. Pointer and key tests in `crates/tools/src/xform/artboard.rs` cover the four gestures and Escape. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 50cda9a086..b66aadac0a 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (isolation mode: a locked or hidden layer keeps the isolated art from clicks and marquees; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (Artboards panel multi-select with any tool, Fill for every selected artboard; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) ## Feature submission evidence @@ -30,6 +30,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | Artboards panel: a Shift- or Ctrl/Cmd-click on a row selects several artboards with any tool, switching to the Artboard tool first, so a preset, orientation, size or Fill set in Properties or the Control bar goes to every selected artboard; Fill used to set the active artboard only (#5698); scores and estimates unchanged | | 2026-11-04 | minor | Isolation mode: once the layer, or a group, around the isolated object is locked or hidden, a click or a marquee with the Selection tool no longer selects the isolated art (part of #5309); scores and estimates unchanged | | 2026-11-04 | minor | Transform Each's Scale has the documented Relative and Absolute radio buttons: percentages of each object's size, or the width and height it becomes (`object.transformEach` `relative`); the two scales have the link that keeps them in proportion (`__constrain`, as the shape dialogs'), and the panel lists Scale, Move, Rotate, the Options in two columns, the Reference Point and Preview (level with Copy, Cancel and OK) in the documented order; scores and estimates unchanged | | 2026-11-04 | minor | Cmd+Space pressed during an active drawing drag keeps that tool's cursor; clarify that Space can move an in-progress shape or anchor. Scores and estimates unchanged. | @@ -253,7 +254,7 @@ tools, never checked side by side) isn't captured row by row. | Escape leaves Artboard editing for Selection; during a drag it first cancels the gesture | done | Headless egui key events cover idle Escape, active-drag cancellation and a subsequent Escape in `tests/distortkeys.rs`. | | Escape while typing ends the edit, keeps the type selected and switches to the Selection tool | done | #1802 (#1686, #1656) | | Selection tool: selected area type and type on a path show an in port and an out port (empty, an arrow where threaded, the red "+" of overflow); a click on either loads the text cursor; a click on a closed path, on empty canvas or a drag threads the text there, after the clicked frame from its out port, before it from its in port; Escape or another tool drops it; a double-click on a threaded port breaks the thread there | partial | #2572 (`text.thread.add`, `before` for the in port); the out port sits on the frame's right side above the bottom-right corner handle and the in port on its left side below the top-left one, so the handles can still be grabbed; a double-click on a threaded port breaks the thread (`text.thread.break`, [archived help](https://web.archive.org/web/20220127090642/https://helpx.adobe.com/illustrator/using/creating-text.html)); the loaded cursor borrows the I-beam | -| Shift-click selects several artboards (Artboard tool, Artboards panel); they move, Alt-copy and delete together | done | `artboard.move`/`artboard.delete` `indices` (#1139); panel menu, trash and Properties share selected-set deletion; all-selected retains artboard 1 and a single board cannot be deleted, with pointer-event and Undo/Redo coverage | +| Shift-click selects several artboards (Artboard tool, Artboards panel); they move, Alt-copy and delete together | done | `artboard.move`/`artboard.delete` `indices` (#1139); in the panel, Shift- and Ctrl/Cmd-click work with any tool by switching to the Artboard tool (#5698); panel menu, trash and Properties share selected-set deletion; all-selected retains artboard 1 and a single board cannot be deleted, with pointer-event and Undo/Redo coverage | | Artboards panel: drag a row above or below another to reorder the artboards (as Move Up / Move Down do) | done | #4687; a line shows where the row lands, `artboard.reorder` in one undo step, the moved artboard becomes active; public forum answers describe the drag | | Artboards panel › Delete Empty Artboards | done | `artboard.deleteEmpty`; one undo step, guides go too, locked artboards stay, and artboard 1 when every artboard is empty and none is locked; an artboard is empty when no object (hidden, locked and template art included; guides not) has visual bounds that meet or touch it, a group counting by its members and a clip group or clipping layer by its members inside the clip (our reading of "no artwork"; the pages give no finer rule); [spec](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/delete-artboards.html) | | Artboard Delete/Backspace delete selected boards while protecting artwork, the last board and active drags | done | Headless shortcut regressions in `tests/distortkeys.rs` cover retaining the original first board when all are selected, single-board protection, artwork, saved state and Undo/Redo; the navigator follows the tool’s surviving board through repeated deletion and history changes. | From e6331e559ad3d77cef459ad8d06ad0be64b60087 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 15:58:47 -0800 Subject: [PATCH 013/196] Render: a moved path reuses its stroke outline A path object that moves without changing shape drew its stroke by outlining the whole line again, because the stroke outline cache is keyed by the node. The renderer now keeps, per object, stroke and outline width, the latest outline with the line it was made from. When the new line is that line moved, it draws the kept outline moved by the same offset, and moves the region a long path was outlined in with it. Scaling, rotating or editing the path, changing the stroke's width, join, cap, dashes or profile, a zoom that changes the outline's tolerance, and a move that takes the view past the outlined region still outline the stroke again. Only the latest outline of each stroke keeps its line. --- crates/render/src/frame.rs | 13 +- crates/render/src/lib.rs | 7 +- crates/render/src/renderer.rs | 9 +- crates/render/src/renderer/paint.rs | 120 ++++++++++++-- crates/render/src/tests.rs | 1 + crates/render/src/tests/movedstroke.rs | 206 +++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 7 files changed, 335 insertions(+), 22 deletions(-) create mode 100644 crates/render/src/tests/movedstroke.rs diff --git a/crates/render/src/frame.rs b/crates/render/src/frame.rs index 81b7198937..715237b06e 100644 --- a/crates/render/src/frame.rs +++ b/crates/render/src/frame.rs @@ -30,14 +30,21 @@ pub(crate) type PtrMap = HashMap, pub(crate) outline: Arc, pub(crate) stamp: u64, pub(crate) crop: Option, + pub(crate) line: Option>, } /// The slices of a stroke whose gradient runs along or across it, each with its paint and bounds. diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index a145ebad1b..cace4f1655 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -74,6 +74,9 @@ pub struct Renderer { /// Expanded stroke outlines keyed by ([`Self::stroke_owner`], stroke layer address, width bits, /// tolerance level): panning re-renders reuse them instead of re-expanding every stroke. strokes: PtrMap, + /// The key in `strokes` of the latest outline of each stroke of an object, under its + /// [`MovedKey`]: a moved copy of the object draws that outline moved ([`Self::moved_outline`]). + moved_strokes: PtrMap, /// Expanded character stroke outlines, with the glyph geometry kept in `texts` they belong to, /// keyed by ([`Self::stroke_owner`] of that geometry, run, width bits, tolerance level): type /// that doesn't change draws them again instead of expanding its strokes in every frame. Within @@ -215,7 +218,9 @@ mod threads; pub use bounds::{drawn_bounds, drawn_outline, effect_bounds, painted_bounds}; pub use frame::FrameStats; -use frame::{ClipEntry, ClipPaintEntry, Frame, FxArtEntry, GeomEntry, PlacedEntry, PlacedKey, PtrHasher, PtrMap, SliceEntry, StrokeEntry, StrokeKey}; +use frame::{ + ClipEntry, ClipPaintEntry, Frame, FxArtEntry, GeomEntry, MovedKey, PlacedEntry, PlacedKey, PtrHasher, PtrMap, SliceEntry, StrokeEntry, StrokeKey, +}; #[cfg(test)] use frame::{OFFSCREEN_PIXELS, Slices}; pub use geometry::region_pixels; diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 87c283f321..638de74e88 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -1,8 +1,8 @@ use super::blobs::{blob_key, blob_pixmap, image_mip, lookup, mask_value, mip_level, plain_image, shape_masked_image, white_shape_mask}; use super::clock::now; use super::frame::{ - ClipEntry, ClipPaintEntry, Frame, FrameStats, GeomEntry, MAX_INLINE_DEPTH, MISSING_INLINE_LOGGED, PlacedEntry, PlacedKey, PtrMap, SliceEntry, - Slices, StrokeEntry, + ClipEntry, ClipPaintEntry, Frame, FrameStats, GeomEntry, MAX_INLINE_DEPTH, MISSING_INLINE_LOGGED, MovedKey, PlacedEntry, PlacedKey, PtrMap, + SliceEntry, Slices, StrokeEntry, }; use super::geometry::{MAX_GUIDE_DASHES, polygon_length, rects_overlap, region_pixels}; use super::node_checks::{ @@ -24,7 +24,7 @@ mod paint; mod text; #[cfg(test)] -pub(crate) use paint::{CROP_STROKES, crop_line}; +pub(crate) use paint::{CROP_STROKES, STROKES_OUTLINED, crop_line, offset_between}; impl Renderer { pub fn new() -> Self { @@ -38,6 +38,7 @@ impl Renderer { symbols: vec![], plugin_revision: 0, strokes: PtrMap::default(), + moved_strokes: PtrMap::default(), char_strokes: FrameCache::new(lru::CHAR_STROKE_BUDGET, 0), cur: None, made_again: false, @@ -186,6 +187,8 @@ impl Renderer { self.kept.retain(|_, e| g - e.stamp <= 3 || geom.get(&(Arc::as_ptr(&e.node) as usize)).is_some_and(|k| Arc::ptr_eq(&k.node, &e.node))); if self.strokes.len() > 1024 { self.strokes.retain(|_, e| g - e.stamp <= 3); + let strokes = &self.strokes; + self.moved_strokes.retain(|_, k| strokes.contains_key(k)); } if self.stroke_slices.len() > 256 { self.stroke_slices.retain(|_, e| g - e.stamp <= 3); diff --git a/crates/render/src/renderer/paint.rs b/crates/render/src/renderer/paint.rs index f31863aa1c..875b39bca1 100644 --- a/crates/render/src/renderer/paint.rs +++ b/crates/render/src/renderer/paint.rs @@ -1,7 +1,7 @@ use super::{ - Affine, AppearanceItem, Arc, BezPath, BlendMode, Compose, FillRule, Frame, Ink, Mix, Node, Rect, RenderContext, Renderer, Shape, SliceEntry, - Slices, StrokeAlign, StrokeEntry, StrokeLayer, TextGeom, blend_mode, drawable, effects, fill_rule, fx, kurbo, lru, owns_stroke, peniko, - rects_overlap, + Affine, AppearanceItem, Arc, BezPath, BlendMode, Compose, FillRule, Frame, Ink, Mix, MovedKey, Node, Rect, RenderContext, Renderer, Shape, + SliceEntry, Slices, StrokeAlign, StrokeEntry, StrokeLayer, TextGeom, blend_mode, drawable, effects, fill_rule, fx, kurbo, lru, owns_stroke, + peniko, rects_overlap, }; use crate::paint; @@ -269,32 +269,90 @@ impl Renderer { e.stamp = self.stamp; return Some(e.outline.clone()); } + // Under its object's id, the stroke's place and the outline's width and tolerance, the key + // of the stroke's latest outline is kept, except for art made again in every frame. + let place = node.appearance.items.iter().position(|i| matches!(i, AppearanceItem::Stroke(s) if std::ptr::eq(s, st))); + let moved = place.filter(|_| !self.made_again).map(|place| (node.id.0, place, width.to_bits(), level)); + let kept = moved.map(|_| Arc::new(line.clone())); + if let Some(mk) = moved + && let Some((outline, crop)) = self.moved_outline(mk, &node, st, line, v) + { + self.strokes.insert(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop, line: kept }); + self.keep_latest(mk, key); + return Some(outline); + } + #[cfg(test)] + STROKES_OUTLINED.with(|n| n.set(n.get() + 1)); // A long stroke without a width profile is outlined only in and around the view, with a // margin of the view's own size on each side ([`crop_dashed`] for a dashed one, // [`crop_line`] otherwise). let region = v.inflate(v.width(), v.height()); let tol = 2f64.powi(level); - if crops() + let (outline, crop) = if crops() && line.elements().len() > CROP_ELEMENTS && st.dash.is_some() && st.profile.is_none() && let Some(outline) = crop_dashed(line, st, width, region, crop_reach(st, width, f.px, tol), tol) { - let outline = Arc::new(outline); - self.strokes.insert(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop: Some(region) }); - return Some(outline); - } - let cropped = (crops() && line.elements().len() > CROP_ELEMENTS && st.dash.is_none() && st.profile.is_none()) - .then(|| crop_line(line, region, crop_reach(st, width, f.px, tol), width)) - .flatten(); - let (outline, crop) = match cropped { - Some(part) => (Arc::new(effects::stroke::line_outline(&part, st, width, tol)), Some(region)), - None => (expand(), None), + (Arc::new(outline), Some(region)) + } else { + let cropped = (crops() && line.elements().len() > CROP_ELEMENTS && st.dash.is_none() && st.profile.is_none()) + .then(|| crop_line(line, region, crop_reach(st, width, f.px, tol), width)) + .flatten(); + match cropped { + Some(part) => (Arc::new(effects::stroke::line_outline(&part, st, width, tol)), Some(region)), + None => (expand(), None), + } }; - self.strokes.insert(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop }); + self.strokes.insert(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop, line: kept }); + if let Some(mk) = moved { + self.keep_latest(mk, key); + } Some(outline) } + /// Lists `key` as the latest outline under `mk`, and drops the line kept with the outline listed + /// there before, which no moved copy draws from any more: one line is kept per [`MovedKey`]. + fn keep_latest(&mut self, mk: MovedKey, key: crate::frame::StrokeKey) { + if let Some(before) = self.moved_strokes.insert(mk, key) + && before != key + && let Some(e) = self.strokes.get_mut(&before) + { + e.line = None; + } + } + + /// The outline of stroke `st` of `node` along `line`, made from the latest outline kept under + /// `mk` ([`MovedKey`]) when that outline's object is `node` changed, its stroke differs from `st` + /// in its paint at most, and its line is `line` moved (to within rounding): that outline moved + /// by the same offset, with the region it was cropped to moved too. `None` when there is no + /// such outline, or when its region does not hold the view `v`. + fn moved_outline(&self, mk: MovedKey, node: &Node, st: &StrokeLayer, line: &BezPath, v: Rect) -> Option<(Arc, Option)> { + let e = self.strokes.get(self.moved_strokes.get(&mk)?)?; + let was = e.line.as_deref()?; + if e.node.id != node.id { + return None; + } + let Some(AppearanceItem::Stroke(old)) = e.node.appearance.items.get(mk.1) else { + return None; + }; + let unpainted = |s: &StrokeLayer| StrokeLayer { paint: vectorcraft_color::Paint::None, ..s.clone() }; + if !std::ptr::eq(old, st) && unpainted(old) != unpainted(st) { + return None; + } + let by = offset_between(was, line)?; + let crop = e.crop.map(|r| r + by); + if crop.is_some_and(|r| r.x0 > v.x0 || r.y0 > v.y0 || r.x1 < v.x1 || r.y1 < v.y1) { + return None; + } + if by == kurbo::Vec2::ZERO { + return Some((e.outline.clone(), crop)); + } + let mut outline = (*e.outline).clone(); + outline.apply_affine(Affine::translate(by)); + Some((Arc::new(outline), crop)) + } + /// What the `strokes`, `char_strokes` and `stroke_slices` keys hold for a stroke owner at /// `address` (`self.cur` or kept glyph geometry): the address, or 0 while art made again in /// every frame is drawn ([`Self::made_again`]). @@ -311,6 +369,38 @@ pub(crate) const CROP_ELEMENTS: usize = 1024; thread_local! { /// Whether long strokes are outlined near the view only on this thread ([`crop_line`]). pub(crate) static CROP_STROKES: std::cell::Cell = const { std::cell::Cell::new(true) }; + /// How many stroke outlines of nodes [`Renderer::cached_stroke`] has made on this thread. + pub(crate) static STROKES_OUTLINED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The offset that moves path `was` onto path `now`, when `now` is `was` moved (each coordinate +/// within a few units in the last place of the moved one, the error that adding the offset and +/// measuring it from the first points can make). `None` otherwise, and for an empty path. +pub(crate) fn offset_between(was: &BezPath, now: &BezPath) -> Option { + use kurbo::PathEl; + let (was, now) = (was.elements(), now.elements()); + if was.len() != now.len() { + return None; + } + let (by, first) = match (was.first()?, now.first()?) { + (PathEl::MoveTo(a), PathEl::MoveTo(b)) => (*b - *a, a.x.abs().max(b.x.abs()).max(a.y.abs()).max(b.y.abs())), + _ => return None, + }; + if !by.is_finite() { + return None; + } + let near = |a: &kurbo::Point, b: &kurbo::Point| { + let close = |a: f64, by: f64, b: f64| (a + by - b).abs() <= 4.0 * f64::EPSILON * (a.abs() + b.abs() + first); + close(a.x, by.x, b.x) && close(a.y, by.y, b.y) + }; + let moved = was.iter().zip(now).all(|pair| match pair { + (PathEl::MoveTo(a), PathEl::MoveTo(b)) | (PathEl::LineTo(a), PathEl::LineTo(b)) => near(a, b), + (PathEl::QuadTo(a0, a1), PathEl::QuadTo(b0, b1)) => near(a0, b0) && near(a1, b1), + (PathEl::CurveTo(a0, a1, a2), PathEl::CurveTo(b0, b1, b2)) => near(a0, b0) && near(a1, b1) && near(a2, b2), + (PathEl::ClosePath, PathEl::ClosePath) => true, + _ => false, + }); + moved.then_some(by) } fn crops() -> bool { diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index ffeb6cc6f7..b7884026b7 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -24,6 +24,7 @@ mod knockout; mod layeropts; mod longstroke; mod memory; +mod movedstroke; mod objectfx; mod placed_document; mod rasterize; diff --git a/crates/render/src/tests/movedstroke.rs b/crates/render/src/tests/movedstroke.rs new file mode 100644 index 0000000000..67b7de9055 --- /dev/null +++ b/crates/render/src/tests/movedstroke.rs @@ -0,0 +1,206 @@ +//! A moved object draws its stroke from the outline made for it before it moved, moved by the same +//! offset, with the pixels a new renderer draws. A change other than a move outlines the stroke +//! again. + +use vectorcraft_color::{Color, Gradient, GradientPaint, Paint}; +use vectorcraft_doc::{Appearance, AppearanceItem, Dash, FillLayer, LineCap, LineJoin, Node, NodeId, NodeKind, StrokeLayer, WidthProfile}; +use vectorcraft_geom::{PathData, Point, Vec2}; + +use crate::renderer::{STROKES_OUTLINED, offset_between}; +use crate::*; + +const SIZE: u32 = 200; + +/// The view that shows `at` in the middle of the 200×200 frame. +fn view_at(at: Point) -> Affine { + Affine::translate((100.0 - at.x, 100.0 - at.y)) +} + +fn render(r: &mut Renderer, d: &Document, at: Point) -> Rendered { + r.render(d, SIZE, SIZE, view_at(at), &RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }) +} + +/// How many stroke outlines the renderers on this thread have made. +fn outlined() -> usize { + STROKES_OUTLINED.with(std::cell::Cell::get) +} + +/// A document holding `path` painted with `items`, and the path's id. +fn doc(path: &BezPath, items: Vec) -> (Document, NodeId) { + let mut d = Document::new(1000.0, 1000.0); + let id = d.alloc_id(); + let n = Node::path(id, PathData::from_bezpath(path), Appearance { items, ..Default::default() }); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + (d, id) +} + +fn stroke(width: f64, join: LineJoin, cap: LineCap) -> StrokeLayer { + let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), width); + st.join = join; + st.cap = cap; + st.miter_limit = 10.0; + st +} + +fn dashed(mut st: StrokeLayer, pattern: &[f64]) -> StrokeLayer { + st.dash = Some(Dash { pattern: pattern.to_vec(), offset: 0.0, align_corners: false }); + st +} + +/// `n` anchors 8 pt apart, up and down by 30 pt, every third segment curved. +fn zigzag(n: usize) -> BezPath { + let mut bp = BezPath::new(); + let at = |i: usize| Point::new(i as f64 * 8.0, if i.is_multiple_of(2) { 0.0 } else { 30.0 }); + bp.move_to(at(0)); + for i in 1..n { + if i % 3 == 0 { + bp.curve_to(at(i - 1) + Vec2::new(6.0, 0.0), at(i) + Vec2::new(-6.0, 10.0), at(i)); + } else { + bp.line_to(at(i)); + } + } + bp +} + +/// A closed polygon of `n` anchors round a circle of radius `r` about the origin. +fn ring(n: usize, r: f64) -> BezPath { + let mut bp = BezPath::new(); + for i in 0..n { + let t = i as f64 / n as f64 * std::f64::consts::TAU; + let p = Point::new(r * t.cos(), r * t.sin()); + if i == 0 { bp.move_to(p) } else { bp.line_to(p) } + } + bp.close_path(); + bp +} + +/// The documents of the cases: open and closed paths, short and long (outlined near the view), plain, +/// dashed, with a width profile, and filled with a gradient (which a move changes, so the moved +/// object has an appearance of its own), each with the point the view is centered on. +fn cases() -> Vec<(&'static str, (Document, NodeId), Point)> { + let round = stroke(6.0, LineJoin::Round, LineCap::Round); + let mut lens = stroke(10.0, LineJoin::Round, LineCap::Butt); + lens.profile = Some(WidthProfile { points: vec![(0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 0.0, 0.0)] }); + let gradient = FillLayer::new(Paint::Gradient(Box::new(GradientPaint::new(Gradient::default())))); + let only = |st: StrokeLayer| vec![AppearanceItem::Stroke(st)]; + vec![ + ("a short open path", doc(&zigzag(20), only(stroke(5.0, LineJoin::Miter, LineCap::Square))), Point::new(70.0, 15.0)), + ("a short closed path, dashed", doc(&ring(40, 80.0), only(dashed(round.clone(), &[12.0, 7.0]))), Point::new(0.0, 0.0)), + ("a long open path", doc(&zigzag(3000), only(stroke(6.0, LineJoin::Miter, LineCap::Square))), Point::new(12_000.0, 15.0)), + ("a long closed path", doc(&ring(4000, 5000.0), only(round.clone())), Point::new(0.0, 5000.0)), + ( + "a long open path, dashed", + doc(&zigzag(3000), only(dashed(stroke(5.0, LineJoin::Bevel, LineCap::Butt), &[30.0, 12.0]))), + Point::new(8000.0, 15.0), + ), + ( + "a long closed path, dashed, filled with a gradient", + doc(&ring(4000, 5000.0), vec![AppearanceItem::Fill(gradient), AppearanceItem::Stroke(dashed(round, &[25.0, 15.0]))]), + Point::new(-5000.0, 0.0), + ), + ("a long open path, a width profile", doc(&zigzag(3000), only(lens)), Point::new(12_000.0, 15.0)), + ] +} + +/// Draws `d` after `change` with `r` and with a new renderer, checks that the two draw the same +/// pixels, and returns how many stroke outlines `r` made. +fn after(r: &mut Renderer, d: &mut Document, id: NodeId, at: Point, change: impl FnOnce(&mut Node)) -> usize { + change(d.node_mut(id).unwrap()); + let before = outlined(); + let img = render(r, d, at); + let made = outlined() - before; + assert!(img.pixels == render(&mut Renderer::new(), d, at).pixels, "the same pixels as a new renderer"); + assert!(img.pixels.chunks(4).any(|p| p[0] < 128), "the stroke shows"); + made +} + +#[test] +fn a_moved_path_draws_its_stroke_from_the_outline_made_before() { + for (what, (mut d, id), at) in cases() { + let mut r = Renderer::new(); + render(&mut r, &d, at); + for by in [Vec2::new(1.0, 0.0), Vec2::new(0.25, -0.5), Vec2::new(-3.0, 2.0), Vec2::new(0.1, 0.0)] { + let made = after(&mut r, &mut d, id, at, |n| n.transform(Affine::translate(by), true)); + assert_eq!(made, 0, "{what}, moved by {by:?}: no new outline"); + } + // A fill of another color keeps the path where it is. + let made = after(&mut r, &mut d, id, at, |n| { + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.paint = Paint::solid(Color::rgb(0.0, 0.0, 1.0)); + } + }); + assert_eq!(made, 0, "{what}, a fill changed: no new outline"); + assert_eq!(r.strokes.values().filter(|e| e.line.is_some()).count(), 1, "{what}: one line kept"); + } +} + +#[test] +fn a_path_changed_otherwise_outlines_its_stroke_again() { + let edit_anchor = |n: &mut Node| { + let NodeKind::Path { path, .. } = &mut n.kind else { + panic!("not a path"); + }; + let mut bp = path.to_bezpath(); + let mut els = bp.elements().to_vec(); + if let Some(kurbo::PathEl::LineTo(p)) = els.get_mut(2) { + *p += Vec2::new(0.0, 3.0); + } + bp = BezPath::from_vec(els); + *path = PathData::from_bezpath(&bp); + }; + for (what, (mut d, id), at) in cases() { + let mut r = Renderer::new(); + render(&mut r, &d, at); + // A move, then an edit of an anchor near the path's start. + assert_eq!(after(&mut r, &mut d, id, at, |n| n.transform(Affine::translate((0.5, 0.0)), true)), 0, "{what}: moved"); + assert_eq!(after(&mut r, &mut d, id, at, edit_anchor), 1, "{what}: an anchor moved"); + // Scaled and rotated about the view's center, stroke weights kept. + assert_eq!(after(&mut r, &mut d, id, at, |n| n.transform(Affine::scale_about(1.001, at), false)), 1, "{what}: scaled"); + assert_eq!(after(&mut r, &mut d, id, at, |n| n.transform(Affine::rotate_about(0.001, at), false)), 1, "{what}: rotated"); + // Another join. + let rejoin = |n: &mut Node| { + for i in n.appearance.items.iter_mut() { + if let AppearanceItem::Stroke(s) = i { + s.join = if s.join == LineJoin::Round { LineJoin::Bevel } else { LineJoin::Round }; + } + } + }; + assert_eq!(after(&mut r, &mut d, id, at, rejoin), 1, "{what}: another join"); + // Back to the first join and moved again: the outline of the join before is not used. + assert_eq!( + after(&mut r, &mut d, id, at, |n| { + rejoin(n); + n.transform(Affine::translate((1.0, 0.0)), true); + }), + 1, + "{what}: the join changed back and moved" + ); + } +} + +#[test] +fn a_small_edit_far_from_the_origin_is_not_taken_for_a_move() { + let far = Affine::translate((1e9, -1e9)); + let was = far * zigzag(20); + let by = Vec2::new(0.25, 3.0); + let moved = Affine::translate(by) * was.clone(); + assert_eq!(offset_between(&was, &moved), Some(moved.elements()[0].end_point().unwrap() - was.elements()[0].end_point().unwrap())); + let mut els = moved.elements().to_vec(); + if let Some(kurbo::PathEl::LineTo(p)) = els.get_mut(2) { + p.y += 0.0005; + } + assert_eq!(offset_between(&was, &BezPath::from_vec(els)), None, "an anchor moved by 0.0005 pt"); +} + +#[test] +fn a_path_moved_out_of_the_region_its_outline_was_cropped_to_is_outlined_again() { + let (mut d, id) = doc(&zigzag(3000), vec![AppearanceItem::Stroke(stroke(6.0, LineJoin::Miter, LineCap::Square))]); + let at = Point::new(12_000.0, 15.0); + let mut r = Renderer::new(); + render(&mut r, &d, at); + assert!(r.strokes.values().any(|e| e.crop.is_some()), "outlined near the view"); + // The outline reaches the view's size past each side of it: 200 pt. + assert_eq!(after(&mut r, &mut d, id, at, |n| n.transform(Affine::translate((150.0, 0.0)), true)), 0, "moved within the region"); + assert_eq!(after(&mut r, &mut d, id, at, |n| n.transform(Affine::translate((150.0, 0.0)), true)), 1, "moved past it"); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3042e2fd33..2f4453f168 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1268,6 +1268,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With more than 10,000 type on a path objects selected, the Selection and Direct Selection tools neither draw nor hit-test the objects' brackets. The renderer outlines the stroke of a path object with more than 1,024 path elements, without dashes or a width profile, only in and around the view, with a margin of the view's size on each side, and outlines it again when the view moves past that margin. The pixels are the same. At 1600 × 1200, the frame after one anchor of an open path of 200,000 anchors moves takes 28 to 30 ms instead of 103 ms, and with a closed path of 50,000 anchors 10 ms instead of 30 ms (`cargo run --release -p vectorcraft-engine --example anchor_bench`). The renderer outlines a dashed stroke of such a path the same way, without a width profile, and draws its dashes and dots in the same places as when the whole path is dashed, so the pixels are the same. A pattern too fine to draw is drawn solid, as before, and its stroke is outlined near the view too. At 1600 × 1200, the frame after one anchor moves takes 14 ms instead of 102 ms with a filled closed path of 50,000 anchors and a stroke of 6 pt dashes and 4 pt gaps (`cargo run --release -p vectorcraft-engine --example anchor_bench`, which now includes that document). + When a path object moves without changing shape, the renderer draws its stroke from the outline it made before the move, moved by the same offset. It outlines the stroke again when the path is scaled, rotated or edited, when the stroke changes, and when the move takes the view past the part of a long path it outlined. The pixels are the same. At 1600 × 1200, the frame after a 1 pt nudge takes 128 ms instead of 405 ms with an open path of 200,000 anchors in view (104 ms with nothing changed), and 14 ms instead of 28 ms with a closed path of 50,000 anchors whose stroke is dashed and has a width profile. The renderer keeps the path of a path or compound path of 1,024 anchors or more by object, with the bounds of its segments and of its miter spikes in runs of 128 segments. When anchors move and the subpaths and anchor counts stay the same, the next frame changes only the segments that start or end at a moved anchor and measures again only the runs that hold them or the segments with length before them, instead of making the whole path again and measuring it whole for culling. The pixels and the cull bounds are the same. On Windows at 1600 × 1200, the frame after one anchor moves takes 8.2 ms instead of 30.1 ms with an open path of 200,000 anchors, 4.3 ms instead of 10.4 ms with a closed path of 50,000 anchors, and 6.6 ms instead of 11.9 ms with the filled closed path of 50,000 anchors and a dashed stroke (medians of five runs of `anchor_bench`). Type › Show Hidden Characters keeps the marks it places on each text object from one frame to the next. The canvas lays a text object out again when an edit changes it or its threaded story, or when the last frame that showed the marks did not draw it, and it lays out all type in view again when the fonts or the hyphenation exceptions change. With 1,000 two-line labels in view, drawing the marks takes 0.8 ms per frame in a release build instead of 19.7 ms. A selection with more than 100,000 points to outline shows its bounds instead of each object's outline and anchors. Paths count their anchors. Area type and type on a path count the anchors of their frame or path, and point type counts six: its box's corners and the ends of its baseline marker. Images, symbol instances, placed documents, and area type or type on a path in perspective count the four corners of their box, and gradient meshes and envelopes count their points and the ends of their mesh lines. The hover highlight leaves out an object past that count, and such an object shows its bounds as the key object. With 32,768 type objects, images, symbol instances, gradient meshes or envelopes selected, the selection's outlines and anchors add fewer than 100 vertices to the canvas's mesh (#2460). From a4e74ed0f0fedfe81bf1ddab76e31d838b5dac7d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 16:07:11 -0800 Subject: [PATCH 014/196] Render: stroke outline reuse leaves the shared imports and the dashed-outline branch as they were The moved-outline key is imported where it is used, and the outline is stored through one helper, so the change touches fewer lines that other work on the renderer also changes. --- crates/render/src/lib.rs | 8 ++--- crates/render/src/renderer.rs | 9 ++++-- crates/render/src/renderer/paint.rs | 47 +++++++++++++++-------------- 3 files changed, 33 insertions(+), 31 deletions(-) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index cace4f1655..b9852d0a19 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -75,8 +75,8 @@ pub struct Renderer { /// tolerance level): panning re-renders reuse them instead of re-expanding every stroke. strokes: PtrMap, /// The key in `strokes` of the latest outline of each stroke of an object, under its - /// [`MovedKey`]: a moved copy of the object draws that outline moved ([`Self::moved_outline`]). - moved_strokes: PtrMap, + /// [`frame::MovedKey`]: a moved copy of the object draws that outline moved ([`Self::moved_outline`]). + moved_strokes: PtrMap, /// Expanded character stroke outlines, with the glyph geometry kept in `texts` they belong to, /// keyed by ([`Self::stroke_owner`] of that geometry, run, width bits, tolerance level): type /// that doesn't change draws them again instead of expanding its strokes in every frame. Within @@ -218,9 +218,7 @@ mod threads; pub use bounds::{drawn_bounds, drawn_outline, effect_bounds, painted_bounds}; pub use frame::FrameStats; -use frame::{ - ClipEntry, ClipPaintEntry, Frame, FxArtEntry, GeomEntry, MovedKey, PlacedEntry, PlacedKey, PtrHasher, PtrMap, SliceEntry, StrokeEntry, StrokeKey, -}; +use frame::{ClipEntry, ClipPaintEntry, Frame, FxArtEntry, GeomEntry, PlacedEntry, PlacedKey, PtrHasher, PtrMap, SliceEntry, StrokeEntry, StrokeKey}; #[cfg(test)] use frame::{OFFSCREEN_PIXELS, Slices}; pub use geometry::region_pixels; diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 638de74e88..534568a14c 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -1,8 +1,8 @@ use super::blobs::{blob_key, blob_pixmap, image_mip, lookup, mask_value, mip_level, plain_image, shape_masked_image, white_shape_mask}; use super::clock::now; use super::frame::{ - ClipEntry, ClipPaintEntry, Frame, FrameStats, GeomEntry, MAX_INLINE_DEPTH, MISSING_INLINE_LOGGED, MovedKey, PlacedEntry, PlacedKey, PtrMap, - SliceEntry, Slices, StrokeEntry, + ClipEntry, ClipPaintEntry, Frame, FrameStats, GeomEntry, MAX_INLINE_DEPTH, MISSING_INLINE_LOGGED, PlacedEntry, PlacedKey, PtrMap, SliceEntry, + Slices, StrokeEntry, }; use super::geometry::{MAX_GUIDE_DASHES, polygon_length, rects_overlap, region_pixels}; use super::node_checks::{ @@ -18,13 +18,16 @@ use super::{ group, ink, kurbo, live, lru, peniko, proof, vello_cpu, }; +#[cfg(test)] +pub(crate) use paint::{STROKES_OUTLINED, offset_between}; + mod images; mod nodes; mod paint; mod text; #[cfg(test)] -pub(crate) use paint::{CROP_STROKES, STROKES_OUTLINED, crop_line, offset_between}; +pub(crate) use paint::{CROP_STROKES, crop_line}; impl Renderer { pub fn new() -> Self { diff --git a/crates/render/src/renderer/paint.rs b/crates/render/src/renderer/paint.rs index 875b39bca1..cf66c50986 100644 --- a/crates/render/src/renderer/paint.rs +++ b/crates/render/src/renderer/paint.rs @@ -1,8 +1,9 @@ use super::{ - Affine, AppearanceItem, Arc, BezPath, BlendMode, Compose, FillRule, Frame, Ink, Mix, MovedKey, Node, Rect, RenderContext, Renderer, Shape, - SliceEntry, Slices, StrokeAlign, StrokeEntry, StrokeLayer, TextGeom, blend_mode, drawable, effects, fill_rule, fx, kurbo, lru, owns_stroke, - peniko, rects_overlap, + Affine, AppearanceItem, Arc, BezPath, BlendMode, Compose, FillRule, Frame, Ink, Mix, Node, Rect, RenderContext, Renderer, Shape, SliceEntry, + Slices, StrokeAlign, StrokeEntry, StrokeLayer, TextGeom, blend_mode, drawable, effects, fill_rule, fx, kurbo, lru, owns_stroke, peniko, + rects_overlap, }; +use crate::frame::{MovedKey, StrokeKey}; use crate::paint; impl Renderer { @@ -277,8 +278,7 @@ impl Renderer { if let Some(mk) = moved && let Some((outline, crop)) = self.moved_outline(mk, &node, st, line, v) { - self.strokes.insert(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop, line: kept }); - self.keep_latest(mk, key); + self.keep_stroke(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop, line: kept }, moved); return Some(outline); } #[cfg(test)] @@ -288,33 +288,34 @@ impl Renderer { // [`crop_line`] otherwise). let region = v.inflate(v.width(), v.height()); let tol = 2f64.powi(level); - let (outline, crop) = if crops() + if crops() && line.elements().len() > CROP_ELEMENTS && st.dash.is_some() && st.profile.is_none() && let Some(outline) = crop_dashed(line, st, width, region, crop_reach(st, width, f.px, tol), tol) { - (Arc::new(outline), Some(region)) - } else { - let cropped = (crops() && line.elements().len() > CROP_ELEMENTS && st.dash.is_none() && st.profile.is_none()) - .then(|| crop_line(line, region, crop_reach(st, width, f.px, tol), width)) - .flatten(); - match cropped { - Some(part) => (Arc::new(effects::stroke::line_outline(&part, st, width, tol)), Some(region)), - None => (expand(), None), - } - }; - self.strokes.insert(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop, line: kept }); - if let Some(mk) = moved { - self.keep_latest(mk, key); + let outline = Arc::new(outline); + self.keep_stroke(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop: Some(region), line: kept }, moved); + return Some(outline); } + let cropped = (crops() && line.elements().len() > CROP_ELEMENTS && st.dash.is_none() && st.profile.is_none()) + .then(|| crop_line(line, region, crop_reach(st, width, f.px, tol), width)) + .flatten(); + let (outline, crop) = match cropped { + Some(part) => (Arc::new(effects::stroke::line_outline(&part, st, width, tol)), Some(region)), + None => (expand(), None), + }; + self.keep_stroke(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop, line: kept }, moved); Some(outline) } - /// Lists `key` as the latest outline under `mk`, and drops the line kept with the outline listed - /// there before, which no moved copy draws from any more: one line is kept per [`MovedKey`]. - fn keep_latest(&mut self, mk: MovedKey, key: crate::frame::StrokeKey) { - if let Some(before) = self.moved_strokes.insert(mk, key) + /// Keeps outline `e` in `strokes` under `key`, and lists `key` as the latest outline under + /// `moved` ([`MovedKey`]), dropping the line kept with the outline listed there before, which + /// no moved copy draws from any more: one line is kept per [`MovedKey`]. + fn keep_stroke(&mut self, key: StrokeKey, e: StrokeEntry, moved: Option) { + self.strokes.insert(key, e); + if let Some(mk) = moved + && let Some(before) = self.moved_strokes.insert(mk, key) && before != key && let Some(e) = self.strokes.get_mut(&before) { From e71daf48cc677957acc99e1a25d4c6fdf5c4a9c1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 16:30:41 -0800 Subject: [PATCH 015/196] Tests: a sheared path or another stroke style outlines the stroke again A shear, a wider stroke, another cap, another dash pattern and another width profile each make one new outline and draw the pixels a new renderer draws, for open and closed, short and long, plain, dashed, profiled and gradient-filled paths. --- crates/render/src/tests/movedstroke.rs | 55 ++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/crates/render/src/tests/movedstroke.rs b/crates/render/src/tests/movedstroke.rs index 67b7de9055..bbea335558 100644 --- a/crates/render/src/tests/movedstroke.rs +++ b/crates/render/src/tests/movedstroke.rs @@ -179,6 +179,61 @@ fn a_path_changed_otherwise_outlines_its_stroke_again() { } } +/// Checks that each case, drawn once and then changed by `change` (given the point the view is +/// centered on), is drawn with one new outline and the pixels of a new renderer. +fn outlined_again(change: impl Fn(&mut Node, Point)) { + for (what, (mut d, id), at) in cases() { + let mut r = Renderer::new(); + render(&mut r, &d, at); + assert_eq!(after(&mut r, &mut d, id, at, |n| change(n, at)), 1, "{what}"); + } +} + +/// Applies `change` to every stroke of `n`. +fn restroke(n: &mut Node, change: impl Fn(&mut StrokeLayer)) { + for i in n.appearance.items.iter_mut() { + if let AppearanceItem::Stroke(s) = i { + change(s); + } + } +} + +#[test] +fn a_sheared_path_outlines_its_stroke_again() { + // Sheared about the view's center, stroke weights kept. + outlined_again(|n, at| n.transform(Affine::translate(at.to_vec2()) * Affine::skew(0.001, 0.0) * Affine::translate(-at.to_vec2()), false)); +} + +#[test] +fn another_stroke_width_outlines_the_stroke_again() { + outlined_again(|n, _| restroke(n, |s| s.width += 1.0)); +} + +#[test] +fn another_cap_outlines_the_stroke_again() { + outlined_again(|n, _| restroke(n, |s| s.cap = if s.cap == LineCap::Round { LineCap::Butt } else { LineCap::Round })); +} + +#[test] +fn another_dash_pattern_outlines_the_stroke_again() { + outlined_again(|n, _| { + restroke(n, |s| match &mut s.dash { + Some(d) => d.pattern[0] += 4.0, + None => s.dash = Some(Dash { pattern: vec![9.0, 5.0], offset: 0.0, align_corners: false }), + }) + }); +} + +#[test] +fn another_width_profile_outlines_the_stroke_again() { + outlined_again(|n, _| { + restroke(n, |s| match &mut s.profile { + Some(p) => p.points[1].1 = 0.5, + None => s.profile = Some(WidthProfile { points: vec![(0.0, 1.0, 1.0), (1.0, 0.25, 0.25)] }), + }) + }); +} + #[test] fn a_small_edit_far_from_the_origin_is_not_taken_for_a_move() { let far = Affine::translate((1e9, -1e9)); From 413fe034f0d8ca7796202b5e6ef67e9923b87c9c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 18:05:53 -0800 Subject: [PATCH 016/196] Render: a moved path's stroke is matched by its anchors, without a copy of its line The outline cache kept a copy of each stroke's line to recognize a moved path, and made that copy on every miss, so an anchor edit of a long path paid for copying its whole line. The entry now records whether its outline was made along a line of the object's own path. On a miss, the anchors of the earlier object are compared with the new one's, stopping at the first that differs, and the earlier line is made again from the object and its stroke only when they match. Strokes with arrowheads keep the reuse: the check uses the untrimmed path. --- crates/render/src/frame.rs | 7 +- crates/render/src/renderer/paint.rs | 107 ++++++++++++++++++------- crates/render/src/tests/movedstroke.rs | 14 +++- 3 files changed, 92 insertions(+), 36 deletions(-) diff --git a/crates/render/src/frame.rs b/crates/render/src/frame.rs index 715237b06e..41a53201a2 100644 --- a/crates/render/src/frame.rs +++ b/crates/render/src/frame.rs @@ -37,14 +37,15 @@ pub(crate) type MovedKey = (u64, usize, u64, i32); /// A stroke expanded to a fill outline: (owning node, outline, last frame used, the region a frame /// must lie in to draw the outline, when the outline leaves out the segments far from that region, -/// `None` when it has every segment, and the line the outline was made from, kept when the entry -/// is listed under a [`MovedKey`]). +/// `None` when it has every segment, and whether the outline was made along a line of the node's +/// own path, the one [`Node::stroke_path`] makes, so that the line can be made again from the +/// node and its stroke). pub(crate) struct StrokeEntry { pub(crate) node: Arc, pub(crate) outline: Arc, pub(crate) stamp: u64, pub(crate) crop: Option, - pub(crate) line: Option>, + pub(crate) own: bool, } /// The slices of a stroke whose gradient runs along or across it, each with its paint and bounds. diff --git a/crates/render/src/renderer/paint.rs b/crates/render/src/renderer/paint.rs index cf66c50986..1ed98e8ed2 100644 --- a/crates/render/src/renderer/paint.rs +++ b/crates/render/src/renderer/paint.rs @@ -134,7 +134,7 @@ impl Renderer { } else if paint::set_paint(ctx, &st.paint, paint_bounds, f) { self.fold_alpha(ctx, f.ink, &st.paint); ctx.set_fill_rule(peniko::Fill::NonZero); - match self.cached_stroke(f, chars, &pieces.line, st, width) { + match self.cached_stroke(f, chars, bp, &pieces.line, st, width) { Some(o) => ctx.fill_path(&o), None => ctx.fill_path(&effects::stroke::line_outline(&pieces.line, st, width, f.px * 0.25)), } @@ -210,7 +210,7 @@ impl Renderer { } None => make(), }; - let line = match self.cached_stroke(f, chars, &pieces.line, st, width) { + let line = match self.cached_stroke(f, chars, bp, &pieces.line, st, width) { Some(o) => o, None => Arc::new(effects::stroke::line_outline(&pieces.line, st, width, f.px * 0.25)), }; @@ -237,11 +237,12 @@ impl Renderer { /// stroke of `self.cur` in `strokes` (under [`Self::stroke_owner`] and the stroke layer). The /// tolerance (vello's 0.25 device px) is bucketed to powers of two, never coarser than needed, /// so zooming reuses outlines until the level changes. Other strokes aren't cached: for them - /// this returns `None`. + /// this returns `None`. `line` is the line of `st` along `path` ([`effects::stroke::stroke_pieces`]). fn cached_stroke( &mut self, f: &Frame, chars: Option<(&Arc, usize)>, + path: &BezPath, line: &BezPath, st: &StrokeLayer, width: f64, @@ -274,11 +275,11 @@ impl Renderer { // of the stroke's latest outline is kept, except for art made again in every frame. let place = node.appearance.items.iter().position(|i| matches!(i, AppearanceItem::Stroke(s) if std::ptr::eq(s, st))); let moved = place.filter(|_| !self.made_again).map(|place| (node.id.0, place, width.to_bits(), level)); - let kept = moved.map(|_| Arc::new(line.clone())); + let own = moved.is_some() && self.own_path(&node, path); if let Some(mk) = moved && let Some((outline, crop)) = self.moved_outline(mk, &node, st, line, v) { - self.keep_stroke(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop, line: kept }, moved); + self.keep_stroke(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop, own }, moved); return Some(outline); } #[cfg(test)] @@ -295,7 +296,7 @@ impl Renderer { && let Some(outline) = crop_dashed(line, st, width, region, crop_reach(st, width, f.px, tol), tol) { let outline = Arc::new(outline); - self.keep_stroke(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop: Some(region), line: kept }, moved); + self.keep_stroke(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop: Some(region), own }, moved); return Some(outline); } let cropped = (crops() && line.elements().len() > CROP_ELEMENTS && st.dash.is_none() && st.profile.is_none()) @@ -305,33 +306,38 @@ impl Renderer { Some(part) => (Arc::new(effects::stroke::line_outline(&part, st, width, tol)), Some(region)), None => (expand(), None), }; - self.keep_stroke(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop, line: kept }, moved); + self.keep_stroke(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop, own }, moved); Some(outline) } + /// Whether `path` is the path that `geom` keeps for `node` ([`Self::path_of`]), the path + /// [`Node::stroke_path`] makes from its anchors. + fn own_path(&self, node: &Arc, path: &BezPath) -> bool { + self.geom + .get(&(Arc::as_ptr(node) as usize)) + .is_some_and(|g| Arc::ptr_eq(&g.node, node) && g.path.as_deref().is_some_and(|p| std::ptr::eq(p, path))) + } + /// Keeps outline `e` in `strokes` under `key`, and lists `key` as the latest outline under - /// `moved` ([`MovedKey`]), dropping the line kept with the outline listed there before, which - /// no moved copy draws from any more: one line is kept per [`MovedKey`]. + /// `moved` ([`MovedKey`]). fn keep_stroke(&mut self, key: StrokeKey, e: StrokeEntry, moved: Option) { self.strokes.insert(key, e); - if let Some(mk) = moved - && let Some(before) = self.moved_strokes.insert(mk, key) - && before != key - && let Some(e) = self.strokes.get_mut(&before) - { - e.line = None; + if let Some(mk) = moved { + self.moved_strokes.insert(mk, key); } } /// The outline of stroke `st` of `node` along `line`, made from the latest outline kept under - /// `mk` ([`MovedKey`]) when that outline's object is `node` changed, its stroke differs from `st` - /// in its paint at most, and its line is `line` moved (to within rounding): that outline moved - /// by the same offset, with the region it was cropped to moved too. `None` when there is no - /// such outline, or when its region does not hold the view `v`. + /// `mk` ([`MovedKey`]) when that outline was made along a line of its object's own path, its + /// object is `node` changed, its stroke differs from `st` in its paint at most, and its line is + /// `line` moved (to within rounding): that outline moved by the same offset, with the region it + /// was cropped to moved too. The anchors of the two objects are compared first + /// ([`anchors_moved`]), and the earlier line is made again from its object and stroke only when + /// they match. `None` when there is no such outline, or when its region does not hold the view + /// `v`. fn moved_outline(&self, mk: MovedKey, node: &Node, st: &StrokeLayer, line: &BezPath, v: Rect) -> Option<(Arc, Option)> { let e = self.strokes.get(self.moved_strokes.get(&mk)?)?; - let was = e.line.as_deref()?; - if e.node.id != node.id { + if !e.own || e.node.id != node.id { return None; } let Some(AppearanceItem::Stroke(old)) = e.node.appearance.items.get(mk.1) else { @@ -341,7 +347,11 @@ impl Renderer { if !std::ptr::eq(old, st) && unpainted(old) != unpainted(st) { return None; } - let by = offset_between(was, line)?; + if !anchors_moved(&e.node, node) { + return None; + } + let path = e.node.stroke_path()?; + let by = offset_between(&effects::stroke::stroke_pieces(&path, old).line, line)?; let crop = e.crop.map(|r| r + by); if crop.is_some_and(|r| r.x0 > v.x0 || r.y0 > v.y0 || r.x1 < v.x1 || r.y1 < v.y1) { return None; @@ -384,16 +394,10 @@ pub(crate) fn offset_between(was: &BezPath, now: &BezPath) -> Option (*b - *a, a.x.abs().max(b.x.abs()).max(a.y.abs()).max(b.y.abs())), + (PathEl::MoveTo(a), PathEl::MoveTo(b)) => first_offset(*a, *b)?, _ => return None, }; - if !by.is_finite() { - return None; - } - let near = |a: &kurbo::Point, b: &kurbo::Point| { - let close = |a: f64, by: f64, b: f64| (a + by - b).abs() <= 4.0 * f64::EPSILON * (a.abs() + b.abs() + first); - close(a.x, by.x, b.x) && close(a.y, by.y, b.y) - }; + let near = |a: &kurbo::Point, b: &kurbo::Point| moved_by(*a, *b, by, first); let moved = was.iter().zip(now).all(|pair| match pair { (PathEl::MoveTo(a), PathEl::MoveTo(b)) | (PathEl::LineTo(a), PathEl::LineTo(b)) => near(a, b), (PathEl::QuadTo(a0, a1), PathEl::QuadTo(b0, b1)) => near(a0, b0) && near(a1, b1), @@ -404,6 +408,49 @@ pub(crate) fn offset_between(was: &BezPath, now: &BezPath) -> Option Option<(kurbo::Vec2, f64)> { + let by = b - a; + by.is_finite().then(|| (by, a.x.abs().max(b.x.abs()).max(a.y.abs()).max(b.y.abs()))) +} + +/// Whether `b` is `a` moved by `by`, each coordinate within a few units in the last place (see +/// [`offset_between`]; `first` from [`first_offset`]). +fn moved_by(a: kurbo::Point, b: kurbo::Point, by: kurbo::Vec2, first: f64) -> bool { + let close = |a: f64, by: f64, b: f64| (a + by - b).abs() <= 4.0 * f64::EPSILON * (a.abs() + b.abs() + first); + close(a.x, by.x, b.x) && close(a.y, by.y, b.y) +} + +/// Whether the anchors and handles of path `now` are those of path `was` moved by one offset, +/// measured as [`offset_between`] measures it, with the same subpaths, anchor counts and closed +/// subpaths. It reads the anchors without making either path ([`Node::stroke_path`]), and stops at +/// the first anchor that differs. `false` for objects other than paths. +fn anchors_moved(was: &Node, now: &Node) -> bool { + let (vectorcraft_doc::NodeKind::Path { path: was, .. }, vectorcraft_doc::NodeKind::Path { path: now, .. }) = (&was.kind, &now.kind) else { + return false; + }; + if was.subpaths.len() != now.subpaths.len() { + return false; + } + let mut offset = None; + for (a, b) in was.subpaths.iter().zip(&now.subpaths) { + if a.closed != b.closed || a.anchors.len() != b.anchors.len() { + return false; + } + for (a, b) in a.anchors.iter().zip(&b.anchors) { + if offset.is_none() { + offset = first_offset(a.p, b.p); + } + let Some((by, first)) = offset else { return false }; + if !(moved_by(a.p, b.p, by, first) && moved_by(a.h_in, b.h_in, by, first) && moved_by(a.h_out, b.h_out, by, first)) { + return false; + } + } + } + true +} + fn crops() -> bool { #[cfg(test)] return CROP_STROKES.with(std::cell::Cell::get); diff --git a/crates/render/src/tests/movedstroke.rs b/crates/render/src/tests/movedstroke.rs index bbea335558..e48c9fefd9 100644 --- a/crates/render/src/tests/movedstroke.rs +++ b/crates/render/src/tests/movedstroke.rs @@ -3,7 +3,7 @@ //! again. use vectorcraft_color::{Color, Gradient, GradientPaint, Paint}; -use vectorcraft_doc::{Appearance, AppearanceItem, Dash, FillLayer, LineCap, LineJoin, Node, NodeId, NodeKind, StrokeLayer, WidthProfile}; +use vectorcraft_doc::{Appearance, AppearanceItem, ArrowAlign, Arrowhead, Dash, FillLayer, LineCap, LineJoin, Node, NodeId, NodeKind, StrokeLayer, WidthProfile}; use vectorcraft_geom::{PathData, Point, Vec2}; use crate::renderer::{STROKES_OUTLINED, offset_between}; @@ -76,12 +76,16 @@ fn ring(n: usize, r: f64) -> BezPath { } /// The documents of the cases: open and closed paths, short and long (outlined near the view), plain, -/// dashed, with a width profile, and filled with a gradient (which a move changes, so the moved +/// dashed, with a width profile, with arrowheads, and filled with a gradient (which a move changes, so the moved /// object has an appearance of its own), each with the point the view is centered on. fn cases() -> Vec<(&'static str, (Document, NodeId), Point)> { let round = stroke(6.0, LineJoin::Round, LineCap::Round); let mut lens = stroke(10.0, LineJoin::Round, LineCap::Butt); lens.profile = Some(WidthProfile { points: vec![(0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 0.0, 0.0)] }); + let mut arrows = stroke(4.0, LineJoin::Miter, LineCap::Butt); + arrows.start_arrow = Some(Arrowhead::Triangle); + arrows.end_arrow = Some(Arrowhead::Circle); + arrows.arrow_align = ArrowAlign::Tip; let gradient = FillLayer::new(Paint::Gradient(Box::new(GradientPaint::new(Gradient::default())))); let only = |st: StrokeLayer| vec![AppearanceItem::Stroke(st)]; vec![ @@ -100,6 +104,9 @@ fn cases() -> Vec<(&'static str, (Document, NodeId), Point)> { Point::new(-5000.0, 0.0), ), ("a long open path, a width profile", doc(&zigzag(3000), only(lens)), Point::new(12_000.0, 15.0)), + // The heads shorten the line, so the line is not the path itself. + ("a short open path, arrowheads", doc(&zigzag(20), only(arrows.clone())), Point::new(70.0, 15.0)), + ("a long open path, arrowheads", doc(&zigzag(3000), only(arrows)), Point::new(40.0, 15.0)), ] } @@ -131,7 +138,6 @@ fn a_moved_path_draws_its_stroke_from_the_outline_made_before() { } }); assert_eq!(made, 0, "{what}, a fill changed: no new outline"); - assert_eq!(r.strokes.values().filter(|e| e.line.is_some()).count(), 1, "{what}: one line kept"); } } @@ -155,6 +161,8 @@ fn a_path_changed_otherwise_outlines_its_stroke_again() { // A move, then an edit of an anchor near the path's start. assert_eq!(after(&mut r, &mut d, id, at, |n| n.transform(Affine::translate((0.5, 0.0)), true)), 0, "{what}: moved"); assert_eq!(after(&mut r, &mut d, id, at, edit_anchor), 1, "{what}: an anchor moved"); + // A move after the edit uses the outline made for the edited path. + assert_eq!(after(&mut r, &mut d, id, at, |n| n.transform(Affine::translate((0.5, 0.0)), true)), 0, "{what}: moved after the edit"); // Scaled and rotated about the view's center, stroke weights kept. assert_eq!(after(&mut r, &mut d, id, at, |n| n.transform(Affine::scale_about(1.001, at), false)), 1, "{what}: scaled"); assert_eq!(after(&mut r, &mut d, id, at, |n| n.transform(Affine::rotate_about(0.001, at), false)), 1, "{what}: rotated"); From 1c0fcd707be31da561d6808d9bdf281d4e523aa7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 19:06:36 -0800 Subject: [PATCH 017/196] Docs: stroke outline reuse timings measured against current main --- docs/target-app-parity.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2f4453f168..a9ea88e4a9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1268,6 +1268,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With more than 10,000 type on a path objects selected, the Selection and Direct Selection tools neither draw nor hit-test the objects' brackets. The renderer outlines the stroke of a path object with more than 1,024 path elements, without dashes or a width profile, only in and around the view, with a margin of the view's size on each side, and outlines it again when the view moves past that margin. The pixels are the same. At 1600 × 1200, the frame after one anchor of an open path of 200,000 anchors moves takes 28 to 30 ms instead of 103 ms, and with a closed path of 50,000 anchors 10 ms instead of 30 ms (`cargo run --release -p vectorcraft-engine --example anchor_bench`). The renderer outlines a dashed stroke of such a path the same way, without a width profile, and draws its dashes and dots in the same places as when the whole path is dashed, so the pixels are the same. A pattern too fine to draw is drawn solid, as before, and its stroke is outlined near the view too. At 1600 × 1200, the frame after one anchor moves takes 14 ms instead of 102 ms with a filled closed path of 50,000 anchors and a stroke of 6 pt dashes and 4 pt gaps (`cargo run --release -p vectorcraft-engine --example anchor_bench`, which now includes that document). + The renderer keeps the path of a path or compound path of 1,024 anchors or more by object, with the bounds of its segments and of its miter spikes in runs of 128 segments. When anchors move and the subpaths and anchor counts stay the same, the next frame changes only the segments that start or end at a moved anchor and measures again only the runs that hold them or the segments with length before them, instead of making the whole path again and measuring it whole for culling. The pixels and the cull bounds are the same. On Windows at 1600 × 1200, the frame after one anchor moves takes 8.2 ms instead of 30.1 ms with an open path of 200,000 anchors, 4.3 ms instead of 10.4 ms with a closed path of 50,000 anchors, and 6.6 ms instead of 11.9 ms with the filled closed path of 50,000 anchors and a dashed stroke (medians of five runs of `anchor_bench`). + When a path object moves without changing shape, the renderer draws its stroke from the outline it made before the move, moved by the same offset. It outlines the stroke again when the path is scaled, rotated or edited, when the stroke changes, and when the move takes the view past the part of a long path it outlined. The pixels are the same. At 1600 × 1200, the frame after a 1 pt nudge takes 123 ms instead of 403 ms with an open path of 200,000 anchors in view (103 ms with nothing changed), and 13 ms instead of 26 ms with a closed path of 50,000 anchors whose stroke is dashed and has a width profile. When a path object moves without changing shape, the renderer draws its stroke from the outline it made before the move, moved by the same offset. It outlines the stroke again when the path is scaled, rotated or edited, when the stroke changes, and when the move takes the view past the part of a long path it outlined. The pixels are the same. At 1600 × 1200, the frame after a 1 pt nudge takes 128 ms instead of 405 ms with an open path of 200,000 anchors in view (104 ms with nothing changed), and 14 ms instead of 28 ms with a closed path of 50,000 anchors whose stroke is dashed and has a width profile. The renderer keeps the path of a path or compound path of 1,024 anchors or more by object, with the bounds of its segments and of its miter spikes in runs of 128 segments. When anchors move and the subpaths and anchor counts stay the same, the next frame changes only the segments that start or end at a moved anchor and measures again only the runs that hold them or the segments with length before them, instead of making the whole path again and measuring it whole for culling. The pixels and the cull bounds are the same. On Windows at 1600 × 1200, the frame after one anchor moves takes 8.2 ms instead of 30.1 ms with an open path of 200,000 anchors, 4.3 ms instead of 10.4 ms with a closed path of 50,000 anchors, and 6.6 ms instead of 11.9 ms with the filled closed path of 50,000 anchors and a dashed stroke (medians of five runs of `anchor_bench`). Type › Show Hidden Characters keeps the marks it places on each text object from one frame to the next. The canvas lays a text object out again when an edit changes it or its threaded story, or when the last frame that showed the marks did not draw it, and it lays out all type in view again when the fonts or the hyphenation exceptions change. With 1,000 two-line labels in view, drawing the marks takes 0.8 ms per frame in a release build instead of 19.7 ms. From 2bb6db5e8f4207c7d0e253bf5b05a1b54e6b00d2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 19:08:24 -0800 Subject: [PATCH 018/196] Tests: movedstroke imports wrapped to the rustfmt width --- crates/render/src/tests/movedstroke.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/render/src/tests/movedstroke.rs b/crates/render/src/tests/movedstroke.rs index e48c9fefd9..99d40cf487 100644 --- a/crates/render/src/tests/movedstroke.rs +++ b/crates/render/src/tests/movedstroke.rs @@ -3,7 +3,9 @@ //! again. use vectorcraft_color::{Color, Gradient, GradientPaint, Paint}; -use vectorcraft_doc::{Appearance, AppearanceItem, ArrowAlign, Arrowhead, Dash, FillLayer, LineCap, LineJoin, Node, NodeId, NodeKind, StrokeLayer, WidthProfile}; +use vectorcraft_doc::{ + Appearance, AppearanceItem, ArrowAlign, Arrowhead, Dash, FillLayer, LineCap, LineJoin, Node, NodeId, NodeKind, StrokeLayer, WidthProfile, +}; use vectorcraft_geom::{PathData, Point, Vec2}; use crate::renderer::{STROKES_OUTLINED, offset_between}; From 7aa759d4de303f1b96f8f7b4c7c35fef050a9df9 Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Wed, 4 Nov 2026 22:10:02 -0500 Subject: [PATCH 019/196] Set Corners: round all, odd-numbered or even-numbered anchors (#5546) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit addon.pathtools.cornerSet takes `every` ("all", "odd" or "even"; default "all"), which keeps, of the anchors already chosen (named, direct-selected or all), only the odd- or even-numbered ones, counted along each path from its first anchor as number 1. Anchors that take no corner still count, so the pattern follows the path's anchor order on open and closed paths; when nothing is left the command says so. Unknown values are refused. Object › Plug-ins › Path Precision Tools › Set Corners… (also a button in the Anchor Inspector's Corners section) opens a dialog with Radius, Corner kind and Anchors (All / Odd-Numbered / Even-Numbered) that previews on the canvas and commits as one undo step. --- .../src/cmd/addons/pathtools/corners.rs | 64 +++++++++-- .../engine/src/cmd/addons/pathtools/tests.rs | 87 +++++++++++++++ crates/engine/tests/command_sweep.rs | 3 + crates/ui-egui/src/addons/pathtools.rs | 4 +- crates/ui-egui/src/addons/pathtools/corner.rs | 7 +- .../src/addons/pathtools/set_corners.rs | 101 ++++++++++++++++++ crates/ui-egui/src/dialogs.rs | 1 + crates/ui-egui/src/menus/invoke.rs | 3 + docs/mcp.md | 7 +- docs/target-app-parity.md | 3 + docs/ui-parity.md | 4 +- 11 files changed, 271 insertions(+), 13 deletions(-) create mode 100644 crates/ui-egui/src/addons/pathtools/set_corners.rs diff --git a/crates/engine/src/cmd/addons/pathtools/corners.rs b/crates/engine/src/cmd/addons/pathtools/corners.rs index 464fa032ba..2da1a5c176 100644 --- a/crates/engine/src/cmd/addons/pathtools/corners.rs +++ b/crates/engine/src/cmd/addons/pathtools/corners.rs @@ -20,7 +20,7 @@ pub(super) fn specs() -> Vec { "Set Corners", [], None, - "{ids?: [id…] (the selection), anchors?: [index…] (of each path's outline with no corners cut; else its direct-selected anchors, or all of them), items?: [{id, anchors?}…] (instead of ids: each path with its own anchors), radius: pt 0..1000000 (drawn no larger than fits), kind?: \"round\"|\"invertedRound\"|\"chamfer\" (each corner's own)} cut live corners at the anchors that can have one, as one undo step → {ids, corners (how many)}", + "{ids?: [id…] (the selection), anchors?: [index…] (of each path's outline with no corners cut; else its direct-selected anchors, or all of them), items?: [{id, anchors?}…] (instead of ids: each path with its own anchors), radius: pt 0..1000000 (drawn no larger than fits), kind?: \"round\"|\"invertedRound\"|\"chamfer\" (each corner's own), every?: \"all\"|\"odd\"|\"even\" (default all: of those anchors, only the odd- or even-numbered ones, counting each path's anchors from 1)} cut live corners at the anchors that can have one, as one undo step → {ids, corners (how many)}", has_doc, corner_set ), @@ -50,8 +50,53 @@ fn anchors_param(p: &Value, cmd: &str) -> Result>> { .map(Some) } -/// The corners a request names: each path with the corners (anchor indices of its uncut outline). -fn named_corners(s: &Session, p: &Value, cmd: &str) -> Result)>> { +/// Which of the chosen anchors `cornerSet` takes, by their number along the path's uncut outline +/// (the first anchor is number 1). +#[derive(Clone, Copy, Debug, PartialEq)] +enum Every { + All, + /// The 1st, 3rd, 5th… anchors: indices 0, 2, 4…. + Odd, + /// The 2nd, 4th, 6th… anchors: indices 1, 3, 5…. + Even, +} + +impl Every { + /// The `every` of `p` (default: all). + fn of(p: &Value, cmd: &str) -> Result { + match p.get("every").filter(|v| !v.is_null()) { + None => Ok(Self::All), + Some(v) => match v.as_str() { + Some("all") => Ok(Self::All), + Some("odd") => Ok(Self::Odd), + Some("even") => Ok(Self::Even), + _ => Err(bad(cmd, format!("`every` must be \"all\", \"odd\" or \"even\", not {v}"))), + }, + } + } + + /// Does it take the anchor at `index`? Anchors that take no corner still count. + fn takes(self, index: usize) -> bool { + match self { + Self::All => true, + Self::Odd => index.is_multiple_of(2), + Self::Even => !index.is_multiple_of(2), + } + } + + /// The error when none of the chosen corners is one it takes. + fn none(self) -> &'static str { + match self { + Self::All => "choose anchors where two sides meet at an angle: only those take a corner", + Self::Odd => "none of the chosen corners is at an odd-numbered anchor (the 1st, 3rd, 5th…)", + Self::Even => "none of the chosen corners is at an even-numbered anchor (the 2nd, 4th, 6th…)", + } + } +} + +/// The corners a request names: each path with the corners (anchor indices of its uncut outline) +/// that `every` takes. +fn named_corners(s: &Session, p: &Value, cmd: &str, every: Every) -> Result)>> { let shared = anchors_param(p, cmd)?; // Each path with its own `anchors`, or sharing the request's. let mut own: Vec>> = vec![]; @@ -71,10 +116,10 @@ fn named_corners(s: &Session, p: &Value, cmd: &str) -> Result = match own.get(i).and_then(Option::as_ref).or(shared.as_ref()) { Some(given) => { let n = lc.base.anchor_count(); if let Some(past) = given.iter().find(|k| **k >= n) { @@ -84,12 +129,14 @@ fn named_corners(s: &Session, p: &Value, cmd: &str) -> Result st.selection.partial(*id).filter(|a| !a.is_empty()).map_or_else(|| lc.all(), |a| lc.corners_of(a)), }; + chosen |= !corners.is_empty(); + let corners: BTreeSet = corners.into_iter().filter(|k| every.takes(*k)).collect(); if !corners.is_empty() { out.push((*id, corners)); } } if out.is_empty() { - return Err(bad(cmd, "choose anchors where two sides meet at an angle: only those take a corner")); + return Err(bad(cmd, if chosen { every.none() } else { Every::All.none() })); } Ok(out) } @@ -134,11 +181,12 @@ fn corner_set(s: &mut Session, p: &Value) -> Result { .map_err(|_| bad(C, format!("`kind` must be \"round\", \"invertedRound\" or \"chamfer\", not {v}"))) }) .transpose()?; - let corners = named_corners(s, p, C)?; + let every = Every::of(p, C)?; + let corners = named_corners(s, p, C, every)?; edit_corners(s, "Set Corners", corners, radius, kind) } fn corner_remove(s: &mut Session, p: &Value) -> Result { - let corners = named_corners(s, p, "addon.pathtools.cornerRemove")?; + let corners = named_corners(s, p, "addon.pathtools.cornerRemove", Every::All)?; edit_corners(s, "Remove Corners", corners, 0.0, Some(CornerKind::Round)) } diff --git a/crates/engine/src/cmd/addons/pathtools/tests.rs b/crates/engine/src/cmd/addons/pathtools/tests.rs index 32bcc0c3b3..33e7eff8ea 100644 --- a/crates/engine/src/cmd/addons/pathtools/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tests.rs @@ -567,6 +567,93 @@ fn corner_commands_refuse_bad_params() { } } +/// A closed five-pointed star about (200, 150): its points at the even indices 0, 2… (the odd +/// numbers counting from 1), its inner corners at the odd ones. +fn star_path(s: &mut Session) -> NodeId { + let pts: Vec<(f64, f64)> = (0..10) + .map(|i| { + let (r, a) = (if i % 2 == 0 { 100.0 } else { 40.0 }, std::f64::consts::PI * f64::from(i) / 5.0); + (200.0 + r * a.sin(), 150.0 - r * a.cos()) + }) + .collect(); + line(s, &pts, true) +} + +/// The cut corners of `id`: anchor indices of its uncut outline with a radius drawn. +fn cut(s: &Session, id: NodeId) -> Vec { + let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap(); + (0..lc.base.anchor_count()).filter(|k| lc.drawn_radius(*k) > 0.0).collect() +} + +#[test] +fn corner_set_every_takes_the_odd_or_even_numbered_anchors_of_each_path() { + let mut s = session(); + let star = star_path(&mut s); + // An open zig-zag: its ends (1st and 5th) take no corner but still count. + let zig = line(&mut s, &[(10.0, 250.0), (30.0, 210.0), (50.0, 250.0), (70.0, 210.0), (90.0, 250.0)], false); + select(&mut s, &[star, zig]); + let n = steps(&s); + // Odd: the 1st, 3rd, 5th… of each path, as one step. + let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 4, "every": "odd"})).unwrap(); + assert_eq!((r["corners"].clone(), steps(&s)), (json!(6), n + 1)); + assert_eq!((cut(&s, star), cut(&s, zig)), (vec![0, 2, 4, 6, 8], vec![2])); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((cut(&s, star), cut(&s, zig), steps(&s)), (vec![], vec![], n)); + // Even: the 2nd, 4th, 6th…. + let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 4, "every": "even"})).unwrap(); + assert_eq!((r["corners"].clone(), steps(&s)), (json!(7), n + 1)); + assert_eq!((cut(&s, star), cut(&s, zig)), (vec![1, 3, 5, 7, 9], vec![1, 3])); + // "all" (and no `every`) is every chosen corner, as before. + s.execute("addon.pathtools.cornerSet", &json!({"ids": [zig.0], "radius": 4, "every": "all"})).unwrap(); + assert_eq!(cut(&s, zig), vec![1, 2, 3]); +} + +#[test] +fn corner_set_every_filters_the_named_and_direct_selected_anchors() { + let mut s = session(); + let star = star_path(&mut s); + // Of the named anchors, only the even-numbered ones (indices 1 and 3); numbers stay the path's. + let r = s.execute("addon.pathtools.cornerSet", &json!({"ids": [star.0], "anchors": [1, 2, 3, 4], "radius": 3, "every": "even"})).unwrap(); + assert_eq!(r["corners"], json!(2)); + assert_eq!(cut(&s, star), vec![1, 3]); + // Per path through `items`. + s.execute("addon.pathtools.cornerSet", &json!({"items": [{"id": star.0, "anchors": [5, 6, 7]}], "radius": 3, "every": "odd"})).unwrap(); + assert_eq!(cut(&s, star), vec![1, 3, 6]); + // Of the direct-selected anchors. + s.execute("addon.pathtools.cornerRemove", &json!({"ids": [star.0]})).unwrap(); + select_anchors(&mut s, star, &[7, 8, 9]); + s.execute("addon.pathtools.cornerSet", &json!({"radius": 3, "every": "odd"})).unwrap(); + assert_eq!(cut(&s, star), vec![8]); +} + +#[test] +fn corner_set_every_refuses_bad_values_and_says_when_nothing_is_left() { + let mut s = session(); + let zig = line(&mut s, &[(10.0, 250.0), (30.0, 210.0), (50.0, 250.0), (70.0, 210.0)], false); + select(&mut s, &[zig]); + let i = zig.0; + refuses( + &mut s, + "addon.pathtools.cornerSet", + &[ + json!({"ids": [i], "radius": 5, "every": "third"}), + json!({"ids": [i], "radius": 5, "every": "Odd"}), + json!({"ids": [i], "radius": 5, "every": 2}), + json!({"ids": [i], "radius": 5, "every": true}), + json!({"ids": [i], "anchors": [1], "radius": 5, "every": "odd"}), + json!({"ids": [i], "anchors": [0, 1], "radius": 5, "every": "odd"}), + ], + ); + let e = s.execute("addon.pathtools.cornerSet", &json!({"ids": [i], "radius": 5, "every": "third"})).unwrap_err().to_string(); + assert!(e.contains("`every` must be \"all\", \"odd\" or \"even\""), "{e}"); + // The 2nd anchor is a corner, but not an odd-numbered one. + let e = s.execute("addon.pathtools.cornerSet", &json!({"ids": [i], "anchors": [1], "radius": 5, "every": "odd"})).unwrap_err().to_string(); + assert!(e.contains("odd-numbered"), "{e}"); + // An open end is no corner at all, whatever `every` says. + let e = s.execute("addon.pathtools.cornerSet", &json!({"ids": [i], "anchors": [0], "radius": 5, "every": "odd"})).unwrap_err().to_string(); + assert!(e.contains("two sides meet"), "{e}"); +} + #[test] fn the_corner_tool_clicks_drags_and_removes_in_one_step_each() { let mut s = session(); diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 3010901ca7..8d973f267d 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -593,6 +593,9 @@ fn structured_junk() { ("addon.pathtools.cornerSet", json!({"items": [1, null, {"anchors": "x"}], "radius": 1})), ("addon.pathtools.cornerSet", json!({"ids": [2], "radius": 1e308, "kind": "spiky"})), ("addon.pathtools.cornerSet", json!({"items": "all", "radius": f64::NAN, "anchors": [-1, 1.5, "x"]})), + ("addon.pathtools.cornerSet", json!({"ids": [2, 3], "radius": 5, "every": "odd"})), + ("addon.pathtools.cornerSet", json!({"items": [{"id": 2, "anchors": [1, u64::MAX]}], "radius": 5, "every": "even"})), + ("addon.pathtools.cornerSet", json!({"ids": [2], "radius": 5, "every": [1, "x", null]})), ("addon.pathtools.cornerRemove", json!({"ids": [0, 1, 2, 3, u64::MAX]})), ("addon.pathtools.cornerRemove", json!({"items": [{"id": 2, "anchors": [u64::MAX]}]})), ("addon.pathtools.slideAnchor", json!({"id": 2, "anchor": 1, "t": 0.98})), diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 2e5306677b..f59984ccdc 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -1,5 +1,5 @@ //! Path Precision Tools in the interface: its submenu (Object › Plug-ins › Path Precision Tools), -//! which selects its tools, opens its panels and runs Split / Add Points at Crossings, Divide into +//! which selects its tools, opens its panels and runs Split / Add Points at Crossings, Set Corners… ([`set_corners`]), Divide into //! Dashes ([`dashes`]), Expand Dashes into Paths and Convert to Parametric Shape; the Anchor Inspector panel (the selected //! anchor's position and handles as numbers, the add-on's anchor edits, the Corner Tool's values, //! [`corner`], and the Shared Edge Merge Tool's, [`shared_edge`]); the Parametric Shape panel @@ -8,6 +8,7 @@ pub mod corner; pub mod dashes; +pub mod set_corners; pub mod shape; pub mod shared_edge; @@ -56,6 +57,7 @@ pub fn menu() -> Vec { tool("Measure & Inspect Tool", measure_inspect::ID), tool("Parametric Shape Tool", parametric_shape::ID), Item::Cmd("Corner Tool", corner::COMMAND, json!({})), + Item::Cmd("Set Corners…", set_corners::COMMAND, Value::Null), tool("Slide Anchor Along Path", slide_anchor::ID), Item::Cmd("Shared Edge Merge Tool", shared_edge::COMMAND, json!({})), Item::Sep, diff --git a/crates/ui-egui/src/addons/pathtools/corner.rs b/crates/ui-egui/src/addons/pathtools/corner.rs index dce1363359..358e4f0b3d 100644 --- a/crates/ui-egui/src/addons/pathtools/corner.rs +++ b/crates/ui-egui/src/addons/pathtools/corner.rs @@ -1,5 +1,6 @@ //! The Anchor Inspector panel's Corners section: the Corner Tool's radius and kind, how many corners -//! the selection holds, and Apply (`addon.pathtools.cornerSet`). +//! the selection holds, Apply (`addon.pathtools.cornerSet`) and Set Corners… (its dialog, which +//! can also take every other anchor). use egui::Ui; use serde_json::{Value, json}; @@ -55,10 +56,14 @@ pub(super) fn section(app: &mut VectorcraftApp, ui: &mut Ui) { }); let width = ui.available_width(); let apply = ui.add_enabled_ui(count > 0, |ui| widgets::flat_button(ui, tl!("Apply to Selected Anchors"), width).clicked()).inner; + let dialog = ui.add_enabled_ui(count > 0, |ui| widgets::flat_button(ui, tl!("Set Corners…"), width).clicked()).inner; if let Some(values) = set { run(app, "tool.setOption", json!({ "tool": ID, "values": values })); } if apply { run(app, "addon.pathtools.cornerSet", json!({ "radius": radius, "kind": kind })); } + if dialog { + crate::menus::invoke(app, super::set_corners::COMMAND, json!({})); + } } diff --git a/crates/ui-egui/src/addons/pathtools/set_corners.rs b/crates/ui-egui/src/addons/pathtools/set_corners.rs new file mode 100644 index 0000000000..52800fed6b --- /dev/null +++ b/crates/ui-egui/src/addons/pathtools/set_corners.rs @@ -0,0 +1,101 @@ +//! Set Corners in the interface: its dialog (radius, corner kind, and which anchors: all, the +//! odd-numbered or the even-numbered ones), which previews on the canvas and runs +//! `addon.pathtools.cornerSet` on OK, one undo step. It opens on the Corner Tool's radius and kind. + +use egui::Ui; +use serde_json::{Value, json}; +use vectorcraft_tools::addons::corner_tool::{ID, MAX_RADIUS, RADIUS}; + +use crate::VectorcraftApp; +use crate::dialogs::{DialogSpec, form}; +use crate::state::Dialog; +use crate::widgets; + +/// The command, and its dialog's kind. +pub const COMMAND: &str = "addon.pathtools.cornerSet"; +pub const KIND: &str = "setCorners"; +/// The corner kinds, as the command names them, and their labels. +const KINDS: [(&str, &str); 3] = [("round", "Round"), ("invertedRound", "Inverted Round"), ("chamfer", "Chamfer")]; +/// Which anchors, as the command's `every` names them, and their labels. +const EVERY: [(&str, &str); 3] = [("all", "All Anchors"), ("odd", "Odd-Numbered Anchors"), ("even", "Even-Numbered Anchors")]; +const LABEL_W: f32 = 64.0; +const FIELD_W: f32 = 170.0; + +/// The dialog's fields to start with: the Corner Tool's radius and kind, every anchor, Preview on. +pub(crate) fn fields(app: &VectorcraftApp) -> Value { + let options = app.session.tool_options_of(ID); + let radius = options["radius"].as_f64().unwrap_or(RADIUS); + let kind = options["kind"].as_str().unwrap_or("round").to_string(); + json!({ "radius": radius, "kind": kind, "every": "all", "preview": true }) +} + +pub(crate) const SPEC: DialogSpec = + DialogSpec { heading: |_| tl!("Set Corners").to_string(), body, confirm, preview: true, min_width: 280.0, ..DialogSpec::FORM }; + +fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { + let unit = app.session.general_unit(); + widgets::label_row(ui, tl!("Radius:"), LABEL_W, |ui| { + form::length_within(ui, d, "radius", unit, FIELD_W, Some(0.0..=MAX_RADIUS)); + }); + form::choice(ui, d, "kind", tl!("Corner:"), (LABEL_W, FIELD_W), &KINDS); + form::choice(ui, d, "every", tl!("Anchors:"), (LABEL_W, FIELD_W), &EVERY); + form::preview(app, ui, d, "Set Corners", COMMAND, form::params(d)); + false +} + +/// OK: keep the preview (or run the command) and close. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + form::commit_preview(app, COMMAND, form::params(d)) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + use vectorcraft_doc::{LiveCorners, NodeId}; + use vectorcraft_engine::Session; + + use crate::tests_labels::painted_text; + use crate::{VectorcraftApp, menus}; + + /// The anchor indices of `id`'s uncut outline with a corner drawn. + fn cut(app: &VectorcraftApp, id: u64) -> Vec { + let doc = &app.session.doc().unwrap().doc; + let lc = LiveCorners::of(doc.node(NodeId(id)).unwrap()).unwrap(); + (0..lc.base.anchor_count()).filter(|k| lc.drawn_radius(*k) > 0.0).collect() + } + + #[test] + fn set_corners_opens_from_the_menu_previews_odd_anchors_and_commits_one_step() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let anchors = json!([{"x": 0, "y": 0}, {"x": 100, "y": 0}, {"x": 100, "y": 100}, {"x": 0, "y": 100}, {"x": -50, "y": 50}]); + let id = app.run("path.create", json!({"anchors": anchors, "closed": true})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let entries = menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Path Precision Tools"] && e.label == "Set Corners…").unwrap(); + let (cmd, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + menus::invoke(&mut app, &cmd, p); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(super::KIND)); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in ["Set Corners", "Radius:", "Corner:", "Anchors:", "All Anchors", "Preview"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + assert_eq!(cut(&app, id), vec![0, 1, 2, 3, 4], "all previewed"); + let n = app.session.doc().unwrap().history.undo.len(); + app.ui.dialog.as_mut().unwrap().fields.insert("every".into(), json!("odd")); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert!(shown.contains("Odd-Numbered Anchors"), "{shown}"); + assert_eq!(cut(&app, id), vec![0, 2, 4], "odd previewed"); + crate::dialogs::cancel(&mut app); + assert_eq!(cut(&app, id), Vec::::new(), "rolled back"); + menus::invoke(&mut app, &cmd, serde_json::Value::Null); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("every".into(), json!("even")); + d.fields.insert("radius".into(), json!(6)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.doc().unwrap().history.undo.len(), n + 1); + assert_eq!(cut(&app, id), vec![1, 3]); + } +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 3373ebf9ce..2a90425c1f 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -417,6 +417,7 @@ registry! { RearrangeArtboards: [rearrange_artboards::KIND] => rearrange_artboards::SPEC, PathToolOptions: [crate::addons::pathtools::KIND] => crate::addons::pathtools::OPTIONS_SPEC, DivideDashes: [crate::addons::pathtools::dashes::KIND] => crate::addons::pathtools::dashes::SPEC, + SetCorners: [crate::addons::pathtools::set_corners::KIND] => crate::addons::pathtools::set_corners::SPEC, NearestSwatch: [crate::addons::color::nearest::KIND] => crate::addons::color::nearest::SPEC, SwatchLegend: [crate::addons::color::legend::KIND] => crate::addons::color::legend::SPEC, TextTweaker: [crate::addons::typetools::KIND] => crate::addons::typetools::SPEC, diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 18e77b792e..963eab802f 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -68,6 +68,9 @@ pub(super) fn menu_dialog(app: &VectorcraftApp, id: &str) -> Option<(&'static st ("splitIntoGrid", crate::dialogs::path_ops::split_fields(size.0, size.1)) } "object.vectorHalftone" => (crate::dialogs::halftone::KIND, crate::dialogs::halftone::fields()), + crate::addons::pathtools::set_corners::COMMAND => { + (crate::addons::pathtools::set_corners::KIND, crate::addons::pathtools::set_corners::fields(app)) + } crate::addons::pathtools::dashes::COMMAND => (crate::addons::pathtools::dashes::KIND, crate::addons::pathtools::dashes::fields()), crate::addons::color::nearest::COMMAND => (crate::addons::color::nearest::KIND, crate::addons::color::nearest::fields()), crate::addons::color::legend::COMMAND => (crate::addons::color::legend::KIND, crate::addons::color::legend::fields()), diff --git a/docs/mcp.md b/docs/mcp.md index 30a7da8e62..c4506fc83d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6627,13 +6627,16 @@ Commands: drawn, and the path's fills stay on it, below its dashes (a path without fills goes). A compound path's dashes are plain paths with its appearance. Paths without a dashed stroke stay as they are, and it is an error if none has one. The dashes are selected; more than 100,000 (or a pattern too fine to draw) is refused. → `{ids, dashes}`. -- `addon.pathtools.cornerSet {ids?, anchors?, items?, radius, kind?}` cuts live corners, the ones Direct Selection's +- `addon.pathtools.cornerSet {ids?, anchors?, items?, radius, kind?, every?}` cuts live corners, the ones Direct Selection's corner widgets and the Corners dialog edit, as one undo step. `ids` (default: the selection) are the paths and `anchors` the anchor indices of each path's outline with no corners cut; without `anchors`, a path's direct-selected anchors, or all of them. `items: [{id, anchors?}…]` gives each path its own instead. Only anchors where two sides meet at an angle take a corner: smooth anchors and open ends are skipped, and it is an error if none is left. `radius` is 0 to 1,000,000 pt, drawn no larger than fits; `kind` is `round`, `invertedRound` or `chamfer` (default: each corner's - own). → `{ids, corners}`. + own). `every` (`all`, `odd` or `even`; default `all`) keeps, of those anchors, only the odd- or even-numbered ones, + counting each path's anchors from 1 (the 1st, 3rd, 5th… are odd): an anchor that takes no corner still counts, and it + is an error if none is left. Object › Plug-ins › Path Precision Tools › Set Corners… (also in the Anchor Inspector's + Corners section) sets these with Preview. → `{ids, corners}`. - `addon.pathtools.cornerRemove {ids?, anchors?, items?}` makes those corners sharp again, as one undo step; a plain path with none left is plain again. → `{ids, corners}`. - `addon.pathtools.slideAnchor {id, subpath?, anchor, t}` moves an anchor along its path, the segments beside it refitted diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a9ea88e4a9..3763b806a5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -23,6 +23,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | Path Precision Tools add-on (a VectorCraft addition): Set Corners… and `addon.pathtools.cornerSet` `every` round all, the odd-numbered or the even-numbered anchors of each path (#5546); evidence added; scores unchanged. | | 2026-11-04 | minor | Transform Each's Scale has the documented Relative and Absolute radio buttons (`object.transformEach` `relative`: percentages of each object's size, or the width and height it becomes, measured on each object's own bounds) and the link that keeps the two scales in proportion; the panel lists Scale, Move, Rotate, the Options in two columns, the Reference Point and Preview (level with Copy, Cancel and OK) in the documented order. Scores and estimates unchanged. | | 2026-11-05 | minor | PDF import: a DeviceN gradient of a spot ink over process plates keeps the ink and the plates, and PDF export writes it as a DeviceN shading again (#3235); scores unchanged | | 2026-11-05 | minor | Optical kerning moves each pair part of the way toward the font's own stem spacing, with a minimum gap and tighter limits, and leaves ideographs, kana, fullwidth forms and dashes on the font's spacing, so text is no longer squeezed (#5336). Scores and estimates unchanged. | @@ -1473,6 +1474,8 @@ shows an anchor that can take a corner, a click cuts one with the tool's radius drag sizes it (Shift: whole values), a cut corner's marker selects it and loads its values, resizes it, and removes it at 0 or on a double-click, a corner never grows past what fits, and an Alt-marquee cuts every eligible anchor inside. A Corners section in the Anchor Inspector sets the radius and kind, counts the selected corners and applies to them. +Set Corners… (in the submenu and the Corners section) sets the radius and kind with Preview, on all the chosen anchors +or only the odd- or even-numbered ones (`every`, #5546). Slide Anchor Along Path drags an anchor along its curve, the two segments beside it refitted by the keep-shape kernel (Shift: where the tangent is a multiple of 45°). Commands `addon.pathtools.cornerSet`, `cornerRemove` and `slideAnchor`, each one undo step; `vectorcraft_pathops::addons::pathtools::slide_anchor`. Tests: `addons::pathtools` in diff --git a/docs/ui-parity.md b/docs/ui-parity.md index b66aadac0a..c7a988d9f0 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (Artboards panel multi-select with any tool, Fill for every selected artboard; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (Path Precision Tools: Set Corners… rounds every other anchor; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) ## Feature submission evidence @@ -379,6 +379,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Smart Pen add-on (VectorCraft addition): Object › Plug-ins › Smart Pen selects the Smart Pen Tool, which the All Tools drawer lists under its own heading but neither toolbar shows as shipped (no shortcut), and opens the Smart Pen panel (next segment straight or curved; Remove Points Keep Shape, Make Smooth, Make Corner, Retract Handles, Close or Join). The tool draws (click: straight or curved segment, a curve after a straight one tangent; drag: smooth anchor, Alt breaks the handle, Shift 45°, Space moves it; Tab switches a segment; rubber band; close, join, continue) and edits without switching tools (click selects a point, drag moves it, Alt-click removes it keeping the shape, Shift+Alt-click deletes it, double-click toggles smooth/corner; handle drags with Shift and Alt; segment drags reshape, Alt-click adds a point) | done | `addon.pen.*`, `crates/tools/src/addons/smart_pen.rs`, `crates/ui-egui/src/addons/pen.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its seven tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path, Shared Edge Merge Tool), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; the Shared Edge Merge Tool shows, over two paths touching at two coincident anchors, the two stretches and the edge merging them, a click merges them (half way; Shift the upper path, Alt the lower), and near anchors meet or an anchor one path lacks is added to match (Shift+Alt asks for this inside a stretch), with a Shared Edges section in the Anchor Inspector (brush diameter, coincidence 0 to 3 pt, Keep Shared Points Together, which takes coincident anchors along with the add-on's own anchor moves); a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Divide into Dashes… (Dash and Gap in any unit, Fit to Corners and Ends, Remove Gaps; Preview) cuts the selected paths, or only their direct-selected segments, into open pieces along the curve, keeping their appearance, one undo step | done | #4950; `addon.pathtools.divideDashes`, `crates/pathops/src/addons/pathtools/dashes.rs`, `crates/ui-egui/src/addons/pathtools/dashes.rs` and their tests; not a feature of the reference app, so it is not scored | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Set Corners… (also a button in the Anchor Inspector's Corners section: Radius in any unit, Corner kind, Anchors: All, Odd-Numbered or Even-Numbered, counted from each path's first anchor; Preview) cuts corners on the chosen anchors of every selected path, one undo step | done | #5546; `addon.pathtools.cornerSet` (`every`), `crates/ui-egui/src/addons/pathtools/set_corners.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Expand Dashes into Paths turns each selected path's dashed stroke into separate open paths, one per dash, laid out as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off; one undo step | done | #4922; `addon.pathtools.expandDashes` (in `crates/engine/src/cmd/addons/pathtools.rs`, using the renderer's dash layout) and its tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Effect › Path Effects lists its live effects (Dashes to Geometry, Add Anchors, Extend Path, Close Path, Smooth Anchors, Retract Handles, Reverse Direction, Simplify Anchors, Split at Anchors), each with the effect dialog's live Preview except Reverse Direction, which has no options, and listed in the Appearance panel like any effect | done | `addon.path.*`, `crates/effects/src/addons/path.rs`, `crates/ui-egui/src/addons/pathtools.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its four tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/shape.rs` and their tests; not a feature of the reference app, so it is not scored | @@ -432,6 +433,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | Path Precision Tools add-on (a VectorCraft addition): Set Corners… rounds all, the odd-numbered or the even-numbered anchors (#5546); scores and estimates unchanged | | 2026-11-04 | minor | New Document: the units chosen in Preset Details belong to the chosen document, as the pane's options are listed "for the selected preset" ([public source](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/create-and-save-custom-document-presets.html)); the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units (#2078); scores and estimates unchanged | | 2026-11-01 | minor | Object › Image Trace › Batch Trace Folder asks for a source and a destination folder and traces each image into it (#4921); scores and estimates unchanged | | 2026-11-01 | minor | Edit › Copy and Cut take the selected ruler guides, with the objects or alone; pasting puts them on the layer new art goes to, moved as the objects are (alone: where they were), Paste in Place onto the active artboard and Paste on All Artboards onto each (#3226); scores and estimates unchanged | From 95d5c738dce298ef30b41107333cf3aac4551fcb Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 5 Nov 2026 10:42:27 +0700 Subject: [PATCH 020/196] i18n: Set Corners dialog strings in every catalog --- crates/ui-egui/src/i18n/bg.tsv | 4 ++++ crates/ui-egui/src/i18n/bs.tsv | 4 ++++ crates/ui-egui/src/i18n/ca.tsv | 4 ++++ crates/ui-egui/src/i18n/cs.tsv | 4 ++++ crates/ui-egui/src/i18n/da.tsv | 4 ++++ crates/ui-egui/src/i18n/de.tsv | 4 ++++ crates/ui-egui/src/i18n/el.tsv | 4 ++++ crates/ui-egui/src/i18n/es.tsv | 4 ++++ crates/ui-egui/src/i18n/fi.tsv | 4 ++++ crates/ui-egui/src/i18n/fr.tsv | 4 ++++ crates/ui-egui/src/i18n/hu.tsv | 4 ++++ crates/ui-egui/src/i18n/id.tsv | 4 ++++ crates/ui-egui/src/i18n/it.tsv | 4 ++++ crates/ui-egui/src/i18n/ja.tsv | 4 ++++ crates/ui-egui/src/i18n/ka.tsv | 4 ++++ crates/ui-egui/src/i18n/ko.tsv | 4 ++++ crates/ui-egui/src/i18n/nl.tsv | 4 ++++ crates/ui-egui/src/i18n/pl.tsv | 4 ++++ crates/ui-egui/src/i18n/pt-br.tsv | 4 ++++ crates/ui-egui/src/i18n/ru.tsv | 4 ++++ crates/ui-egui/src/i18n/sv.tsv | 4 ++++ crates/ui-egui/src/i18n/tr.tsv | 4 ++++ crates/ui-egui/src/i18n/uk.tsv | 4 ++++ crates/ui-egui/src/i18n/vi.tsv | 4 ++++ crates/ui-egui/src/i18n/zh-hans.tsv | 4 ++++ crates/ui-egui/src/i18n/zh-hant.tsv | 4 ++++ 26 files changed, 104 insertions(+) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 284e70e095..4c43cceb5c 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6197,3 +6197,7 @@ breakText Glyphs Глифи Fully Outside Изцяло извън No artboards match. Няма съвпадащи работни области. Chosen: {n} of {total} Избрани: {n} от {total} + Set Corners… Задаване на ъгли… + All Anchors Всички опорни точки + Odd-Numbered Anchors Нечетни опорни точки + Even-Numbered Anchors Четни опорни точки diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index d6e1bdb8ef..611cc970c1 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6231,3 +6231,7 @@ shape Open Otvoren Fully Outside Potpuno vani No artboards match. Nijedna radna ploča ne odgovara. Chosen: {n} of {total} Odabrano: {n} od {total} + Set Corners… Postavi uglove… + All Anchors Sva sidra + Odd-Numbered Anchors Neparna sidra + Even-Numbered Anchors Parna sidra diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 75b6b4ca3a..3c0158af29 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6332,3 +6332,7 @@ breakText Glyphs Glifs Fully Outside Totalment fora No artboards match. Cap tauler no coincideix. Chosen: {n} of {total} Triats: {n} de {total} + Set Corners… Defineix les cantonades… + All Anchors Tots els ancoratges + Odd-Numbered Anchors Ancoratges senars + Even-Numbered Anchors Ancoratges parells diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 4cb2257256..f19c56d39b 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6346,3 +6346,7 @@ breakText Glyphs Glyfy Fully Outside Zcela vně No artboards match. Žádná pracovní plocha neodpovídá. Chosen: {n} of {total} Zvoleno: {n} z {total} + Set Corners… Nastavit rohy… + All Anchors Všechny kotevní body + Odd-Numbered Anchors Liché kotevní body + Even-Numbered Anchors Sudé kotevní body diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 3388daba92..e4c908156a 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6213,3 +6213,7 @@ breakText Glyphs Glyffer Fully Outside Helt udenfor No artboards match. Ingen tegneflader passer. Chosen: {n} of {total} Valgt: {n} af {total} + Set Corners… Angiv hjørner… + All Anchors Alle ankre + Odd-Numbered Anchors Ulige ankre + Even-Numbered Anchors Lige ankre diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 8010726abf..8e2e67985d 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5932,3 +5932,7 @@ breakText Glyphs Glyphen Fully Outside Vollständig außen No artboards match. Keine Zeichenfläche passt. Chosen: {n} of {total} Gewählt: {n} von {total} + Set Corners… Ecken festlegen… + All Anchors Alle Ankerpunkte + Odd-Numbered Anchors Ungerade Ankerpunkte + Even-Numbered Anchors Gerade Ankerpunkte diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 17f383fb8c..f05becf607 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6298,3 +6298,7 @@ breakText Glyphs Γλύφοι Fully Outside Πλήρως εκτός No artboards match. Κανένας πίνακας σχεδίασης δεν ταιριάζει. Chosen: {n} of {total} Επιλεγμένοι: {n} από {total} + Set Corners… Ορισμός γωνιών… + All Anchors Όλα τα σημεία αγκύρωσης + Odd-Numbered Anchors Μονά σημεία αγκύρωσης + Even-Numbered Anchors Ζυγά σημεία αγκύρωσης diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 29c0d06621..074fccb606 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6288,3 +6288,7 @@ breakText Glyphs Glifos Fully Outside Totalmente fuera No artboards match. Ninguna mesa de trabajo coincide. Chosen: {n} of {total} Elegidas: {n} de {total} + Set Corners… Definir esquinas… + All Anchors Todas las anclas + Odd-Numbered Anchors Anclas impares + Even-Numbered Anchors Anclas pares diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 65f97fab17..9651fdd43a 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6381,3 +6381,7 @@ breakText Glyphs Merkit Fully Outside Kokonaan ulkona No artboards match. Mikään piirtoalusta ei vastaa hakua. Chosen: {n} of {total} Valittu: {n}/{total} + Set Corners… Aseta kulmat… + All Anchors Kaikki ankkurit + Odd-Numbered Anchors Parittomat ankkurit + Even-Numbered Anchors Parilliset ankkurit diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6734fd75ab..2cd0ae07c0 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6341,3 +6341,7 @@ breakText Glyphs Glyphes Fully Outside Entièrement à l’extérieur No artboards match. Aucun plan de travail ne correspond. Chosen: {n} of {total} Choisis : {n} sur {total} + Set Corners… Définir les angles… + All Anchors Tous les points d’ancrage + Odd-Numbered Anchors Points d’ancrage impairs + Even-Numbered Anchors Points d’ancrage pairs diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 8e67cbe935..a30e8e7949 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6330,3 +6330,7 @@ breakText Glyphs Glifák Fully Outside Teljesen kívül No artboards match. Nincs egyező rajztábla. Chosen: {n} of {total} Kiválasztva: {n} / {total} + Set Corners… Sarkok beállítása… + All Anchors Összes horgonypont + Odd-Numbered Anchors Páratlan horgonypontok + Even-Numbered Anchors Páros horgonypontok diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 8fc99dbdf4..678e3fb423 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6213,3 +6213,7 @@ breakText Glyphs Glif Fully Outside Sepenuhnya di luar No artboards match. Tidak ada artboard yang cocok. Chosen: {n} of {total} Dipilih: {n} dari {total} + Set Corners… Atur sudut… + All Anchors Semua jangkar + Odd-Numbered Anchors Jangkar bernomor ganjil + Even-Numbered Anchors Jangkar bernomor genap diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index cddf63e822..9c92dc5e4c 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5966,3 +5966,7 @@ breakText Glyphs Glifi Fully Outside Completamente esterno No artboards match. Nessuna tavola da disegno corrisponde. Chosen: {n} of {total} Scelte: {n} di {total} + Set Corners… Imposta angoli… + All Anchors Tutti gli ancoraggi + Odd-Numbered Anchors Ancoraggi dispari + Even-Numbered Anchors Ancoraggi pari diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 3263faaf57..c0ec9be3e2 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -6031,3 +6031,7 @@ breakText Glyphs 字形 Fully Outside 完全に外側 No artboards match. 一致するアートボードはありません。 Chosen: {n} of {total} 選択中: {n} / {total} + Set Corners… コーナーを設定… + All Anchors すべてのアンカー + Odd-Numbered Anchors 奇数番目のアンカー + Even-Numbered Anchors 偶数番目のアンカー diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 7c73e2f990..a643231056 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6357,3 +6357,7 @@ font-script Japanese იაპონური Fully Outside მთლიანად გარეთ No artboards match. შესაბამისი სამუშაო დაფა არ არის. Chosen: {n} of {total} არჩეულია: {n} / {total} + Set Corners… კუთხეების დაყენება… + All Anchors ყველა საყრდენი წერტილი + Odd-Numbered Anchors კენტი საყრდენი წერტილები + Even-Numbered Anchors ლუწი საყრდენი წერტილები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 04ce6904bf..c31f973b26 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5927,3 +5927,7 @@ breakText Glyphs 글리프 Fully Outside 완전히 바깥쪽 No artboards match. 일치하는 아트보드가 없습니다. Chosen: {n} of {total} 선택됨: {n} / {total} + Set Corners… 모퉁이 설정… + All Anchors 모든 앵커 + Odd-Numbered Anchors 홀수 번째 앵커 + Even-Numbered Anchors 짝수 번째 앵커 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 02004bb0ca..f2a20670ea 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6257,3 +6257,7 @@ breakText Glyphs Glyphs Fully Outside Volledig buiten No artboards match. Geen tekengebied komt overeen. Chosen: {n} of {total} Gekozen: {n} van {total} + Set Corners… Hoeken instellen… + All Anchors Alle ankerpunten + Odd-Numbered Anchors Oneven ankerpunten + Even-Numbered Anchors Even ankerpunten diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 61b2e60ccd..80e3e3f1eb 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -6201,3 +6201,7 @@ breakText Glyphs Glify Fully Outside Całkowicie na zewnątrz No artboards match. Żaden obszar kompozycji nie pasuje. Chosen: {n} of {total} Wybrano: {n} z {total} + Set Corners… Ustaw narożniki… + All Anchors Wszystkie punkty + Odd-Numbered Anchors Punkty nieparzyste + Even-Numbered Anchors Punkty parzyste diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 0221a45e0a..f9c911e855 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6419,3 +6419,7 @@ swatch Yellow Green Verde-amarelado Fully Outside Totalmente fora No artboards match. Nenhuma mesa de trabalho corresponde. Chosen: {n} of {total} Escolhidas: {n} de {total} + Set Corners… Definir Cantos… + All Anchors Todas as Âncoras + Odd-Numbered Anchors Âncoras Ímpares + Even-Numbered Anchors Âncoras Pares diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index bdf6dd16dc..9d80cb092a 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6435,3 +6435,7 @@ shape Open Открытый Fully Outside Полностью снаружи No artboards match. Нет подходящих монтажных областей. Chosen: {n} of {total} Выбрано: {n} из {total} + Set Corners… Задать углы… + All Anchors Все опорные точки + Odd-Numbered Anchors Нечётные опорные точки + Even-Numbered Anchors Чётные опорные точки diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index e488cf3175..8ee422b5c5 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6402,3 +6402,7 @@ digits Hindi Hindi Fully Outside Helt utanför No artboards match. Ingen rityta matchar. Chosen: {n} of {total} Valda: {n} av {total} + Set Corners… Ange hörn… + All Anchors Alla ankare + Odd-Numbered Anchors Udda ankare + Even-Numbered Anchors Jämna ankare diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index a39ca73666..e7d4b3ca1d 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6303,3 +6303,7 @@ breakText Glyphs Glifler Fully Outside Tamamen dışarıda No artboards match. Eşleşen çalışma yüzeyi yok. Chosen: {n} of {total} Seçilen: {n}/{total} + Set Corners… Köşeleri Ayarla… + All Anchors Tüm Çapalar + Odd-Numbered Anchors Tek Numaralı Çapalar + Even-Numbered Anchors Çift Numaralı Çapalar diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 81be50a597..e00c216d59 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5946,3 +5946,7 @@ breakText Glyphs Гліфи Fully Outside Повністю зовні No artboards match. Немає відповідних монтажних областей. Chosen: {n} of {total} Вибрано: {n} з {total} + Set Corners… Задати кути… + All Anchors Усі опорні точки + Odd-Numbered Anchors Непарні опорні точки + Even-Numbered Anchors Парні опорні точки diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 66ad83aea3..f026b728f7 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5947,3 +5947,7 @@ breakText Glyphs Glyph Fully Outside Hoàn toàn bên ngoài No artboards match. Không có bảng vẽ nào khớp. Chosen: {n} of {total} Đã chọn: {n} trên {total} + Set Corners… Đặt góc… + All Anchors Tất cả điểm neo + Odd-Numbered Anchors Điểm neo số lẻ + Even-Numbered Anchors Điểm neo số chẵn diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index d134298ebe..ad37f23cf4 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -6187,3 +6187,7 @@ breakText Glyphs 字形 Fully Outside 完全在外 No artboards match. 没有匹配的画板。 Chosen: {n} of {total} 已选:{n} / {total} + Set Corners… 设置转角… + All Anchors 所有锚点 + Odd-Numbered Anchors 奇数锚点 + Even-Numbered Anchors 偶数锚点 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index b2bbeec797..d4805dd9b7 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5984,3 +5984,7 @@ breakText Glyphs 字符 Fully Outside 完全在外 No artboards match. 沒有符合的工作區域。 Chosen: {n} of {total} 已選:{n} / {total} + Set Corners… 設定轉角… + All Anchors 所有錨點 + Odd-Numbered Anchors 奇數錨點 + Even-Numbered Anchors 偶數錨點 From 3f12cfdbbf1e16f05b1ff562cb3d2a221e0a7a4d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 18:49:43 -0800 Subject: [PATCH 021/196] Control bar: idle frames read the selected object without copying it The Control bar and the contextual task bar copied the first selected object every frame (the task bar twice), which on a path of 200,000 anchors costs about 1.4 ms per copy. Both bars now borrow it; the task bar copies it only when it is a basic shape, for Shape Properties. With one selected open path of 200,000 anchors, an idle frame with both bars shown takes 3.8 ms instead of 8.0 ms in a release build. --- crates/ui-egui/src/canvas/task_bar.rs | 18 ++++++++++-------- crates/ui-egui/src/chrome/control_bar.rs | 7 ++++--- crates/ui-egui/src/tests/place.rs | 23 +++++++++++++++++++++++ docs/target-app-parity.md | 2 ++ 4 files changed, 39 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index e6579d8f31..b5f8dac668 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -48,7 +48,7 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { let Some(b) = (if on_artboards { picked_artboards_bounds(app) } else { app.selection_bounds() }) else { return }; let Some(st) = app.session.active() else { return }; let n = st.selection.len(); - let first = st.selection.objects.first().and_then(|id| st.doc.node(*id)).cloned(); + let first = st.selection.objects.first().and_then(|id| st.doc.node(*id)); let is_group = first.as_ref().is_some_and(|f| matches!(f.kind, NodeKind::Group { .. })); let is_image = first.as_ref().is_some_and(|f| matches!(f.kind, NodeKind::Image(_))); let is_clip_group = first.as_ref().is_some_and(|f| matches!(f.kind, NodeKind::Group { clip: true, .. })); @@ -72,13 +72,15 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { // Selection tool: its properties take the place of Lock, as in the reference app // (). use vectorcraft_doc::LiveShape; - let shape = first.clone().filter(|f| { - n == 1 - && st.selection.anchors.is_empty() - && app.session.tool_id() == "selection" - && matches!(&f.kind, NodeKind::Path { live: Some(l), .. } - if matches!(**l, LiveShape::Rectangle { .. } | LiveShape::Ellipse { .. } | LiveShape::Polygon { .. })) - }); + let shape = first + .filter(|f| { + n == 1 + && st.selection.anchors.is_empty() + && app.session.tool_id() == "selection" + && matches!(&f.kind, NodeKind::Path { live: Some(l), .. } + if matches!(**l, LiveShape::Rectangle { .. } | LiveShape::Ellipse { .. } | LiveShape::Polygon { .. })) + }) + .cloned(); let mut items: Vec<(&str, &str, &str, serde_json::Value)> = vec![]; // (label, icon, command, params) let none = || json!({}); if on_artboards { diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index df58c1be7a..018a4e2d94 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -203,9 +203,9 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let Some(st) = app.session.active() else { return }; let sel = st.selection.objects.clone(); let units = app.session.general_unit(); - let first = sel.first().and_then(|id| st.doc.node(*id)).cloned(); + let first = sel.first().and_then(|id| st.doc.node(*id)); let anchors = anchor_controls(app); - let label = match &first { + let label = match first { _ if app.session.tool_id() == "artboard" => tl!("Artboard"), Some(_) if sel.len() == 1 && anchors != AnchorControls::None => { tl!("Anchor Point") @@ -222,6 +222,7 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { } _ => tl!(crate::panels::appearance::object_label(app)), }; + let has_first = first.is_some(); ui.label(egui::RichText::new(label).font(theme::semibold(12.0)).color(t.text)); // With the Artboard tool in use, the bar shows the active artboard's controls in place // of the object controls. @@ -238,7 +239,7 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { crate::toolbar::control_bar_options(app, ui); crate::dialogs::envelope::control_bar(app, ui); crate::panels::symbols::control_bar(app, ui); - let opacity = if first.is_some() { crate::panels::current_transparency(app).map_or(1.0, |t| t.0) } else { 1.0 }; + let opacity = if has_first { crate::panels::current_transparency(app).map_or(1.0, |t| t.0) } else { 1.0 }; if !image { let shown_stroke = crate::panels::current_stroke(app); let mixed = crate::panels::stroke_mixed(app, ui.ctx()); diff --git a/crates/ui-egui/src/tests/place.rs b/crates/ui-egui/src/tests/place.rs index e4c9d47ef4..9406ba2c97 100644 --- a/crates/ui-egui/src/tests/place.rs +++ b/crates/ui-egui/src/tests/place.rs @@ -488,6 +488,29 @@ fn the_control_bar_shows_the_image_file_link_colour_mode_and_ppi() { assert!(text.contains("Embedded"), "{text}"); } +/// The Control bar's label is read from the first selected object each frame, so it follows an +/// edit, Undo, a switch to another document and back, and a selection change. +#[test] +fn the_control_bar_label_follows_edits_undo_documents_and_selection() { + let mut app = app(); + let path = temp_file("label.png", &png(30, 30, 72.0)); + app.run("file.place", json!({"path": path})).unwrap(); + let text = |app: &mut VectorcraftApp| crate::tests_labels::painted_text(app, crate::chrome::control_bar); + assert!(text(&mut app).contains("Linked File")); + app.run("links.embed", json!({})).unwrap(); + let embedded = text(&mut app); + assert!(embedded.contains("Embedded") && !embedded.contains("Linked File"), "{embedded}"); + app.run("edit.undo", json!({})).unwrap(); + assert!(text(&mut app).contains("Linked File")); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + assert!(!text(&mut app).contains("Linked File"), "the new document has nothing selected"); + app.session.set_active(0); + assert!(text(&mut app).contains("Linked File")); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap(); + let rect = text(&mut app); + assert!(!rect.contains("Linked File") && !rect.contains("Embedded"), "{rect}"); +} + /// Click the Control bar's `label`. fn click_label(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) { use crate::tests_removeanchors::{at, click_control, control_frame}; diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3763b806a5..15ab8bed65 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1314,6 +1314,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Live objects in documents with many symbols:** a live object, or an object with effects, that shows symbols or patterns is not walked again in a later frame to find them while the document's symbols and patterns stay the same. One that shows a placed file is walked in every frame. At 1000 × 1000 pixels, a page of 2,000 envelopes around instances of the last 2,000 of 10,000 symbols takes 30 ms a frame, and 83 ms when every frame walks them again, with the same pixels. +- **Control bar and task bar on large paths:** the Control bar and the contextual task bar read the first selected object in place each frame instead of copying it; the task bar copies the object only when it is a basic shape, for its Shape Properties. With one selected open path of 200,000 anchors, an idle frame with both bars shown takes 3.8 ms in a release build instead of 8.0 ms (medians of five interleaved runs). Test: `the_control_bar_label_follows_edits_undo_documents_and_selection`. + - **Type drawn as glyph outlines:** under a geometry effect, in EMF and WMF export, in DXF export when it is written as outlines, flattened with Convert All Text to Outlines, and inside an envelope, type keeps its underline and strikethrough, the weight and dashes of its character strokes when it is scaled, and the placement of its gradients and patterns, as the canvas draws it. A group's or layer's own fills and strokes also paint the underline and strikethrough of the type in it. - **Texture redraws (#1257):** Craquelure, Mosaic Tiles and Stained Glass compare squared distances when finding their nearest cells; rounding/tie boundaries use the original distance ordering. Brute-force candidate tests and three 1800×1500 viewport comparisons preserve the old pixels. A CMYK rectangle move at 190.07%/DPI 1.5 is reproducible with `cargo test -p vectorcraft-render texture_drag_perf -- --ignored --nocapture`; idle-machine Windows interaction is still unverified. From dba21932342b5c0b4e40924ab9b14937be8dc0ec Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 19:07:21 -0800 Subject: [PATCH 022/196] Tests: the task bar follows the active document after a switch A test selects an open path in one document and a rectangle in a new one, then switches back and forth with set_active: the task bar offers Join only for the open path and Shape Properties only for the rectangle. --- crates/ui-egui/src/tests/taskbar.rs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/crates/ui-egui/src/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index a1374bd373..f52235297d 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -418,3 +418,29 @@ fn a_compound_path_under_direct_selection_drops_edit_path() { let (_, texts) = bar(&mut app); assert!(has(&texts, "Release Compound Path") && !has(&texts, "Edit Path"), "{texts:?}"); } + +/// After a switch to another document and back, the task bar shows the actions for the active +/// document's selection: an open path's Join in the first, a rectangle's Shape Properties in the +/// second. +#[test] +fn the_task_bar_follows_the_active_document() { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let line = id(app.run("shape.line", json!({"x1": 50, "y1": 50, "x2": 200, "y2": 120})).unwrap()); + select(&mut app, &[line]); + assert!(has(&bar(&mut app).1, "Join")); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let rect = id(app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 80, "height": 60})).unwrap()); + select(&mut app, &[rect]); + let (_, texts) = bar(&mut app); + assert!(!has(&texts, "Join") && has(&texts, "Duplicate"), "{texts:?}"); + app.session.set_active(0); + let (_, texts) = bar(&mut app); + assert!(has(&texts, "Join"), "{texts:?}"); + app.session.set_active(1); + let (_, texts) = bar(&mut app); + assert!(!has(&texts, "Join"), "{texts:?}"); + let (_, texts) = click_lock_slot(&mut app); + assert!(has(&texts, "Rectangle Properties:"), "{texts:?}"); + assert!(!locked(&app, rect), "the button doesn't lock the shape"); +} From 822e4669ce8a0ad19fa3e156fa3b06cd9025b0cb Mon Sep 17 00:00:00 2001 From: Ammar Almakzumi Date: Wed, 4 Nov 2026 21:42:32 -0600 Subject: [PATCH 023/196] fix(ui): avoid duplicate cursor without Wayland theme --- crates/ui-egui/src/canvas.rs | 2 +- crates/ui-egui/src/cursors.rs | 10 +++++----- crates/ui-egui/src/cursors/tests.rs | 7 ++++--- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 06a9f488d3..4205c31782 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -460,7 +460,7 @@ fn canvas_cursor(app: &mut VectorcraftApp, ui: &Ui, view_info: vectorcraft_engin } Some(hp) if custom - && crate::cursors::paint_glyphs(crate::cursors::HIDES_ONLY_WHEN_KEY, ui.input(|i| i.focused)) + && crate::cursors::paint_glyphs(crate::cursors::HIDES_ONLY_WHEN_KEY, ui.input(|i| i.focused), app.services.no_cursor_theme) && crate::cursors::paint(&painter, c, hp, 1.0 / ui_scale) => { // No cursor theme (Wayland): the glyph is painted, the system pointer stays (#2450). diff --git a/crates/ui-egui/src/cursors.rs b/crates/ui-egui/src/cursors.rs index 44377a2c84..b404f99677 100644 --- a/crates/ui-egui/src/cursors.rs +++ b/crates/ui-egui/src/cursors.rs @@ -714,11 +714,11 @@ pub fn hide_system_pointer(no_cursor_theme: bool) -> bool { /// Over a window behind another app or under a sheet, the system pointer shows (#2020). pub const HIDES_ONLY_WHEN_KEY: bool = cfg!(target_os = "macos"); -/// Does the window paint the glyphs over a hidden pointer, `focused` or not? Not where the system -/// shows its pointer over a window without the focus ([`HIDES_ONLY_WHEN_KEY`]): the system pointer -/// shows alone there. -pub fn paint_glyphs(hides_only_when_key: bool, focused: bool) -> bool { - focused || !hides_only_when_key +/// Does the window paint a glyph over a hidden pointer? Not where it cannot hide the system pointer +/// (no cursor theme on Wayland), or where the system shows its pointer without the focus +/// ([`HIDES_ONLY_WHEN_KEY`]): the system pointer shows alone there. +pub fn paint_glyphs(hides_only_when_key: bool, focused: bool, no_cursor_theme: bool) -> bool { + !no_cursor_theme && (focused || !hides_only_when_key) } /// The cursor bitmaps handed to the OS, by (cursor, pixels per point): each glyph is rasterized diff --git a/crates/ui-egui/src/cursors/tests.rs b/crates/ui-egui/src/cursors/tests.rs index ece8895b44..73c0b5979f 100644 --- a/crates/ui-egui/src/cursors/tests.rs +++ b/crates/ui-egui/src/cursors/tests.rs @@ -472,9 +472,10 @@ fn wayland_windows_paint_the_glyphs() { #[test] fn macos_windows_paint_the_glyphs_only_with_the_focus() { - assert!(paint_glyphs(true, true), "macOS with the focus"); - assert!(!paint_glyphs(true, false), "macOS without the focus: the system pointer shows (#2020)"); - assert!(paint_glyphs(false, true) && paint_glyphs(false, false), "Wayland, the web: painted with the focus or without"); + assert!(paint_glyphs(true, true, false), "macOS with the focus"); + assert!(!paint_glyphs(true, false, false), "macOS without the focus: the system pointer shows (#2020)"); + assert!(paint_glyphs(false, true, false) && paint_glyphs(false, false, false), "Wayland, the web: painted with the focus or without"); + assert!(!paint_glyphs(false, true, true), "without a cursor theme, use the system pointer alone"); } #[test] From c23612970265ba1a420e07e44883ffb859433720 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 19:10:12 -0800 Subject: [PATCH 024/196] Docs: name the task bar test in the Control bar and task bar line --- 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 15ab8bed65..3b3b6e46d5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1314,7 +1314,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Live objects in documents with many symbols:** a live object, or an object with effects, that shows symbols or patterns is not walked again in a later frame to find them while the document's symbols and patterns stay the same. One that shows a placed file is walked in every frame. At 1000 × 1000 pixels, a page of 2,000 envelopes around instances of the last 2,000 of 10,000 symbols takes 30 ms a frame, and 83 ms when every frame walks them again, with the same pixels. -- **Control bar and task bar on large paths:** the Control bar and the contextual task bar read the first selected object in place each frame instead of copying it; the task bar copies the object only when it is a basic shape, for its Shape Properties. With one selected open path of 200,000 anchors, an idle frame with both bars shown takes 3.8 ms in a release build instead of 8.0 ms (medians of five interleaved runs). Test: `the_control_bar_label_follows_edits_undo_documents_and_selection`. +- **Control bar and task bar on large paths:** the Control bar and the contextual task bar read the first selected object in place each frame instead of copying it; the task bar copies the object only when it is a basic shape, for its Shape Properties. With one selected open path of 200,000 anchors, an idle frame with both bars shown takes 3.8 ms in a release build instead of 8.0 ms (medians of five interleaved runs). Tests: `the_control_bar_label_follows_edits_undo_documents_and_selection`, `the_task_bar_follows_the_active_document`. - **Type drawn as glyph outlines:** under a geometry effect, in EMF and WMF export, in DXF export when it is written as outlines, flattened with Convert All Text to Outlines, and inside an envelope, type keeps its underline and strikethrough, the weight and dashes of its character strokes when it is scaled, and the placement of its gradients and patterns, as the canvas draws it. A group's or layer's own fills and strokes also paint the underline and strikethrough of the type in it. From ba3e4a9da26ccd75efe09655242c191d46a1cb03 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 5 Nov 2026 10:50:19 +0700 Subject: [PATCH 025/196] Cursors: drop the system-pointer branch that no cursor theme can reach any more --- crates/ui-egui/src/canvas.rs | 5 +++-- crates/ui-egui/src/cursors.rs | 10 ++-------- crates/ui-egui/src/cursors/tests.rs | 2 -- crates/ui-egui/src/services.rs | 2 +- 4 files changed, 6 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 4205c31782..0b563c24c5 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -463,8 +463,9 @@ fn canvas_cursor(app: &mut VectorcraftApp, ui: &Ui, view_info: vectorcraft_engin && crate::cursors::paint_glyphs(crate::cursors::HIDES_ONLY_WHEN_KEY, ui.input(|i| i.focused), app.services.no_cursor_theme) && crate::cursors::paint(&painter, c, hp, 1.0 / ui_scale) => { - // No cursor theme (Wayland): the glyph is painted, the system pointer stays (#2450). - if crate::cursors::hide_system_pointer(app.services.no_cursor_theme) { egui::CursorIcon::None } else { cursor_icon(c) } + // The painted glyph stands in for the hidden system pointer. Without a cursor theme + // (Wayland) none is painted: the system pointer can't be hidden there (#2450). + egui::CursorIcon::None } _ => cursor_icon(c), } diff --git a/crates/ui-egui/src/cursors.rs b/crates/ui-egui/src/cursors.rs index b404f99677..eda747fc8f 100644 --- a/crates/ui-egui/src/cursors.rs +++ b/crates/ui-egui/src/cursors.rs @@ -702,20 +702,14 @@ pub fn os_cursors(build: bool, wayland: bool) -> bool { build && !wayland } -/// Does the canvas hide the system pointer to show a painted tool glyph alone? Not when there is no -/// cursor theme on Wayland ([`crate::Services::no_cursor_theme`]): winit sets no pointer then, and a -/// hidden one would not come back over the panels (#2450). The system pointer stays beside the glyph. -pub fn hide_system_pointer(no_cursor_theme: bool) -> bool { - !no_cursor_theme -} - /// Does the window hide the pointer only while it is the key window? macOS does: winit hides it with /// a cursor rect holding a transparent cursor, and macOS applies the rect only in the key window. /// Over a window behind another app or under a sheet, the system pointer shows (#2020). pub const HIDES_ONLY_WHEN_KEY: bool = cfg!(target_os = "macos"); /// Does the window paint a glyph over a hidden pointer? Not where it cannot hide the system pointer -/// (no cursor theme on Wayland), or where the system shows its pointer without the focus +/// (no cursor theme on Wayland, [`crate::Services::no_cursor_theme`]: winit sets no pointer then, +/// and a hidden one would not come back over the panels, #2450), or where the system shows its pointer without the focus /// ([`HIDES_ONLY_WHEN_KEY`]): the system pointer shows alone there. pub fn paint_glyphs(hides_only_when_key: bool, focused: bool, no_cursor_theme: bool) -> bool { !no_cursor_theme && (focused || !hides_only_when_key) diff --git a/crates/ui-egui/src/cursors/tests.rs b/crates/ui-egui/src/cursors/tests.rs index 73c0b5979f..e70f7d488a 100644 --- a/crates/ui-egui/src/cursors/tests.rs +++ b/crates/ui-egui/src/cursors/tests.rs @@ -387,8 +387,6 @@ fn a_wayland_window_paints_the_tool_cursor() { /// Without a cursor theme the canvas keeps the system pointer visible (#2450). #[test] fn no_cursor_theme_keeps_the_system_pointer() { - assert!(!hide_system_pointer(true)); - assert!(hide_system_pointer(false)); let mut app = VectorcraftApp::new(Session::new(), crate::Services { wayland: true, no_cursor_theme: true, ..Default::default() }); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); let ctx = egui::Context::default(); diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 3d35247880..d7fe9e593b 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -150,7 +150,7 @@ pub struct Services { pub wayland: bool, /// On Wayland, no cursor theme can be loaded, so winit sets no pointer and the compositor's /// default one would never come back once the canvas hid it: the canvas keeps the system - /// pointer visible next to the tool glyph ([`cursors::hide_system_pointer`], #2450). + /// pointer and paints no tool glyph ([`cursors::paint_glyphs`], #2450). pub no_cursor_theme: bool, /// The pen pressure and pen end the host reads from the system itself (desktop Linux under /// X11 and XWayland, macOS and Windows). The canvas uses the pressure when a frame's events carry no touch force, From 8a5ec6a25fff090843adac5569f20e467f0021fb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 19:35:44 -0800 Subject: [PATCH 026/196] Tests: the task bar follows an edit and Undo The task bar drops Join once the selected open path is closed and offers it again after Undo, and Shape Properties shows a rectangle's corner radius as it is after object.setLiveShape and after Undo. The progress line names the new test. --- crates/ui-egui/src/tests/taskbar.rs | 30 +++++++++++++++++++++++++++++ docs/target-app-parity.md | 2 +- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index f52235297d..96e4533449 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -444,3 +444,33 @@ fn the_task_bar_follows_the_active_document() { assert!(has(&texts, "Rectangle Properties:"), "{texts:?}"); assert!(!locked(&app, rect), "the button doesn't lock the shape"); } + +/// The task bar shows the selection as it is after an edit and after Undo: Join leaves once the +/// open path is closed and comes back with Undo, and Shape Properties shows a rectangle's new +/// corner radius and then its old one. +#[test] +fn the_task_bar_follows_edits_and_undo() { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let line = id(app.run("shape.line", json!({"x1": 50, "y1": 50, "x2": 200, "y2": 120})).unwrap()); + select(&mut app, &[line]); + assert!(has(&bar(&mut app).1, "Join")); + app.run("path.join", json!({})).unwrap(); + let (_, texts) = bar(&mut app); + assert!(!has(&texts, "Join"), "{texts:?}"); + app.run("edit.undo", json!({})).unwrap(); + let (_, texts) = bar(&mut app); + assert!(has(&texts, "Join"), "{texts:?}"); + + let rect = id(app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 80, "height": 60, "radius": 10})).unwrap()); + select(&mut app, &[rect]); + let (_, texts) = click_lock_slot(&mut app); + assert!(has(&texts, "10 pt") && !has(&texts, "20 pt"), "{texts:?}"); + app.run("object.setLiveShape", json!({"radius": 20})).unwrap(); + let (_, texts) = click_lock_slot(&mut app); + assert!(has(&texts, "20 pt") && !has(&texts, "10 pt"), "{texts:?}"); + app.run("edit.undo", json!({})).unwrap(); + let (_, texts) = click_lock_slot(&mut app); + assert!(has(&texts, "10 pt") && !has(&texts, "20 pt"), "{texts:?}"); + assert!(!locked(&app, rect), "the button doesn't lock the shape"); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b3b6e46d5..a8ee089e5c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1314,7 +1314,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Live objects in documents with many symbols:** a live object, or an object with effects, that shows symbols or patterns is not walked again in a later frame to find them while the document's symbols and patterns stay the same. One that shows a placed file is walked in every frame. At 1000 × 1000 pixels, a page of 2,000 envelopes around instances of the last 2,000 of 10,000 symbols takes 30 ms a frame, and 83 ms when every frame walks them again, with the same pixels. -- **Control bar and task bar on large paths:** the Control bar and the contextual task bar read the first selected object in place each frame instead of copying it; the task bar copies the object only when it is a basic shape, for its Shape Properties. With one selected open path of 200,000 anchors, an idle frame with both bars shown takes 3.8 ms in a release build instead of 8.0 ms (medians of five interleaved runs). Tests: `the_control_bar_label_follows_edits_undo_documents_and_selection`, `the_task_bar_follows_the_active_document`. +- **Control bar and task bar on large paths:** the Control bar and the contextual task bar read the first selected object in place each frame instead of copying it; the task bar copies the object only when it is a basic shape, for its Shape Properties. With one selected open path of 200,000 anchors, an idle frame with both bars shown takes 3.8 ms in a release build instead of 8.0 ms (medians of five interleaved runs). Tests: `the_control_bar_label_follows_edits_undo_documents_and_selection`, `the_task_bar_follows_the_active_document`, `the_task_bar_follows_edits_and_undo`. - **Type drawn as glyph outlines:** under a geometry effect, in EMF and WMF export, in DXF export when it is written as outlines, flattened with Convert All Text to Outlines, and inside an envelope, type keeps its underline and strikethrough, the weight and dashes of its character strokes when it is scaled, and the placement of its gradients and patterns, as the canvas draws it. A group's or layer's own fills and strokes also paint the underline and strikethrough of the type in it. From 077ef54d706b3f329ae04e6a4e93faa46a593d5d Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Wed, 4 Nov 2026 22:46:21 -0500 Subject: [PATCH 027/196] Gradient panel: Delete Stop sits beside the ramp, so a short panel no longer hides it (#5403) The Delete Stop button sat at the end of the Opacity/Location row, below the selected stop's Color row. In the default docked panel height that row is cut off as soon as a stop is selected, so the button looked missing. It now sits at the right end of the ramp, level with it, and shows whenever the ramp does (with options hidden too). It deletes the selected stop, never below two, as before. Adds a headless panel test for deleting a stop by dragging it off the ramp and with the button beside it, one undo step each, and for a two-stop gradient keeping both. --- crates/ui-egui/src/panels/gradient.rs | 44 ++++++++++++++------- crates/ui-egui/src/panels/gradient/tests.rs | 36 +++++++++++++++++ docs/target-app-parity.md | 4 +- docs/ui-parity.md | 4 +- 4 files changed, 72 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/panels/gradient.rs b/crates/ui-egui/src/panels/gradient.rs index 2b71ea0545..631d38ab7f 100644 --- a/crates/ui-egui/src/panels/gradient.rs +++ b/crates/ui-egui/src/panels/gradient.rs @@ -41,6 +41,8 @@ use crate::{VectorcraftApp, icons}; /// Dragging a stop this far below the ramp removes it. const REMOVE_DISTANCE: f32 = 28.0; +/// The Delete Stop button beside the ramp, points square. +const DELETE_STOP_SIZE: f32 = 22.0; /// The Angle field's preset menu, degrees. const ANGLE_PRESETS: [f64; 9] = [-180.0, -135.0, -90.0, -45.0, 0.0, 45.0, 90.0, 135.0, 180.0]; /// The Aspect Ratio field's preset menu, percent. @@ -280,7 +282,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if hidden { if !freeform { ui.add_space(6.0); - ramp(app, ui, &g.gradient, is_grad); + ramp_row(app, ui, &g.gradient, is_grad); } return; } @@ -358,7 +360,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { }); }); ui.add_space(6.0); - ramp(app, ui, &g.gradient, is_grad); + ramp_row(app, ui, &g.gradient, is_grad); ui.add_space(4.0); stop_fields(app, ui, &g.gradient, is_grad); // Dither applies to gradient fills only: off and dimmed behind the Stroke proxy. @@ -569,7 +571,7 @@ fn thumbnail(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint, is_grad: } /// The selected stop's colour (click: its popover; the eyedropper samples one from the art), -/// opacity and location (a selected diamond's midpoint instead), and Delete Stop. +/// opacity and location (a selected diamond's midpoint instead). fn stop_fields(app: &mut VectorcraftApp, ui: &mut Ui, g: &Gradient, is_grad: bool) { let stops = &g.stops; let sel = app.session.selected_stop().filter(|i| *i < stops.len() && is_grad); @@ -623,14 +625,29 @@ fn stop_fields(app: &mut VectorcraftApp, ui: &mut Ui, g: &Gradient, is_grad: boo } } }); - let can_del = sel.is_some() && stops.len() > MIN_STOPS; - if widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Stop"), false, can_del, 22.0).clicked() - && let Some(i) = sel - && let Some(v) = remove_stop(stops, i) - { - let next = i.min(v.len() - 1); - set_stops(app, &v, Some(next), Live::Released); - } + }); +} + +/// The ramp with Delete Stop at its right end, level with the ramp so it shows whenever the ramp +/// does: it deletes the selected stop, never below two. +fn ramp_row(app: &mut VectorcraftApp, ui: &mut Ui, g: &Gradient, is_grad: bool) { + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = 0.0; + let w = (ui.available_width() - DELETE_STOP_SIZE).max(DELETE_STOP_SIZE * 2.0); + ramp(app, ui, g, is_grad, w); + ui.vertical(|ui| { + // Level with the ramp (the bar starts 10 points down and is 18 tall). + ui.add_space(8.0); + let sel = app.session.selected_stop().filter(|i| *i < g.stops.len() && is_grad); + let can_del = sel.is_some() && g.stops.len() > MIN_STOPS; + if widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Stop"), false, can_del, DELETE_STOP_SIZE).clicked() + && let Some(i) = sel + && let Some(v) = remove_stop(&g.stops, i) + { + let next = i.min(v.len().saturating_sub(1)); + set_stops(app, &v, Some(next), Live::Released); + } + }); }); } @@ -709,10 +726,9 @@ fn dropped_swatch(app: &VectorcraftApp, ui: &Ui, g: &Gradient, area_resp: &egui: Some(drop_color(g, g.stops.iter().position(|s| marker(s.offset).contains(p)), x_to_offset(p.x, bar.left(), bar.width()), c, link)) } -/// The gradient slider: ramp, stops below, midpoint diamonds above. -fn ramp(app: &mut VectorcraftApp, ui: &mut Ui, g: &Gradient, is_grad: bool) { +/// The gradient slider, `w` points wide: ramp, stops below, midpoint diamonds above. +fn ramp(app: &mut VectorcraftApp, ui: &mut Ui, g: &Gradient, is_grad: bool, w: f32) { let t = Tokens::get(ui.ctx()); - let w = ui.available_width(); let (area, area_resp) = ui.allocate_exact_size(vec2(w, 50.0), Sense::hover()); let bar = Rect::from_min_size(area.min + vec2(8.0, 10.0), vec2(w - 16.0, 18.0)); paint_ramp(ui, g, bar); diff --git a/crates/ui-egui/src/panels/gradient/tests.rs b/crates/ui-egui/src/panels/gradient/tests.rs index 83a290bb1d..65602079b8 100644 --- a/crates/ui-egui/src/panels/gradient/tests.rs +++ b/crates/ui-egui/src/panels/gradient/tests.rs @@ -726,3 +726,39 @@ fn the_panel_menu_saves_deletes_and_hides_presets() { p.menu_click(&mut app, text_at(&texts, "Show Presets").unwrap()); assert!(text_at(&p.frame(&mut app, vec![], Modifiers::NONE), "Presets:").is_some()); } + +/// A stop is deleted by dragging it down off the ramp or with Delete Stop, which sits at the +/// ramp's right end (so a short panel doesn't hide it below the stop fields, #5403); one undo +/// step each, and a two-stop gradient keeps both. +#[test] +fn a_stop_dragged_off_the_ramp_or_deleted_with_the_button_beside_it_goes() { + let stops = json!([{"offset": 0, "color": "#ffffff"}, {"offset": 0.5, "color": "#ff0000"}, {"offset": 1, "color": "#000000"}]); + let mut app = app(json!({"gradient": {"stops": stops}})); + let mut p = Panel::new(); + p.frame(&mut app, vec![], Modifiers::NONE); + let mid = p.widget(("grad-stop", 1)).center(); + // Dragged down off the ramp, the middle stop goes. + p.drag(&mut app, mid, mid + vec2(0.0, 60.0), Modifiers::NONE); + assert_eq!(hexes(&app), ["#ffffff", "#000000"]); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(hexes(&app), ["#ffffff", "#ff0000", "#000000"]); + // Delete Stop, level with the ramp and right of it, removes the selected stop. + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + p.frame(&mut app, vec![], Modifiers::NONE); + let bar = p.widget("grad-bar"); + let del = *p.row_after(bar.left_center(), 22.0).last().expect("Delete Stop beside the ramp"); + assert!(del.left() >= bar.right(), "right of the ramp"); + p.click(&mut app, del.center()); + assert_eq!(hexes(&app), ["#ffffff", "#000000"]); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(hexes(&app), ["#ffffff", "#ff0000", "#000000"]); + app.run("edit.redo", json!({})).unwrap(); + // Two stops stay two: dragged off, the stop comes back, and the button is off. + let first = p.widget(("grad-stop", 0)).center(); + p.drag(&mut app, first, first + vec2(0.0, 60.0), Modifiers::NONE); + assert_eq!(hexes(&app), ["#ffffff", "#000000"]); + app.run("gradient.selectStop", json!({"index": 0})).unwrap(); + p.frame(&mut app, vec![], Modifiers::NONE); + p.click(&mut app, del.center()); + assert_eq!(hexes(&app), ["#ffffff", "#000000"]); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a8ee089e5c..cbbb336c8b 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-05 · **Change:** minor (Artboards panel multi-select with any tool, Fill for every selected artboard; 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-05 · **Change:** minor (Gradient panel: Delete Stop beside the ramp, #5403; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -27,6 +27,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | 2026-11-04 | minor | Transform Each's Scale has the documented Relative and Absolute radio buttons (`object.transformEach` `relative`: percentages of each object's size, or the width and height it becomes, measured on each object's own bounds) and the link that keeps the two scales in proportion; the panel lists Scale, Move, Rotate, the Options in two columns, the Reference Point and Preview (level with Copy, Cancel and OK) in the documented order. Scores and estimates unchanged. | | 2026-11-05 | minor | PDF import: a DeviceN gradient of a spot ink over process plates keeps the ink and the plates, and PDF export writes it as a DeviceN shading again (#3235); scores unchanged | | 2026-11-05 | minor | Optical kerning moves each pair part of the way toward the font's own stem spacing, with a minimum gap and tighter limits, and leaves ideographs, kana, fullwidth forms and dashes on the font's spacing, so text is no longer squeezed (#5336). Scores and estimates unchanged. | +| 2026-11-05 | minor | Gradient panel: Delete Stop sits at the right end of the ramp, so it shows whenever the ramp does instead of under the stop fields, where a short panel hid it (#5403); scores and estimates unchanged | | 2026-11-04 | minor | Type core: a Type-range Copy or Cut publishes styled art alongside plain text, so canvas Paste keeps font family, size and color after editing ends (#5636); scores and estimates unchanged. | | 2026-11-04 | minor | Selection Tools add-on: Select by Artboards selects the objects overlapping, fully inside or fully outside several chosen artboards, from a dialog that lists, searches and multi-selects the artboards and fits one in the window on double-click (#5525, #5548, #5549, a VectorCraft addition); scores and estimates unchanged. | | 2026-11-04 | minor | New Document: the units chosen in Preset Details belong to the chosen preset, as the public page lists the pane's options for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units (#2078). Scores and estimates unchanged. | @@ -1064,6 +1065,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Sample Color from Screen:** an eyedropper button in the Color Picker and `ui.sampleScreenColor` (which can be given a key in Keyboard Shortcuts) pick a color anywhere on the screen with the system's sampler: `NSColorSampler` on macOS, the EyeDropper API in browsers that have it. The color becomes the fill or the stroke as one undo step, or the Color Picker's color, converted from display sRGB into the working RGB space. Windows, Linux and other browsers have no sampler yet; the button is gray there. - **Stroke visibility (#1253):** adding paint to a previously unpainted zero-width stroke restores the existing 1 pt default (`PaintDefaults::default`, `Appearance::set_stroke`), for the selected appearance item, the new-art defaults and Swap Fill/Stroke. Positive widths are kept; recoloring a painted zero-width stroke keeps its explicit zero. A real Eyedropper-to-new-shape sequence reproduces the zero-width inheritance. Five engine regressions cover creation, defaults, targeted items, preserved widths and one-step Undo/Redo (`crates/engine/tests/it/stroke_visibility.rs`). - **Gradients:** lossless, validated gradient params; gradients follow rotate, reflect, shear, non-uniform scale and distortions; the Gradient tool edits the fill or stroke of the active proxy, type included; an interactive on-canvas annotator (move, length/angle, rotate, add/move/delete/duplicate stops, midpoints, a stop popover, Delete and arrow keys). The Gradient panel has the Fill/Stroke proxy, a gradient-swatch dropdown with Save to Swatches, midpoint locations, Alt-drag to copy or swap stops, swatch drops on the ramp and a stop eyedropper; copied appearances and graphic styles place gradients on each target's own bounds; gradient handles snap and honour Constrain Angle. Gradient stops stay linked to global and spot swatches. Freeform gradients (points and lines) are edited on the canvas; radial gradients have an extent ellipse, an aspect handle and an off-centre focal point (SVG `fx`/`fy`, PDF two-point radials). A stroke's gradient runs within, along or across it. Object ▸ Expand turns gradients into N objects or a gradient mesh. + - The Gradient panel's Delete Stop sits at the right end of the ramp, level with it, so a panel too short to show the stop fields still shows it; it deletes the selected stop (never below two), as dragging a stop down off the ramp does (#5403). - The stop popover a double-click on a stop opens (the Gradient tool's annotator or the Gradient panel) has an eyedropper beside its Color and Swatches tabs: it closes the popover and samples the next colour clicked on the art into the stop, as the Gradient panel's eyedropper does (#4681). Cmd/Ctrl-click on the Gradient panel's Gradient Fill box or on the Tools panel's Gradient button resets the gradient of the active Fill or Stroke to the linear White, Black gradient, as one undo step ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). With a gradient stop or a freeform gradient point selected, Alt-clicking a color swatch in the Swatches panel recolors it instead of the inactive Fill or Stroke. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index c7a988d9f0..35bdd5d628 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (Path Precision Tools: Set Corners… rounds every other anchor; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Gradient panel: Delete Stop beside the ramp, #5403; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) ## Feature submission evidence @@ -30,6 +30,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-05 | minor | Gradient panel: Delete Stop sits at the right end of the ramp, so it shows whenever the ramp does instead of under the stop fields, where a short panel hid it (#5403); scores and estimates unchanged | | 2026-11-04 | minor | Artboards panel: a Shift- or Ctrl/Cmd-click on a row selects several artboards with any tool, switching to the Artboard tool first, so a preset, orientation, size or Fill set in Properties or the Control bar goes to every selected artboard; Fill used to set the active artboard only (#5698); scores and estimates unchanged | | 2026-11-04 | minor | Isolation mode: once the layer, or a group, around the isolated object is locked or hidden, a click or a marquee with the Selection tool no longer selects the isolated art (part of #5309); scores and estimates unchanged | | 2026-11-04 | minor | Transform Each's Scale has the documented Relative and Absolute radio buttons: percentages of each object's size, or the width and height it becomes (`object.transformEach` `relative`); the two scales have the link that keeps them in proportion (`__constrain`, as the shape dialogs'), and the panel lists Scale, Move, Rotate, the Options in two columns, the Reference Point and Preview (level with Copy, Cancel and OK) in the documented order; scores and estimates unchanged | @@ -358,6 +359,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Gradient panel: Dither (30.0) | done | Dither box under the stops (`paint.editGradient` `dither`); dimmed behind the Stroke proxy, fills only; `panels::gradient` test | | Gradient panel: Method, Classic or Perceptual (30.0) | done | Method menu under the Stroke buttons for linear and radial gradients (`paint.editGradient` `method`); [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-gradients/control-perceptual-interpolation-in-gradients.html); `panels::gradient` test | | Gradient panel: Presets (30.0) | done | Presets menu by library (theme) plus Saved: applies a preset to the gradient behind the active proxy, keeping its placement, one undo step; panel menu Save Gradient Preset…, Delete Gradient Preset, Hide/Show Presets (`gradient.presets.*`); `panels::gradient` tests | +| Gradient panel: delete a stop | done | Delete Stop at the right end of the ramp deletes the selected stop, and a stop dragged down off the ramp is deleted on release, never below two stops, one undo step each; [Gradient panel options](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-gradients/gradient-tool-and-panel.html); `panels::gradient` test | | SVG Interactivity, Retype, Comments, Version History panels | missing | the last two are cloud features (out of scope) | | Workspaces (save, reset, switch); each remembers the layout changes made in it across switches and restarts until Reset | done | `UiState::workspace_changes` | | Background Export: a progress dialog with the file name, the artboard count and a bar (busy for one artboard and for formats made in one go), Cancel (Esc) and Continue in Background; it opens after 0.4 s and never over another dialog. A cancelled export writes no file | done | #2564; on the shared `vectorcraft_doc::cancel` token (#2546), so a cancelled render keeps no half-drawn pattern tile or effect raster. The bar moves between artboards, not within one. Save As, Export for Screens and Export Selection don't show it yet | From 62c6d42dffa938c37408cbcd2001bce8d61cdc98 Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Thu, 5 Nov 2026 11:04:52 +0700 Subject: [PATCH 028/196] Set Corners: round only the corners in an angle range (#5545) Squashed from #5737 onto main. --- .../src/cmd/addons/pathtools/corners.rs | 81 ++++++++++++++++--- .../engine/src/cmd/addons/pathtools/tests.rs | 77 ++++++++++++++++++ crates/engine/tests/command_sweep.rs | 3 + crates/ui-egui/src/addons/pathtools/corner.rs | 2 +- .../src/addons/pathtools/set_corners.rs | 57 ++++++++++++- crates/ui-egui/src/i18n/bg.tsv | 2 + crates/ui-egui/src/i18n/bs.tsv | 2 + crates/ui-egui/src/i18n/ca.tsv | 2 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/da.tsv | 2 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/el.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/fi.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/id.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/ka.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/nl.tsv | 2 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt-br.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 2 + crates/ui-egui/src/i18n/sv.tsv | 2 + crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + docs/mcp.md | 6 +- docs/target-app-parity.md | 4 +- docs/ui-parity.md | 5 +- 34 files changed, 264 insertions(+), 23 deletions(-) diff --git a/crates/engine/src/cmd/addons/pathtools/corners.rs b/crates/engine/src/cmd/addons/pathtools/corners.rs index 2da1a5c176..2f035d8ad4 100644 --- a/crates/engine/src/cmd/addons/pathtools/corners.rs +++ b/crates/engine/src/cmd/addons/pathtools/corners.rs @@ -20,7 +20,7 @@ pub(super) fn specs() -> Vec { "Set Corners", [], None, - "{ids?: [id…] (the selection), anchors?: [index…] (of each path's outline with no corners cut; else its direct-selected anchors, or all of them), items?: [{id, anchors?}…] (instead of ids: each path with its own anchors), radius: pt 0..1000000 (drawn no larger than fits), kind?: \"round\"|\"invertedRound\"|\"chamfer\" (each corner's own), every?: \"all\"|\"odd\"|\"even\" (default all: of those anchors, only the odd- or even-numbered ones, counting each path's anchors from 1)} cut live corners at the anchors that can have one, as one undo step → {ids, corners (how many)}", + "{ids?: [id…] (the selection), anchors?: [index…] (of each path's outline with no corners cut; else its direct-selected anchors, or all of them), items?: [{id, anchors?}…] (instead of ids: each path with its own anchors), radius: pt 0..1000000 (drawn no larger than fits), kind?: \"round\"|\"invertedRound\"|\"chamfer\" (each corner's own), every?: \"all\"|\"odd\"|\"even\" (default all: of those anchors, only the odd- or even-numbered ones, counting each path's anchors from 1), minAngle?: degrees 0..180 (default 0), maxAngle?: degrees 0..180 (default 180; of those anchors, only the corners whose sides meet at an angle in this range: small for a sharp spike, near 180 for a shallow bend)} cut live corners at the anchors that can have one, as one undo step → {ids, corners (how many)}", has_doc, corner_set ), @@ -84,19 +84,74 @@ impl Every { } } - /// The error when none of the chosen corners is one it takes. - fn none(self) -> &'static str { + /// Where the corners it takes are, for an error: "" for all of them. + fn at(self) -> &'static str { match self { - Self::All => "choose anchors where two sides meet at an angle: only those take a corner", - Self::Odd => "none of the chosen corners is at an odd-numbered anchor (the 1st, 3rd, 5th…)", - Self::Even => "none of the chosen corners is at an even-numbered anchor (the 2nd, 4th, 6th…)", + Self::All => "", + Self::Odd => " at an odd-numbered anchor (the 1st, 3rd, 5th…)", + Self::Even => " at an even-numbered anchor (the 2nd, 4th, 6th…)", + } + } +} + +/// How far (degrees) past the ends of the angle range a corner's angle may be, so that a typed 90 +/// takes a rectangle's corners whatever the rounding. +const ANGLE_SLACK: f64 = 1e-6; +/// The error when no anchor named is a corner at all. +const NO_CORNER: &str = "choose anchors where two sides meet at an angle: only those take a corner"; + +/// Which of the chosen corners `cornerSet` takes: by their number (`every`) and by the angle their +/// sides meet at (`minAngle`..`maxAngle`, degrees). +#[derive(Clone, Copy, Debug, PartialEq)] +struct Pick { + every: Every, + min_angle: f64, + max_angle: f64, +} + +impl Pick { + /// Every chosen corner. + const ALL: Self = Self { every: Every::All, min_angle: 0.0, max_angle: 180.0 }; + + /// The `every`, `minAngle` and `maxAngle` of `p`. + fn of(p: &Value, cmd: &str) -> Result { + let every = Every::of(p, cmd)?; + let angle = |key: &str, default: f64| -> Result { + let a = number_or(p, key, default, cmd)?; + if !(a.is_finite() && (0.0..=180.0).contains(&a)) { + return Err(bad(cmd, format!("`{key}` must be from 0 to 180 degrees, not {a}"))); + } + Ok(a) + }; + let (min_angle, max_angle) = (angle("minAngle", 0.0)?, angle("maxAngle", 180.0)?); + if min_angle > max_angle { + return Err(bad(cmd, format!("`minAngle` ({min_angle}°) can't be more than `maxAngle` ({max_angle}°)"))); + } + Ok(Self { every, min_angle, max_angle }) + } + + /// Does it take corner `index` of `lc`? + fn takes(&self, lc: &LiveCorners, index: usize) -> bool { + self.every.takes(index) + && lc.corner(index).is_some_and(|c| (self.min_angle - ANGLE_SLACK..=self.max_angle + ANGLE_SLACK).contains(&c.angle_deg())) + } + + /// The error when it takes none of the chosen corners. + fn none(&self) -> String { + let at = self.every.at(); + if self.min_angle > 0.0 || self.max_angle < 180.0 { + format!("none of the chosen corners{at} has an angle from {}° to {}°", self.min_angle, self.max_angle) + } else if at.is_empty() { + NO_CORNER.into() + } else { + format!("none of the chosen corners is{at}") } } } /// The corners a request names: each path with the corners (anchor indices of its uncut outline) -/// that `every` takes. -fn named_corners(s: &Session, p: &Value, cmd: &str, every: Every) -> Result)>> { +/// that `pick` takes. +fn named_corners(s: &Session, p: &Value, cmd: &str, pick: Pick) -> Result)>> { let shared = anchors_param(p, cmd)?; // Each path with its own `anchors`, or sharing the request's. let mut own: Vec>> = vec![]; @@ -130,13 +185,13 @@ fn named_corners(s: &Session, p: &Value, cmd: &str, every: Every) -> Result st.selection.partial(*id).filter(|a| !a.is_empty()).map_or_else(|| lc.all(), |a| lc.corners_of(a)), }; chosen |= !corners.is_empty(); - let corners: BTreeSet = corners.into_iter().filter(|k| every.takes(*k)).collect(); + let corners: BTreeSet = corners.into_iter().filter(|k| pick.takes(&lc, *k)).collect(); if !corners.is_empty() { out.push((*id, corners)); } } if out.is_empty() { - return Err(bad(cmd, if chosen { every.none() } else { Every::All.none() })); + return Err(bad(cmd, if chosen { pick.none() } else { NO_CORNER.into() })); } Ok(out) } @@ -181,12 +236,12 @@ fn corner_set(s: &mut Session, p: &Value) -> Result { .map_err(|_| bad(C, format!("`kind` must be \"round\", \"invertedRound\" or \"chamfer\", not {v}"))) }) .transpose()?; - let every = Every::of(p, C)?; - let corners = named_corners(s, p, C, every)?; + let pick = Pick::of(p, C)?; + let corners = named_corners(s, p, C, pick)?; edit_corners(s, "Set Corners", corners, radius, kind) } fn corner_remove(s: &mut Session, p: &Value) -> Result { - let corners = named_corners(s, p, "addon.pathtools.cornerRemove", Every::All)?; + let corners = named_corners(s, p, "addon.pathtools.cornerRemove", Pick::ALL)?; edit_corners(s, "Remove Corners", corners, 0.0, Some(CornerKind::Round)) } diff --git a/crates/engine/src/cmd/addons/pathtools/tests.rs b/crates/engine/src/cmd/addons/pathtools/tests.rs index 33e7eff8ea..e31aadf56e 100644 --- a/crates/engine/src/cmd/addons/pathtools/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tests.rs @@ -654,6 +654,83 @@ fn corner_set_every_refuses_bad_values_and_says_when_nothing_is_left() { assert!(e.contains("two sides meet"), "{e}"); } +/// A closed house: a 100 × 100 square under a roof, its corners 90°, 90°, 135°, 90° and 135°. +fn house(s: &mut Session) -> NodeId { + line(s, &[(250.0, 100.0), (350.0, 100.0), (350.0, 200.0), (300.0, 250.0), (250.0, 200.0)], true) +} + +#[test] +fn corner_set_angle_range_rounds_only_the_corners_in_it_on_each_path() { + let mut s = session(); + // The star's points meet at about 38°, its inner corners at about 110°. + let (star, home) = (star_path(&mut s), house(&mut s)); + select(&mut s, &[star, home]); + let n = steps(&s); + // The sharp spikes only: the house has none, the star five, as one step. + let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 3, "maxAngle": 60})).unwrap(); + assert_eq!((r["ids"].clone(), r["corners"].clone(), steps(&s)), (json!([star.0]), json!(5), n + 1)); + assert_eq!((cut(&s, star), cut(&s, home)), (vec![0, 2, 4, 6, 8], vec![])); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((cut(&s, star), steps(&s)), (vec![], n)); + // Exactly 90°: the house's square corners. + s.execute("addon.pathtools.cornerSet", &json!({"radius": 3, "minAngle": 90, "maxAngle": 90})).unwrap(); + assert_eq!((cut(&s, star), cut(&s, home)), (vec![], vec![0, 1, 3])); + // 100° to 140°: the star's inner corners and the roof's; the square corners stay as they are. + let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 2, "minAngle": 100, "maxAngle": 140})).unwrap(); + assert_eq!(r["corners"], json!(7)); + assert_eq!((cut(&s, star), cut(&s, home)), (vec![1, 3, 5, 7, 9], vec![0, 1, 2, 3, 4])); + assert_eq!((drawn(&s, home, 0), drawn(&s, home, 2)), (3.0, 2.0)); + // On top of the named anchors and of `every`. + s.execute("addon.pathtools.cornerRemove", &json!({})).unwrap(); + s.execute("addon.pathtools.cornerSet", &json!({"ids": [home.0], "anchors": [1, 2, 3], "radius": 4, "minAngle": 80, "maxAngle": 100})).unwrap(); + assert_eq!(cut(&s, home), vec![1, 3]); + s.execute("addon.pathtools.cornerSet", &json!({"ids": [star.0], "radius": 4, "every": "even", "minAngle": 100})).unwrap(); + assert_eq!(cut(&s, star), vec![1, 3, 5, 7, 9]); +} + +#[test] +fn corner_set_angle_range_on_a_three_anchor_path() { + let mut s = session(); + // An open pen path of three anchors: one corner, of 90°. + let id = line(&mut s, &[(10.0, 10.0), (60.0, 60.0), (110.0, 10.0)], false); + select(&mut s, &[id]); + let e = s.execute("addon.pathtools.cornerSet", &json!({"radius": 5, "maxAngle": 45})).unwrap_err().to_string(); + assert!(e.contains("none of the chosen corners has an angle from 0° to 45°"), "{e}"); + let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 5, "minAngle": 80, "maxAngle": 100})).unwrap(); + assert_eq!(r["corners"], json!(1)); + assert_eq!(cut(&s, id), vec![1]); +} + +#[test] +fn corner_set_angle_range_refuses_bad_values_and_says_when_nothing_matches() { + let mut s = session(); + let star = star_path(&mut s); + select(&mut s, &[star]); + let i = star.0; + refuses( + &mut s, + "addon.pathtools.cornerSet", + &[ + json!({"ids": [i], "radius": 5, "minAngle": -1}), + json!({"ids": [i], "radius": 5, "maxAngle": 181}), + json!({"ids": [i], "radius": 5, "minAngle": 1e308}), + json!({"ids": [i], "radius": 5, "maxAngle": "sharp"}), + json!({"ids": [i], "radius": 5, "minAngle": 120, "maxAngle": 60}), + json!({"ids": [i], "radius": 5, "minAngle": 50, "maxAngle": 100}), + json!({"ids": [i], "radius": 5, "every": "odd", "minAngle": 100}), + ], + ); + let err = |s: &mut Session, p: Value| s.execute("addon.pathtools.cornerSet", &p).unwrap_err().to_string(); + let e = err(&mut s, json!({"ids": [i], "radius": 5, "maxAngle": 200})); + assert!(e.contains("`maxAngle` must be from 0 to 180 degrees"), "{e}"); + let e = err(&mut s, json!({"ids": [i], "radius": 5, "minAngle": 120, "maxAngle": 60})); + assert!(e.contains("`minAngle` (120°) can't be more than `maxAngle` (60°)"), "{e}"); + let e = err(&mut s, json!({"ids": [i], "radius": 5, "minAngle": 50, "maxAngle": 100})); + assert!(e.contains("none of the chosen corners has an angle from 50° to 100°"), "{e}"); + let e = err(&mut s, json!({"ids": [i], "radius": 5, "every": "odd", "minAngle": 100})); + assert!(e.contains("none of the chosen corners at an odd-numbered anchor (the 1st, 3rd, 5th…) has an angle from 100° to 180°"), "{e}"); +} + #[test] fn the_corner_tool_clicks_drags_and_removes_in_one_step_each() { let mut s = session(); diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 8d973f267d..b660831781 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -596,6 +596,9 @@ fn structured_junk() { ("addon.pathtools.cornerSet", json!({"ids": [2, 3], "radius": 5, "every": "odd"})), ("addon.pathtools.cornerSet", json!({"items": [{"id": 2, "anchors": [1, u64::MAX]}], "radius": 5, "every": "even"})), ("addon.pathtools.cornerSet", json!({"ids": [2], "radius": 5, "every": [1, "x", null]})), + ("addon.pathtools.cornerSet", json!({"ids": [2, 3], "radius": 5, "minAngle": 0, "maxAngle": 0})), + ("addon.pathtools.cornerSet", json!({"ids": [2], "radius": 5, "minAngle": 180, "maxAngle": 180, "every": "odd"})), + ("addon.pathtools.cornerSet", json!({"ids": [2], "radius": 5, "minAngle": f64::MAX, "maxAngle": -1e-300})), ("addon.pathtools.cornerRemove", json!({"ids": [0, 1, 2, 3, u64::MAX]})), ("addon.pathtools.cornerRemove", json!({"items": [{"id": 2, "anchors": [u64::MAX]}]})), ("addon.pathtools.slideAnchor", json!({"id": 2, "anchor": 1, "t": 0.98})), diff --git a/crates/ui-egui/src/addons/pathtools/corner.rs b/crates/ui-egui/src/addons/pathtools/corner.rs index 358e4f0b3d..36ee1bd1c9 100644 --- a/crates/ui-egui/src/addons/pathtools/corner.rs +++ b/crates/ui-egui/src/addons/pathtools/corner.rs @@ -1,6 +1,6 @@ //! The Anchor Inspector panel's Corners section: the Corner Tool's radius and kind, how many corners //! the selection holds, Apply (`addon.pathtools.cornerSet`) and Set Corners… (its dialog, which -//! can also take every other anchor). +//! can also take every other anchor, or only the corners in an angle range). use egui::Ui; use serde_json::{Value, json}; diff --git a/crates/ui-egui/src/addons/pathtools/set_corners.rs b/crates/ui-egui/src/addons/pathtools/set_corners.rs index 52800fed6b..59ba7035a2 100644 --- a/crates/ui-egui/src/addons/pathtools/set_corners.rs +++ b/crates/ui-egui/src/addons/pathtools/set_corners.rs @@ -1,6 +1,7 @@ -//! Set Corners in the interface: its dialog (radius, corner kind, and which anchors: all, the -//! odd-numbered or the even-numbered ones), which previews on the canvas and runs -//! `addon.pathtools.cornerSet` on OK, one undo step. It opens on the Corner Tool's radius and kind. +//! Set Corners in the interface: its dialog (radius, corner kind, which anchors: all, the +//! odd-numbered or the even-numbered ones, and the range of corner angles to round), which +//! previews on the canvas and runs `addon.pathtools.cornerSet` on OK, one undo step. It opens on +//! the Corner Tool's radius and kind, every corner angle (0° to 180°). use egui::Ui; use serde_json::{Value, json}; @@ -20,13 +21,16 @@ const KINDS: [(&str, &str); 3] = [("round", "Round"), ("invertedRound", "Inverte const EVERY: [(&str, &str); 3] = [("all", "All Anchors"), ("odd", "Odd-Numbered Anchors"), ("even", "Even-Numbered Anchors")]; const LABEL_W: f32 = 64.0; const FIELD_W: f32 = 170.0; +const ANGLE_W: f32 = 64.0; +/// The corner angles the command takes (degrees). +const ANGLES: std::ops::RangeInclusive = 0.0..=180.0; /// The dialog's fields to start with: the Corner Tool's radius and kind, every anchor, Preview on. pub(crate) fn fields(app: &VectorcraftApp) -> Value { let options = app.session.tool_options_of(ID); let radius = options["radius"].as_f64().unwrap_or(RADIUS); let kind = options["kind"].as_str().unwrap_or("round").to_string(); - json!({ "radius": radius, "kind": kind, "every": "all", "preview": true }) + json!({ "radius": radius, "kind": kind, "every": "all", "minAngle": 0.0, "maxAngle": 180.0, "preview": true }) } pub(crate) const SPEC: DialogSpec = @@ -39,6 +43,24 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { }); form::choice(ui, d, "kind", tl!("Corner:"), (LABEL_W, FIELD_W), &KINDS); form::choice(ui, d, "every", tl!("Anchors:"), (LABEL_W, FIELD_W), &EVERY); + // Only the corners whose sides meet at an angle in this range: small for a sharp spike, near + // 180° for a shallow bend. Typing one end past the other moves the other along. + let (min, max) = (d.f64("minAngle", 0.0), d.f64("maxAngle", 180.0)); + widgets::label_row(ui, tl!("Angle:"), LABEL_W, |ui| { + if let Some(v) = widgets::range_field_named(ui, "set-corners-min-angle", Some(tl!("Minimum angle")), min, ANGLES, "°", 1, ANGLE_W) { + d.fields.insert("minAngle".into(), json!(v)); + if v > max { + d.fields.insert("maxAngle".into(), json!(v)); + } + } + ui.label(tl!("to")); + if let Some(v) = widgets::range_field_named(ui, "set-corners-max-angle", Some(tl!("Maximum angle")), max, ANGLES, "°", 1, ANGLE_W) { + d.fields.insert("maxAngle".into(), json!(v)); + if v < min { + d.fields.insert("minAngle".into(), json!(v)); + } + } + }); form::preview(app, ui, d, "Set Corners", COMMAND, form::params(d)); false } @@ -98,4 +120,31 @@ mod tests { assert_eq!(app.session.doc().unwrap().history.undo.len(), n + 1); assert_eq!(cut(&app, id), vec![1, 3]); } + + #[test] + fn set_corners_previews_only_the_corners_in_its_angle_range() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + // A house: square corners at 0, 1 and 3, the roof's 135° corners at 2 and 4. + let anchors = json!([{"x": 0, "y": 0}, {"x": 100, "y": 0}, {"x": 100, "y": 100}, {"x": 50, "y": 150}, {"x": 0, "y": 100}]); + let id = app.run("path.create", json!({"anchors": anchors, "closed": true})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + menus::invoke(&mut app, super::COMMAND, json!({})); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in ["Angle:", "to", "0°", "180°"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + let n = app.session.doc().unwrap().history.undo.len(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("minAngle".into(), json!(120)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(cut(&app, id), vec![2, 4], "the roof previewed"); + app.ui.dialog.as_mut().unwrap().fields.insert("maxAngle".into(), json!(100)); + app.ui.dialog.as_mut().unwrap().fields.insert("minAngle".into(), json!(80)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(cut(&app, id), vec![0, 1, 3], "the square corners previewed"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.session.doc().unwrap().history.undo.len(), n + 1); + assert_eq!(cut(&app, id), vec![0, 1, 3]); + } } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 4c43cceb5c..8948a14828 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6201,3 +6201,5 @@ breakText Glyphs Глифи All Anchors Всички опорни точки Odd-Numbered Anchors Нечетни опорни точки Even-Numbered Anchors Четни опорни точки + Minimum angle Минимален ъгъл + Maximum angle Максимален ъгъл diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 611cc970c1..f6410a8274 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6235,3 +6235,5 @@ shape Open Otvoren All Anchors Sva sidra Odd-Numbered Anchors Neparna sidra Even-Numbered Anchors Parna sidra + Minimum angle Najmanji ugao + Maximum angle Najveći ugao diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 3c0158af29..afedb11f96 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6336,3 +6336,5 @@ breakText Glyphs Glifs All Anchors Tots els ancoratges Odd-Numbered Anchors Ancoratges senars Even-Numbered Anchors Ancoratges parells + Minimum angle Angle mínim + Maximum angle Angle màxim diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index f19c56d39b..fc3a7c5cc1 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6350,3 +6350,5 @@ breakText Glyphs Glyfy All Anchors Všechny kotevní body Odd-Numbered Anchors Liché kotevní body Even-Numbered Anchors Sudé kotevní body + Minimum angle Minimální úhel + Maximum angle Maximální úhel diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index e4c908156a..d58f0610b6 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6217,3 +6217,5 @@ breakText Glyphs Glyffer All Anchors Alle ankre Odd-Numbered Anchors Ulige ankre Even-Numbered Anchors Lige ankre + Minimum angle Mindste vinkel + Maximum angle Største vinkel diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 8e2e67985d..d88d86b5f4 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5936,3 +5936,5 @@ breakText Glyphs Glyphen All Anchors Alle Ankerpunkte Odd-Numbered Anchors Ungerade Ankerpunkte Even-Numbered Anchors Gerade Ankerpunkte + Minimum angle Minimaler Winkel + Maximum angle Maximaler Winkel diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index f05becf607..1c116fe3d6 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6302,3 +6302,5 @@ breakText Glyphs Γλύφοι All Anchors Όλα τα σημεία αγκύρωσης Odd-Numbered Anchors Μονά σημεία αγκύρωσης Even-Numbered Anchors Ζυγά σημεία αγκύρωσης + Minimum angle Ελάχιστη γωνία + Maximum angle Μέγιστη γωνία diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 074fccb606..d9bad3fc80 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6292,3 +6292,5 @@ breakText Glyphs Glifos All Anchors Todas las anclas Odd-Numbered Anchors Anclas impares Even-Numbered Anchors Anclas pares + Minimum angle Ángulo mínimo + Maximum angle Ángulo máximo diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 9651fdd43a..d66e806d8a 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6385,3 +6385,5 @@ breakText Glyphs Merkit All Anchors Kaikki ankkurit Odd-Numbered Anchors Parittomat ankkurit Even-Numbered Anchors Parilliset ankkurit + Minimum angle Pienin kulma + Maximum angle Suurin kulma diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 2cd0ae07c0..4ddf66a51c 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6345,3 +6345,5 @@ breakText Glyphs Glyphes All Anchors Tous les points d’ancrage Odd-Numbered Anchors Points d’ancrage impairs Even-Numbered Anchors Points d’ancrage pairs + Minimum angle Angle minimal + Maximum angle Angle maximal diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index a30e8e7949..b42cb25bbe 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6334,3 +6334,5 @@ breakText Glyphs Glifák All Anchors Összes horgonypont Odd-Numbered Anchors Páratlan horgonypontok Even-Numbered Anchors Páros horgonypontok + Minimum angle Legkisebb szög + Maximum angle Legnagyobb szög diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 678e3fb423..843de1391c 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6217,3 +6217,5 @@ breakText Glyphs Glif All Anchors Semua jangkar Odd-Numbered Anchors Jangkar bernomor ganjil Even-Numbered Anchors Jangkar bernomor genap + Minimum angle Sudut minimum + Maximum angle Sudut maksimum diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 9c92dc5e4c..2a90453d4d 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5970,3 +5970,5 @@ breakText Glyphs Glifi All Anchors Tutti gli ancoraggi Odd-Numbered Anchors Ancoraggi dispari Even-Numbered Anchors Ancoraggi pari + Minimum angle Angolo minimo + Maximum angle Angolo massimo diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c0ec9be3e2..a73e548d83 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -6035,3 +6035,5 @@ breakText Glyphs 字形 All Anchors すべてのアンカー Odd-Numbered Anchors 奇数番目のアンカー Even-Numbered Anchors 偶数番目のアンカー + Minimum angle 最小角度 + Maximum angle 最大角度 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index a643231056..78de8173fa 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6361,3 +6361,5 @@ font-script Japanese იაპონური All Anchors ყველა საყრდენი წერტილი Odd-Numbered Anchors კენტი საყრდენი წერტილები Even-Numbered Anchors ლუწი საყრდენი წერტილები + Minimum angle მინიმალური კუთხე + Maximum angle მაქსიმალური კუთხე diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index c31f973b26..aefbd17df5 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5931,3 +5931,5 @@ breakText Glyphs 글리프 All Anchors 모든 앵커 Odd-Numbered Anchors 홀수 번째 앵커 Even-Numbered Anchors 짝수 번째 앵커 + Minimum angle 최소 각도 + Maximum angle 최대 각도 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index f2a20670ea..dbb31fd127 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6261,3 +6261,5 @@ breakText Glyphs Glyphs All Anchors Alle ankerpunten Odd-Numbered Anchors Oneven ankerpunten Even-Numbered Anchors Even ankerpunten + Minimum angle Minimale hoek + Maximum angle Maximale hoek diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 80e3e3f1eb..88322303be 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -6205,3 +6205,5 @@ breakText Glyphs Glify All Anchors Wszystkie punkty Odd-Numbered Anchors Punkty nieparzyste Even-Numbered Anchors Punkty parzyste + Minimum angle Kąt minimalny + Maximum angle Kąt maksymalny diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index f9c911e855..0293e24e37 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6423,3 +6423,5 @@ swatch Yellow Green Verde-amarelado All Anchors Todas as Âncoras Odd-Numbered Anchors Âncoras Ímpares Even-Numbered Anchors Âncoras Pares + Minimum angle Ângulo Mínimo + Maximum angle Ângulo Máximo diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 9d80cb092a..9791fe1c38 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6439,3 +6439,5 @@ shape Open Открытый All Anchors Все опорные точки Odd-Numbered Anchors Нечётные опорные точки Even-Numbered Anchors Чётные опорные точки + Minimum angle Минимальный угол + Maximum angle Максимальный угол diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 8ee422b5c5..58f82f37bc 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6406,3 +6406,5 @@ digits Hindi Hindi All Anchors Alla ankare Odd-Numbered Anchors Udda ankare Even-Numbered Anchors Jämna ankare + Minimum angle Minsta vinkel + Maximum angle Största vinkel diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index e7d4b3ca1d..ae5a58dd6c 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6307,3 +6307,5 @@ breakText Glyphs Glifler All Anchors Tüm Çapalar Odd-Numbered Anchors Tek Numaralı Çapalar Even-Numbered Anchors Çift Numaralı Çapalar + Minimum angle En Küçük Açı + Maximum angle En Büyük Açı diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index e00c216d59..363a8f6fb9 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5950,3 +5950,5 @@ breakText Glyphs Гліфи All Anchors Усі опорні точки Odd-Numbered Anchors Непарні опорні точки Even-Numbered Anchors Парні опорні точки + Minimum angle Мінімальний кут + Maximum angle Максимальний кут diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index f026b728f7..2275c27d8d 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5951,3 +5951,5 @@ breakText Glyphs Glyph All Anchors Tất cả điểm neo Odd-Numbered Anchors Điểm neo số lẻ Even-Numbered Anchors Điểm neo số chẵn + Minimum angle Góc tối thiểu + Maximum angle Góc tối đa diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index ad37f23cf4..1d44f8cc6e 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -6191,3 +6191,5 @@ breakText Glyphs 字形 All Anchors 所有锚点 Odd-Numbered Anchors 奇数锚点 Even-Numbered Anchors 偶数锚点 + Minimum angle 最小角度 + Maximum angle 最大角度 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index d4805dd9b7..6d6b107519 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5988,3 +5988,5 @@ breakText Glyphs 字符 All Anchors 所有錨點 Odd-Numbered Anchors 奇數錨點 Even-Numbered Anchors 偶數錨點 + Minimum angle 最小角度 + Maximum angle 最大角度 diff --git a/docs/mcp.md b/docs/mcp.md index c4506fc83d..63f41074ca 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6627,7 +6627,7 @@ Commands: drawn, and the path's fills stay on it, below its dashes (a path without fills goes). A compound path's dashes are plain paths with its appearance. Paths without a dashed stroke stay as they are, and it is an error if none has one. The dashes are selected; more than 100,000 (or a pattern too fine to draw) is refused. → `{ids, dashes}`. -- `addon.pathtools.cornerSet {ids?, anchors?, items?, radius, kind?, every?}` cuts live corners, the ones Direct Selection's +- `addon.pathtools.cornerSet {ids?, anchors?, items?, radius, kind?, every?, minAngle?, maxAngle?}` cuts live corners, the ones Direct Selection's corner widgets and the Corners dialog edit, as one undo step. `ids` (default: the selection) are the paths and `anchors` the anchor indices of each path's outline with no corners cut; without `anchors`, a path's direct-selected anchors, or all of them. `items: [{id, anchors?}…]` gives each path its own instead. Only anchors where two sides meet @@ -6635,7 +6635,9 @@ Commands: 0 to 1,000,000 pt, drawn no larger than fits; `kind` is `round`, `invertedRound` or `chamfer` (default: each corner's own). `every` (`all`, `odd` or `even`; default `all`) keeps, of those anchors, only the odd- or even-numbered ones, counting each path's anchors from 1 (the 1st, 3rd, 5th… are odd): an anchor that takes no corner still counts, and it - is an error if none is left. Object › Plug-ins › Path Precision Tools › Set Corners… (also in the Anchor Inspector's + is an error if none is left. `minAngle` and `maxAngle` (degrees 0 to 180; default 0 and 180) keep only the corners + whose sides meet at an angle in that range (small for a sharp spike, near 180 for a shallow bend); `minAngle` can't + be more than `maxAngle`, and it is an error, saying so, if no chosen corner is in the range. Object › Plug-ins › Path Precision Tools › Set Corners… (also in the Anchor Inspector's Corners section) sets these with Preview. → `{ids, corners}`. - `addon.pathtools.cornerRemove {ids?, anchors?, items?}` makes those corners sharp again, as one undo step; a plain path with none left is plain again. → `{ids, corners}`. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index cbbb336c8b..2f851ca410 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -23,6 +23,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | Path Precision Tools add-on (a VectorCraft addition): Set Corners… and `addon.pathtools.cornerSet` `minAngle`/`maxAngle` round only the corners whose angle is in a range (#5545); evidence added; scores unchanged. | | 2026-11-04 | minor | Path Precision Tools add-on (a VectorCraft addition): Set Corners… and `addon.pathtools.cornerSet` `every` round all, the odd-numbered or the even-numbered anchors of each path (#5546); evidence added; scores unchanged. | | 2026-11-04 | minor | Transform Each's Scale has the documented Relative and Absolute radio buttons (`object.transformEach` `relative`: percentages of each object's size, or the width and height it becomes, measured on each object's own bounds) and the link that keeps the two scales in proportion; the panel lists Scale, Move, Rotate, the Options in two columns, the Reference Point and Preview (level with Copy, Cancel and OK) in the documented order. Scores and estimates unchanged. | | 2026-11-05 | minor | PDF import: a DeviceN gradient of a spot ink over process plates keeps the ink and the plates, and PDF export writes it as a DeviceN shading again (#3235); scores unchanged | @@ -1479,7 +1480,8 @@ drag sizes it (Shift: whole values), a cut corner's marker selects it and loads at 0 or on a double-click, a corner never grows past what fits, and an Alt-marquee cuts every eligible anchor inside. A Corners section in the Anchor Inspector sets the radius and kind, counts the selected corners and applies to them. Set Corners… (in the submenu and the Corners section) sets the radius and kind with Preview, on all the chosen anchors -or only the odd- or even-numbered ones (`every`, #5546). +or only the odd- or even-numbered ones (`every`, #5546), and only the corners whose angle is in a range +(`minAngle`/`maxAngle`, #5545). Slide Anchor Along Path drags an anchor along its curve, the two segments beside it refitted by the keep-shape kernel (Shift: where the tangent is a multiple of 45°). Commands `addon.pathtools.cornerSet`, `cornerRemove` and `slideAnchor`, each one undo step; `vectorcraft_pathops::addons::pathtools::slide_anchor`. Tests: `addons::pathtools` in diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 35bdd5d628..3bf5440192 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Gradient panel: Delete Stop beside the ramp, #5403; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Path Precision Tools: Set Corners… rounds only the corners in an angle range; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) ## Feature submission evidence @@ -381,7 +381,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Smart Pen add-on (VectorCraft addition): Object › Plug-ins › Smart Pen selects the Smart Pen Tool, which the All Tools drawer lists under its own heading but neither toolbar shows as shipped (no shortcut), and opens the Smart Pen panel (next segment straight or curved; Remove Points Keep Shape, Make Smooth, Make Corner, Retract Handles, Close or Join). The tool draws (click: straight or curved segment, a curve after a straight one tangent; drag: smooth anchor, Alt breaks the handle, Shift 45°, Space moves it; Tab switches a segment; rubber band; close, join, continue) and edits without switching tools (click selects a point, drag moves it, Alt-click removes it keeping the shape, Shift+Alt-click deletes it, double-click toggles smooth/corner; handle drags with Shift and Alt; segment drags reshape, Alt-click adds a point) | done | `addon.pen.*`, `crates/tools/src/addons/smart_pen.rs`, `crates/ui-egui/src/addons/pen.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its seven tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path, Shared Edge Merge Tool), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; the Shared Edge Merge Tool shows, over two paths touching at two coincident anchors, the two stretches and the edge merging them, a click merges them (half way; Shift the upper path, Alt the lower), and near anchors meet or an anchor one path lacks is added to match (Shift+Alt asks for this inside a stretch), with a Shared Edges section in the Anchor Inspector (brush diameter, coincidence 0 to 3 pt, Keep Shared Points Together, which takes coincident anchors along with the add-on's own anchor moves); a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Divide into Dashes… (Dash and Gap in any unit, Fit to Corners and Ends, Remove Gaps; Preview) cuts the selected paths, or only their direct-selected segments, into open pieces along the curve, keeping their appearance, one undo step | done | #4950; `addon.pathtools.divideDashes`, `crates/pathops/src/addons/pathtools/dashes.rs`, `crates/ui-egui/src/addons/pathtools/dashes.rs` and their tests; not a feature of the reference app, so it is not scored | -| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Set Corners… (also a button in the Anchor Inspector's Corners section: Radius in any unit, Corner kind, Anchors: All, Odd-Numbered or Even-Numbered, counted from each path's first anchor; Preview) cuts corners on the chosen anchors of every selected path, one undo step | done | #5546; `addon.pathtools.cornerSet` (`every`), `crates/ui-egui/src/addons/pathtools/set_corners.rs` and their tests; not a feature of the reference app, so it is not scored | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Set Corners… (also a button in the Anchor Inspector's Corners section: Radius in any unit, Corner kind, Anchors: All, Odd-Numbered or Even-Numbered, counted from each path's first anchor; Angle: from … to …°, only the corners whose sides meet at an angle in that range; Preview) cuts corners on the chosen anchors of every selected path, one undo step | done | #5546, #5545; `addon.pathtools.cornerSet` (`every`, `minAngle`, `maxAngle`), `crates/ui-egui/src/addons/pathtools/set_corners.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Expand Dashes into Paths turns each selected path's dashed stroke into separate open paths, one per dash, laid out as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off; one undo step | done | #4922; `addon.pathtools.expandDashes` (in `crates/engine/src/cmd/addons/pathtools.rs`, using the renderer's dash layout) and its tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Effect › Path Effects lists its live effects (Dashes to Geometry, Add Anchors, Extend Path, Close Path, Smooth Anchors, Retract Handles, Reverse Direction, Simplify Anchors, Split at Anchors), each with the effect dialog's live Preview except Reverse Direction, which has no options, and listed in the Appearance panel like any effect | done | `addon.path.*`, `crates/effects/src/addons/path.rs`, `crates/ui-egui/src/addons/pathtools.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its four tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/shape.rs` and their tests; not a feature of the reference app, so it is not scored | @@ -435,6 +435,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | Path Precision Tools add-on (a VectorCraft addition): Set Corners… rounds only the corners in an angle range (#5545); scores and estimates unchanged | | 2026-11-04 | minor | Path Precision Tools add-on (a VectorCraft addition): Set Corners… rounds all, the odd-numbered or the even-numbered anchors (#5546); scores and estimates unchanged | | 2026-11-04 | minor | New Document: the units chosen in Preset Details belong to the chosen document, as the pane's options are listed "for the selected preset" ([public source](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/create-and-save-custom-document-presets.html)); the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units (#2078); scores and estimates unchanged | | 2026-11-01 | minor | Object › Image Trace › Batch Trace Folder asks for a source and a destination folder and traces each image into it (#4921); scores and estimates unchanged | From 045030f444c322c79c041e6cd003c42efe40703f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 19:41:21 -0800 Subject: [PATCH 029/196] =?UTF-8?q?Preferences:=20Additional=20Plug-ins=20?= =?UTF-8?q?Folder=20gets=20Choose=E2=80=A6,=20and=20OK=20checks=20typed=20?= =?UTF-8?q?folders?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Additional Plug-ins Folder (Plug-ins & Scratch Disks) gets the Choose… button that Data Recovery's Folder has, on hosts with a folder picker. A picked plug-ins folder must be a folder whose contents can be listed; otherwise the status bar says why and the field keeps its value. OK now gives a folder typed into either field the same check as a picked one. When it fails, the dialog stays open, the status bar says why and no preference is set. An empty field and the folder already saved are not checked. Under automation roots, a folder outside them is refused before it is looked at. Additional Fonts Folder and Templates Folder stay typed only. --- crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.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/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/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/prefs_dialog.rs | 76 +++++++++++--- crates/ui-egui/src/prefs_dialog/tests.rs | 121 +++++++++++++++++++++-- docs/plugins.md | 3 +- docs/target-app-parity.md | 2 +- 25 files changed, 202 insertions(+), 21 deletions(-) diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 73df162e86..70c893f326 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5055,6 +5055,7 @@ digits Malayalam Malaiàlam @msg damaged malmès @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) La recuperació de dades no té cap lloc on guardar còpies: configureu Preferències → Gestió de fitxers → Recuperació de dades → Carpeta (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} La recuperació de dades no pot guardar còpies a {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} No es poden carregar complements des de {path}: {e} @msg data the program reads is damaged or cut short, or the program asks for a position in a file that has none les dades que llegeix el programa estan malmeses o tallades, o el programa demana una posició en un fitxer que no en té @msg decimals must be {_1}–{_2} (got {_3}) els decimals han de ser {_1}–{_2} (rebut {_3}) @msg Dimension point is outside the canvas El punt de dimensió és fora del llenç diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 084f68e32c..cac60a6482 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4292,6 +4292,7 @@ imageTrace Outline Obrys @msg Create from Selection: the selection has no area Vytvořit z výběru: výběr nemá žádnou plochu @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Obnovení dat nemá kam ukládat kopie: nastavte Předvolby → Práce se soubory → Obnovení dat → Složka (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Obnovení dat nemůže ukládat kopie do {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Zásuvné moduly nelze načíst z {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) nástrojem Přímý výběr vyberte kotevní body, kde se má cesta rozdělit (ne koncové body otevřených cest) @msg Divide Objects Below: select a path Rozdělit objekty pod: vyberte cestu @msg Divide Objects Below: select exactly one path Rozdělit objekty pod: vyberte právě jednu cestu diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 93c8f21d49..fea15fbe24 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3899,6 +3899,7 @@ theme Appearance Erscheinungsbild @msg Create from Selection: the selection has no area Aus Auswahl erstellen: Die Auswahl hat keine Fläche @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Die Datenwiederherstellung hat keinen Ort für ihre Kopien: Legen Sie Voreinstellungen → Dateihandhabung → Datenwiederherstellung → Ordner (recoveryFolder) fest @msg Data Recovery can't keep copies in {path}: {e} Die Datenwiederherstellung kann keine Kopien in {path} ablegen: {e} +@msg Plug-ins can't be loaded from {path}: {e} Aus {path} können keine Plug-ins geladen werden: {e} @msg direct-select anchor points to cut at (not the end points of open paths) wählen Sie mit der Direktauswahl die Ankerpunkte aus, an denen geschnitten werden soll (nicht die Endpunkte offener Pfade) @msg Divide Objects Below: select a path Darunterliegende Objekte aufteilen: Wählen Sie einen Pfad aus @msg Divide Objects Below: select exactly one path Darunterliegende Objekte aufteilen: Wählen Sie genau einen Pfad aus diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 9b0d4049d0..72684a9c6c 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2184,6 +2184,7 @@ axis Both Και τα δύο @msg Create from Selection: the selection has no area Δημιουργία από επιλογή: η επιλογή δεν έχει επιφάνεια @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Η ανάκτηση δεδομένων δεν διαθέτει θέση αποθήκευσης αντιγράφων: ορίστε Προτιμήσεις → Χειρισμός αρχείων → Ανάκτηση δεδομένων → Φάκελος (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Η ανάκτηση δεδομένων δεν μπορεί να αποθηκεύσει αντίγραφα στο {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Δεν είναι δυνατή η φόρτωση πρόσθετων από το {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) Επιλέξτε άμεσα τα σημεία αγκύρωσης όπου θα γίνει η αποκοπή (όχι τα τελικά σημεία ανοιχτών διαδρομών) @msg Divide Objects Below: select a path Διαίρεση αντικειμένων από κάτω: επιλέξτε μια διαδρομή @msg Divide Objects Below: select exactly one path Διαίρεση αντικειμένων από κάτω: επιλέξτε ακριβώς μία διαδρομή diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index cd98ba9ef5..caf2b7b054 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3984,6 +3984,7 @@ axis Both Ambos @msg Create from Selection: the selection has no area Crear a partir de la selección: la selección no tiene área @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Recuperación de datos no tiene dónde guardar copias: configura Preferencias → Manejo de archivos → Recuperación de datos → Carpeta (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Recuperación de datos no puede guardar copias en {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} No se pueden cargar plugins desde {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) selecciona con Selección directa los puntos de ancla en los que cortar (no los puntos finales de trazados abiertos) @msg Divide Objects Below: select a path Dividir objetos inferiores: selecciona un trazado @msg Divide Objects Below: select exactly one path Dividir objetos inferiores: selecciona exactamente un trazado diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index ea55b031d3..73a7465a8c 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4206,6 +4206,7 @@ imageTrace Outline Ääriviiva @msg Create from Selection: the selection has no area Luo valinnasta: valinnalla ei ole pinta-alaa @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Tietojen palautuksella ei ole paikkaa kopioille: määritä Asetukset → Tiedostojen käsittely → Tietojen palautus → Kansio (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Tietojen palautus ei voi tallentaa kopioita kansioon {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Laajennuksia ei voi ladata kansiosta {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) valitse suoravalinnalla ankkuripisteet, joista leikataan (ei avoimien polkujen päätepisteitä) @msg Divide Objects Below: select a path Jaa alla olevat objektit: valitse polku @msg Divide Objects Below: select exactly one path Jaa alla olevat objektit: valitse tasan yksi polku diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 0ed2c4d718..8aa5fa1e90 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3974,6 +3974,7 @@ axis Both Les deux @msg Create from Selection: the selection has no area Créer d’après la sélection : la sélection n’a pas de surface @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) La récupération des données n’a aucun emplacement où conserver les copies : définissez Préférences → Gestion des fichiers → Récupération des données → Dossier (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} La récupération des données ne peut pas conserver de copies dans {path} ({e}) +@msg Plug-ins can't be loaded from {path}: {e} Impossible de charger les plug-ins depuis {path} ({e}) @msg direct-select anchor points to cut at (not the end points of open paths) sélectionnez avec l’outil Sélection directe les points d’ancrage où couper (pas les extrémités des tracés ouverts) @msg Divide Objects Below: select a path Diviser les objets inférieurs : sélectionnez un tracé @msg Divide Objects Below: select exactly one path Diviser les objets inférieurs : sélectionnez exactement un tracé diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index a6cef2de64..2137addf13 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4775,6 +4775,7 @@ imageTrace Outline Körvonal @msg damaged sérült @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Az adat-helyreállításnak nincs hova mentenie a másolatokat: állítsd be a Beállítások → Fájlkezelés → Adat-helyreállítás → Mappa értéket (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Az adat-helyreállítás nem tud másolatokat menteni ide: {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Innen nem tölthetők be bővítmények: {path}: {e} @msg decimals must be {_1}–{_2} (got {_3}) a tizedesjegyek száma {_1}–{_2} lehet (kapott érték: {_3}) @msg direct-select anchor points to cut at (not the end points of open paths) jelöld ki közvetlen kijelöléssel a vágási horgonypontokat (nyitott útvonal végpontja nem lehet) @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Elvetett helyreállított dokumentumok: {n} diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index d41988a0c8..d3add5036c 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4026,6 +4026,7 @@ axis Both Entrambi @msg Create from Selection: the selection has no area Crea da selezione: la selezione non ha area @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Il recupero dati non ha dove conservare le copie: imposta Preferenze → Gestione file → Recupero dati → Cartella (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Il recupero dati non può conservare copie in {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Impossibile caricare plug-in da {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) seleziona con Selezione diretta i punti di ancoraggio in cui tagliare (non i punti finali dei tracciati aperti) @msg Divide Objects Below: select a path Dividi oggetti sottostanti: seleziona un tracciato @msg Divide Objects Below: select exactly one path Dividi oggetti sottostanti: seleziona esattamente un tracciato diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 12a4442305..3533338d7a 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4321,6 +4321,7 @@ swatch Bright Violet ビビッドバイオレット @msg unknown preference `{key}` `{key}` は不明な環境設定の項目です @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) データ復帰のコピーを保存する場所がありません: 環境設定 → ファイル管理 → データ復帰 → フォルダー (recoveryFolder) を設定してください @msg Data Recovery can't keep copies in {path}: {e} データ復帰は {path} にコピーを保存できません: {e} +@msg Plug-ins can't be loaded from {path}: {e} {path} からプラグインを読み込めません: {e} @msg `{area}` is no recovery area name `{area}` は復帰用領域の名前として使えません @msg `{name}` is no recovery entry name `{name}` は復帰用エントリの名前として使えません @msg no clock to keep a heartbeat by ハートビートの記録に必要な時刻を取得できません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 2c89b17ee3..cc96a111cb 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3771,6 +3771,7 @@ font-technology Variable ცვლადი @msg Create from Selection: the selection has no area მონიშნულიდან შექმნა: მონიშნულს ფართობი არ აქვს @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) მონაცემთა აღდგენას ასლების შესანახი ადგილი არ აქვს: მიუთითეთ პარამეტრები → ფაილების დამუშავება → მონაცემთა აღდგენა → საქაღალდე (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} მონაცემთა აღდგენა ვერ ინახავს ასლებს აქ: {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} პლაგინების ჩატვირთვა ვერ ხერხდება აქედან: {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) პირდაპირი მონიშვნით მონიშნეთ საყრდენი წერტილები, სადაც გაიჭრება (არა ღია ტრაექტორიების ბოლო წერტილები) @msg Divide Objects Below: select a path ქვედა ობიექტების დაყოფა: მონიშნეთ ტრაექტორია @msg Divide Objects Below: select exactly one path ქვედა ობიექტების დაყოფა: მონიშნეთ ზუსტად ერთი ტრაექტორია diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 979fdefec2..1ac6fdc758 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4248,6 +4248,7 @@ theme Appearance 외관 @msg unknown preference `{key}` 알 수 없는 환경 설정 `{key}` @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) 데이터 복구에 복사본을 보관할 곳이 없습니다. 환경 설정 → 파일 처리 → 데이터 복구 → 폴더(recoveryFolder)를 지정하세요 @msg Data Recovery can't keep copies in {path}: {e} 데이터 복구가 {path}에 복사본을 보관할 수 없습니다: {e} +@msg Plug-ins can't be loaded from {path}: {e} {path}에서 플러그인을 불러올 수 없습니다: {e} @msg `{area}` is no recovery area name `{area}`은(는) 복구 영역 이름이 아닙니다 @msg `{name}` is no recovery entry name `{name}`은(는) 복구 항목 이름이 아닙니다 @msg no clock to keep a heartbeat by 하트비트를 유지할 시계가 없습니다 diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 82b042541d..da7f069e60 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4115,6 +4115,7 @@ imageTrace Outline Kontur @msg Create from Selection: the selection has no area Utwórz z zaznaczenia: zaznaczenie nie ma powierzchni @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Odzyskiwanie danych nie ma gdzie przechowywać kopii: ustaw Preferencje → Obsługa plików → Odzyskiwanie danych → Folder (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Odzyskiwanie danych nie może przechowywać kopii w {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Nie można wczytać wtyczek z {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) zaznacz bezpośrednio punkty kontrolne, w których ma nastąpić cięcie (nie punkty końcowe otwartych ścieżek) @msg Divide Objects Below: select a path Podziel obiekty poniżej: zaznacz ścieżkę @msg Divide Objects Below: select exactly one path Podziel obiekty poniżej: zaznacz dokładnie jedną ścieżkę diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 245d237753..4e05fc1eeb 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3573,6 +3573,7 @@ axis Both Ambos @msg Create from Selection: the selection has no area Criar a partir da seleção: a seleção não tem área @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) A recuperação de dados não tem onde guardar cópias: defina Preferências → Manipulação de arquivos → Recuperação de dados → Pasta (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} A recuperação de dados não pode guardar cópias em {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Não é possível carregar plug-ins de {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) selecione diretamente os pontos de ancoragem onde cortar (não as extremidades de traçados abertos) @msg Divide Objects Below: select a path Dividir objetos abaixo: selecione um traçado @msg Divide Objects Below: select exactly one path Dividir objetos abaixo: selecione exatamente um traçado diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index f49a5f68b6..60dcc9e321 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4021,6 +4021,7 @@ axis Both Оба @msg Create from Selection: the selection has no area Создание из выделения: у выделения нет области @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Восстановлению данных негде хранить копии: задайте Настройки → Работа с файлами → Восстановление данных → Папка (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Восстановление данных не может хранить копии в {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Не удается загрузить модули из {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) выделите прямым выделением опорные точки для разреза (не конечные точки открытых контуров) @msg Divide Objects Below: select a path Разделение объектов ниже: выделите контур @msg Divide Objects Below: select exactly one path Разделение объектов ниже: выделите ровно один контур diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 0588ec2617..7a26b4d02f 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3895,6 +3895,7 @@ axis Both Båda @msg Create from Selection: the selection has no area Skapa från markering: markeringen har ingen area @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Dataåterställning har ingenstans att spara kopior: ange Inställningar → Filhantering → Dataåterställning → Mapp (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Dataåterställning kan inte spara kopior i {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Det går inte att läsa in plugin-program från {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) direktmarkera ankarpunkter att klippa vid (inte slutpunkterna på öppna banor) @msg Divide Objects Below: select a path Dela objekt under: markera en bana @msg Divide Objects Below: select exactly one path Dela objekt under: markera exakt en bana diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index f0ae591f4e..f50913c3ed 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3779,6 +3779,7 @@ axis Both Her İkisi @msg Create from Selection: the selection has no area Seçimden Oluştur: Seçimin alanı yok @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Veri Kurtarma'nın kopyaları saklayacak yeri yoktur: Tercihleri ayarlayın → Dosya İşleme → Veri Kurtarma → Klasör (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Veri Kurtarma kopyaları {path} konumunda saklayamıyor: {e} +@msg Plug-ins can't be loaded from {path}: {e} Eklentiler {path} konumundan yüklenemiyor: {e} @msg direct-select anchor points to cut at (not the end points of open paths) kesilecek bağlantı noktalarını doğrudan seçin (açık yolların bitiş noktalarını değil) @msg Divide Objects Below: select a path Aşağıdaki Nesneleri Böl: bir yol seçin @msg Divide Objects Below: select exactly one path Aşağıdaki Nesneleri Böl: tam olarak bir yol seçin diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 109a591763..35b806a1f4 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4010,6 +4010,7 @@ axis Both Обидві @msg Create from Selection: the selection has no area Створення з виділення: виділення немає області @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Відновлення даних ніде зберігати копії: задайте Установки → Робота з файлами → Відновлення даних → Папка (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Відновлення даних не може зберігати копії в {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Не вдається завантажити модулі з {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) виділіть прямим виділенням опорні точки для розрізу (не кінцеві точки відкритих контурів) @msg Divide Objects Below: select a path Поділ об’єктів нижче: виділіть контур @msg Divide Objects Below: select exactly one path Поділ об’єктів нижче: виділіть рівно один контур diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 07ecd390eb..bae63ccf83 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4427,6 +4427,7 @@ theme Appearance Giao diện @msg damaged bị hỏng @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Phục hồi dữ liệu không có nơi lưu bản sao: đặt Tùy chọn → Xử lý tệp → Phục hồi dữ liệu → Thư mục (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Phục hồi dữ liệu không thể lưu bản sao vào {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Không thể tải plug-in từ {path}: {e} @msg decimals must be {_1}–{_2} (got {_3}) số thập phân phải từ {_1}–{_2} (nhận được {_3}) @msg direct-select anchor points to cut at (not the end points of open paths) chọn trực tiếp các điểm neo để cắt (không phải điểm cuối của đường dẫn mở) @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Đã loại bỏ {n} tài liệu đã phục hồi diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index be24cce506..c5004c3670 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4047,6 +4047,7 @@ imageTrace Outline 轮廓 @msg unknown preference `{key}` 未知首选项 `{key}` @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) 数据恢复没有可保存副本的位置:请设置“首选项 → 文件处理 → 数据恢复 → 文件夹” (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} 数据恢复无法将副本保存到 {path}:{e} +@msg Plug-ins can't be loaded from {path}: {e} 无法从 {path} 载入增效工具:{e} @msg `{area}` is no recovery area name `{area}` 不是恢复区域名称 @msg `{name}` is no recovery entry name `{name}` 不是恢复条目名称 @msg no clock to keep a heartbeat by 没有可用于维持心跳的时钟 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 777873899f..e42ab765b5 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1933,6 +1933,7 @@ file-filter Templates 範本 @msg unknown preference `{key}` 未知的偏好設定 `{key}` @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) 「資料復原」沒有可存放拷貝的位置:請設定「偏好設定 → 檔案處理 → 資料復原 → 資料夾」 (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} 「資料復原」無法將拷貝存放到 {path}:{e} +@msg Plug-ins can't be loaded from {path}: {e} 無法從 {path} 載入增效模組:{e} @msg `{area}` is no recovery area name `{area}` 不是復原區域名稱 @msg `{name}` is no recovery entry name `{name}` 不是復原項目名稱 @msg no clock to keep a heartbeat by 沒有可用來維持心跳的時鐘 diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index ba00aabbf5..49f14f281b 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -40,6 +40,7 @@ pub fn confirm(app: &mut VectorcraftApp) -> Result { let Some(d) = app.ui.dialog.clone() else { return Err("no dialog open".into()) }; let values: Map = d.fields.iter().filter(|(k, _)| !k.starts_with("__")).map(|(k, v)| (k.clone(), v.clone())).collect(); let touch_ws = values.get("touchWorkspace").and_then(Value::as_bool); + check_typed_folders(app, &values)?; app.run("prefs.set", json!({ "values": values }))?; if touch_ws.is_some() { crate::workspaces::sync_touch_workspace(app, app.touch_screen); @@ -386,16 +387,17 @@ fn category_fields(ui: &mut egui::Ui, app: &mut VectorcraftApp, d: &mut Dialog, } }); } - // File Handling › Data Recovery › Folder: typed, or picked with Choose… where the host - // has a folder picker (not on the web). - PrefKind::Text if sp.key == "recoveryFolder" => { + // File Handling › Data Recovery › Folder and Plug-ins & Scratch Disks › Additional + // Plug-ins Folder: typed, or picked with Choose… where the host has a folder picker + // (not on the web). + PrefKind::Text if folder_check(sp.key).is_some() => { labeled(ui, sp.label, |ui| { let mut s = v.as_str().unwrap_or("").to_string(); if ui.add(egui::TextEdit::singleline(&mut s).align(egui::Align2::LEFT_CENTER).desired_width(200.0)).changed() { d.fields.insert(sp.key.into(), json!(s)); } if app.services.pick_folder.is_some() && ui.button(tl!("Choose…")).clicked() { - choose_recovery_folder(app, d); + choose_folder(app, d, sp.key); } }); } @@ -411,15 +413,30 @@ fn category_fields(ui: &mut egui::Ui, app: &mut VectorcraftApp, d: &mut Dialog, } } -/// Data Recovery › Choose…: the folder picked becomes the Folder field's value when a folder can be -/// made in it. Otherwise the status bar says why and the field keeps its value, as it does when -/// the picker is canceled. The answer fills the field even when the active document closed while -/// the picker was open. -fn choose_recovery_folder(app: &mut VectorcraftApp, d: &mut Dialog) { - let r = crate::picks::in_app_dialog(app, d, |app, d| { +/// A check of a folder path: `Err` says why the folder can't be the preference's value. +type FolderCheck = fn(&str) -> Result<(), String>; + +/// The check a folder preference with a Choose… button gives a folder before it becomes the +/// preference's value: Data Recovery keeps its copies in its folder, and the Additional Plug-ins +/// Folder is read for plug-ins. `None` for any other preference. +fn folder_check(key: &str) -> Option { + match key { + "recoveryFolder" => Some(writable_folder), + "pluginsFolder" => Some(plugins_folder), + _ => None, + } +} + +/// Choose… beside the folder preference `key`: the folder picked becomes the field's value when it +/// passes the preference's [`folder_check`]. Otherwise the status bar says why and the field keeps +/// its value, as it does when the picker is canceled. The answer fills the field even when the +/// active document closed while the picker was open. +fn choose_folder(app: &mut VectorcraftApp, d: &mut Dialog, key: &'static str) { + let Some(check) = folder_check(key) else { return }; + let r = crate::picks::in_app_dialog(app, d, move |app, d| { let Some(path) = crate::picks::folder(app) else { return Ok(()) }; - writable_folder(&path)?; - d.fields.insert("recoveryFolder".into(), json!(path)); + check(&path)?; + d.fields.insert(key.into(), json!(path)); Ok(()) }); if let Err(e) = r { @@ -427,10 +444,43 @@ fn choose_recovery_folder(app: &mut VectorcraftApp, d: &mut Dialog) { } } +/// OK's check of the folder preferences with a Choose… button: a folder typed into one of their +/// fields gets the same [`folder_check`] as a picked one. An empty field (the default folder) and +/// a folder the preference already holds are not checked. The web has no folders to check. +fn check_typed_folders(app: &VectorcraftApp, fields: &Map) -> Result<(), String> { + if cfg!(target_arch = "wasm32") { + return Ok(()); + } + let saved = app.session.prefs.to_json(); + for (key, v) in fields { + let (Some(check), Some(path)) = (folder_check(key), v.as_str()) else { continue }; + let path = path.trim(); + if path.is_empty() || saved[key.as_str()].as_str().is_some_and(|s| s.trim() == path) { + continue; + } + check(path)?; + } + Ok(()) +} + +/// `Ok` when `path` is a folder whose contents can be listed, as the plug-ins in it are found by +/// listing it. A folder outside the automation roots in force is refused before it is looked at. +fn plugins_folder(path: &str) -> Result<(), String> { + vectorcraft_engine::file_access::check_read(path)?; + let dir = std::path::Path::new(path); + if !dir.is_dir() { + return Err(format!("{path} is not a folder")); + } + std::fs::read_dir(dir).map(drop).map_err(|e| format!("Plug-ins can't be loaded from {path}: {e}")) +} + /// `Ok` when `path` is a folder that can be listed and that a folder can be created in, as the /// recovery store lists its folders there and makes its own: the folder is listed, and an empty -/// folder is made there and removed. A folder that can't be removed again is an error too. +/// folder is made there and removed. A folder that can't be removed again is an error too. A +/// folder outside the automation roots in force is refused before it is looked at. fn writable_folder(path: &str) -> Result<(), String> { + vectorcraft_engine::file_access::check_write(path)?; + vectorcraft_engine::file_access::check_read(path)?; let dir = std::path::Path::new(path); if !dir.is_dir() { return Err(format!("{path} is not a folder")); diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index ff5dcbca7b..75a165674f 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -458,12 +458,12 @@ fn a_chosen_recovery_folder_fills_the_field_and_cancel_keeps_it() { let answer = picked.clone(); a.services.pick_folder = Some(Box::new(move || Some(answer.clone()))); let mut d = a.ui.dialog.clone().unwrap(); - choose_recovery_folder(&mut a, &mut d); + choose_folder(&mut a, &mut d, "recoveryFolder"); assert_eq!(d.str("recoveryFolder"), picked); assert!(a.ui.status.is_empty(), "{}", a.ui.status); assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "the write check leaves nothing behind"); a.services.pick_folder = Some(Box::new(|| None)); - choose_recovery_folder(&mut a, &mut d); + choose_folder(&mut a, &mut d, "recoveryFolder"); assert_eq!(d.str("recoveryFolder"), picked, "cancel keeps the field"); a.ui.dialog = Some(d); confirm(&mut a).unwrap(); @@ -486,7 +486,7 @@ fn a_recovery_folder_that_cannot_be_written_is_refused() { let answer = path.to_string_lossy().into_owned(); a.services.pick_folder = Some(Box::new(move || Some(answer.clone()))); a.ui.status.clear(); - choose_recovery_folder(&mut a, &mut d); + choose_folder(&mut a, &mut d, "recoveryFolder"); assert_eq!(d.str("recoveryFolder"), "kept"); assert_eq!(a.ui.status, format!("{} is not a folder", path.to_string_lossy())); } @@ -501,7 +501,7 @@ fn a_recovery_folder_that_cannot_be_written_is_refused() { let answer = locked.to_string_lossy().into_owned(); a.services.pick_folder = Some(Box::new(move || Some(answer.clone()))); a.ui.status.clear(); - choose_recovery_folder(&mut a, &mut d); + choose_folder(&mut a, &mut d, "recoveryFolder"); assert_eq!(d.str("recoveryFolder"), "kept"); assert!(a.ui.status.starts_with("Data Recovery can't keep copies in "), "{}", a.ui.status); } @@ -515,7 +515,7 @@ fn a_recovery_folder_that_cannot_be_written_is_refused() { let answer = unlisted.to_string_lossy().into_owned(); a.services.pick_folder = Some(Box::new(move || Some(answer.clone()))); a.ui.status.clear(); - choose_recovery_folder(&mut a, &mut d); + choose_folder(&mut a, &mut d, "recoveryFolder"); assert_eq!(d.str("recoveryFolder"), "kept"); assert!(a.ui.status.starts_with("Data Recovery can't keep copies in "), "{}", a.ui.status); } @@ -535,7 +535,7 @@ fn a_chosen_recovery_folder_fills_the_field_after_the_active_document_closes() { a.run("file.new", json!({"width": 100, "height": 80})).unwrap(); open(&mut a, Some("File Handling")); let mut d = a.ui.dialog.take().unwrap(); - choose_recovery_folder(&mut a, &mut d); + choose_folder(&mut a, &mut d, "recoveryFolder"); a.ui.dialog = Some(d); assert!(matches!(shown.requests().as_slice(), [crate::picks::PickRequest::Folder])); a.session.execute("file.close", &json!({})).unwrap(); @@ -546,3 +546,112 @@ fn a_chosen_recovery_folder_fills_the_field_after_the_active_document_closes() { assert_eq!(a.ui.dialog.as_ref().unwrap().str("recoveryFolder"), picked, "{}", a.ui.status); let _ = std::fs::remove_dir_all(&dir); } + +/// Plug-ins & Scratch Disks › Additional Plug-ins Folder has a Choose… button where the host has a +/// folder picker, and none where it has not (the web). +#[test] +fn plugins_folder_has_a_choose_button_with_a_folder_picker() { + let mut a = VectorcraftApp::new(Session::new(), Default::default()); + a.services.pick_folder = Some(Box::new(|| None)); + open(&mut a, Some("Plug-ins & Scratch Disks")); + let text = crate::tests_labels::painted_text(&mut a, |a, ui| show(a, ui.ctx())); + assert!(text.contains("Additional Plug-ins Folder") && text.contains("Choose…"), "{text}"); + a.services.pick_folder = None; + let text = crate::tests_labels::painted_text(&mut a, |a, ui| show(a, ui.ctx())); + assert!(text.contains("Additional Plug-ins Folder") && !text.contains("Choose…"), "{text}"); +} + +/// Choose… beside Additional Plug-ins Folder puts the folder picked into the field, and OK saves +/// it; a canceled picker, a file and a missing folder leave the field as it was. +#[test] +fn a_chosen_plugins_folder_fills_the_field_and_others_keep_it() { + let dir = temp_folder("plugins-chosen"); + let file = dir.join("not-a-folder.txt"); + std::fs::write(&file, b"x").unwrap(); + let mut a = VectorcraftApp::new(Session::new(), Default::default()); + open(&mut a, Some("Plug-ins & Scratch Disks")); + let mut d = a.ui.dialog.clone().unwrap(); + for path in [file.clone(), dir.join("missing")] { + let answer = path.to_string_lossy().into_owned(); + a.services.pick_folder = Some(Box::new(move || Some(answer.clone()))); + a.ui.status.clear(); + choose_folder(&mut a, &mut d, "pluginsFolder"); + assert_eq!(d.str("pluginsFolder"), ""); + assert_eq!(a.ui.status, format!("{} is not a folder", path.to_string_lossy())); + } + let picked = dir.to_string_lossy().into_owned(); + let answer = picked.clone(); + a.services.pick_folder = Some(Box::new(move || Some(answer.clone()))); + a.ui.status.clear(); + choose_folder(&mut a, &mut d, "pluginsFolder"); + assert_eq!(d.str("pluginsFolder"), picked); + assert!(a.ui.status.is_empty(), "{}", a.ui.status); + a.services.pick_folder = Some(Box::new(|| None)); + choose_folder(&mut a, &mut d, "pluginsFolder"); + assert_eq!(d.str("pluginsFolder"), picked, "cancel keeps the field"); + a.ui.dialog = Some(d); + confirm(&mut a).unwrap(); + assert_eq!(a.session.prefs.plugins_folder, picked); + let _ = std::fs::remove_dir_all(&dir); +} + +/// OK checks a folder typed into Data Recovery › Folder or Additional Plug-ins Folder as Choose… +/// checks a picked one: one that fails keeps the dialog open and changes no preference. An empty +/// field and a folder the preference already holds are not checked. +#[test] +fn ok_refuses_a_typed_folder_that_choose_would_refuse() { + let dir = temp_folder("typed-folders"); + let file = dir.join("not-a-folder.txt"); + std::fs::write(&file, b"x").unwrap(); + let missing = dir.join("missing").to_string_lossy().into_owned(); + for key in ["recoveryFolder", "pluginsFolder"] { + let mut a = VectorcraftApp::new(Session::new(), Default::default()); + open(&mut a, Some("File Handling")); + let before = a.session.prefs.to_json(); + for path in [file.to_string_lossy().into_owned(), missing.clone()] { + let d = a.ui.dialog.as_mut().unwrap(); + d.fields.insert(key.into(), json!(path)); + d.fields.insert("showToolTips".into(), json!(!a.session.prefs.show_tool_tips)); + assert_eq!(confirm(&mut a), Err(format!("{path} is not a folder")), "{key}"); + assert!(a.ui.dialog.is_some(), "{key}: the dialog stays open"); + assert_eq!(a.session.prefs.to_json(), before, "{key}: no preference changes"); + } + // A typed folder that passes is saved, with the spaces around it as typed. + let typed = format!(" {} ", dir.to_string_lossy()); + a.ui.dialog.as_mut().unwrap().fields.insert(key.into(), json!(typed)); + confirm(&mut a).unwrap(); + assert_eq!(a.session.prefs.to_json()[key], json!(typed), "{key}"); + // An empty field keeps the default folder. + open(&mut a, Some("File Handling")); + a.ui.dialog.as_mut().unwrap().fields.insert(key.into(), json!("")); + confirm(&mut a).unwrap(); + assert_eq!(a.session.prefs.to_json()[key], json!(""), "{key}"); + // A folder already saved is not checked again, so OK works while it is unavailable. + a.run("prefs.set", json!({"key": key, "value": missing})).unwrap(); + open(&mut a, Some("File Handling")); + a.ui.dialog.as_mut().unwrap().fields.insert("showToolTips".into(), json!(!a.session.prefs.show_tool_tips)); + confirm(&mut a).unwrap(); + assert_eq!(a.session.prefs.to_json()[key], json!(missing), "{key}"); + } + let _ = std::fs::remove_dir_all(&dir); +} + +/// Under automation roots, OK refuses a typed folder outside them before it looks at the folder. +#[test] +fn ok_refuses_a_typed_folder_outside_the_automation_roots_before_looking_at_it() { + use vectorcraft_engine::file_access::{self, Access}; + let dir = temp_folder("typed-roots"); + let inside = dir.join("inside"); + std::fs::create_dir_all(&inside).unwrap(); + let outside = dir.join("outside-missing").to_string_lossy().into_owned(); + let roots = file_access::AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap().unwrap(); + for (key, access) in [("recoveryFolder", Access::Write), ("pluginsFolder", Access::Read)] { + let mut a = VectorcraftApp::new(Session::new(), Default::default()); + open(&mut a, Some("File Handling")); + a.ui.dialog.as_mut().unwrap().fields.insert(key.into(), json!(outside)); + let r = file_access::confine(Some(&roots), || confirm(&mut a)); + assert_eq!(r, Err(roots.check(&outside, access).unwrap_err()), "{key}"); + assert!(a.ui.dialog.is_some(), "{key}: the dialog stays open"); + } + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/docs/plugins.md b/docs/plugins.md index cd867d53ed..bdd02b6f64 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -51,7 +51,8 @@ background ([below](#heavy-filters)). **Preference folder.** Edit › Preferences › Plug-ins & Scratch Disks › *Additional Plug-ins Folder*: when set, every `*.wasm` in that folder (not recursive) is installed at startup and whenever the preference changes (desktop builds; -the web build installs from bytes). +the web build installs from bytes). On the desktop, Choose… beside the field picks the folder; the dialog refuses a +picked or typed folder whose contents can't be listed. Plug-ins are installed **per process**, not per document. Documents store a live effect as an ordinary effect record (`{"id": "plugin.", "params": {…}}`): while the plug-in is installed it is drawn, exported and expanded; without it diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2166985548..27a6035895 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1144,7 +1144,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur PDF export writes a linear or radial gradient that mixes a spot color with process colors, or two spot colors, as a DeviceN shading of the spot inks and the process inks its stops use, so each spot ink prints on its own plate; an off-center midpoint is written as a stop with the inks halfway between its two stops. A gradient that mixes a spot color with RGB or Lab colors is still written without the spot ink, with a warning. A Perceptual gradient of spot inks is written as a Separation or DeviceN shading of the stops on its curve; a dithered gradient fill, and a Perceptual gradient with RGB or Lab stops other than white or more than 4,096 stops on its curve, are written as images in process colors, with a warning. A Lab spot color in such a shading is named by the same Separation space, with the Lab alternate, as its flat fills (`engine/src/tests/linked_stops.rs`, `engine/src/tests/labspots.rs`). PDF export writes a spot color named All or None (in a Separation space, the names of every plate and of no plate: [ISO 32000-1:2008](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf), 8.6.6.4) as the ink All Spot or None Spot (All Spot 2 and on when a spot swatch already has that name) in its fills, strokes, gradients, colorized images and Lab alternates; Registration still prints on every plate (`pdf/src/tests/output.rs`). - `.vectorcraft` (lossless JSON, compressed, atomic saves, save down to v1), Save As with a format chooser, Save a Copy, Revert, templates, Data Recovery after a crash (browser tabs hold their copies with Web Locks too, so a background tab's copies are never taken for a crash's, and a tab repairs copies another removed when it resumes: #367), background save and export. The desktop app writes its warnings and errors (graphics adapter, a lost graphics device, panics the guard recovered from) to standard error and to `logs/vectorcraft.log` next to the preferences, the two previous runs kept and each file capped at 16 MiB, so a launch without a terminal still leaves something to attach to a bug report (#465). Native documents with a lot of path data (traced or generated art, in layers, symbols or patterns) are saved as compact JSON, about a fifth of the size; small documents stay pretty-printed (#1492). Saving to a network drive on macOS falls back to a plain fsync when the share refuses a full flush (#1625, part of #1620; not confirmed on a real share), and a save still succeeds when a folder refuses the temporary file, the rename over the document or copying permissions: the content is written elsewhere first and copied in, and a failed copy keeps the temporary file and names it (#1649, part of #1620). A document opened by a relative path finds its relatively linked images, and `vectorcraft-cli convert` lists what reading the input left out as `importWarnings` (#1606, fixes #1604). - Preferences › File Handling › Data Recovery › Folder has a Choose… button on the desktop that picks the folder Data Recovery keeps its copies in ([Illustrator reference, Set Data Recovery preferences](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf)); a picked folder that Data Recovery cannot create its folders in or list is refused with a status message, and the field keeps its value. + Preferences › File Handling › Data Recovery › Folder has a Choose… button on the desktop that picks the folder Data Recovery keeps its copies in ([Illustrator reference, Set Data Recovery preferences](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf)); a picked folder that Data Recovery cannot create its folders in or list is refused with a status message, and the field keeps its value. OK applies the same check to a folder typed into the field: when it fails, the dialog stays open, the status bar says why and no preference changes; an empty field (the default folder) and the folder already saved are not checked. Preferences › Plug-ins & Scratch Disks › Additional Plug-ins Folder has a Choose… button on the desktop too ([an answer describing Additional Plug-ins Folder's Choose button](https://stackoverflow.com/questions/43902576/how-to-make-adobe-illustrator-use-a-plug-in-built-in-xcode)); VectorCraft's own rule refuses a picked or typed folder whose contents can't be listed. Additional Fonts Folder and Templates Folder stay typed only. A name typed in the desktop save panel without the file type's extension gets it, and when a file of that name exists, which the panel did not ask about, Save, Save As, Save a Copy, Save as Template, the exports and every other write through a save panel ask before replacing it (dialog `replaceFile`; Cancel writes nothing). A name returned by the desktop save panel with the extension of a format the save does not write has it replaced with the saved format's: Save As of a new document saves `card.ait` and `card.png` as `card.vectorcraft`, and Save as Template saves `card.pdf` as `card.vctemplate`. An extension that names no format stays part of the name (`notes.v2` is saved as `notes.v2.vectorcraft`). Export As, Save as PDF, Save for Office Documents, Save for Web, Text Export Options, print to file, the presets' Export… and the library, swatch and Document Info saves replace a typed extension of another format than the one they write in the same way: Export As PNG writes `card.svg` as `card.png`, Save as PDF writes `card.png` as `card.pdf`, and `document.exportSelection` with a `format` suggests and adds that format's extension. An extension of the written format stays as typed in any letter case (`photo.JPEG` for JPEG), Export As SVG writes `art.svgz` compressed, and `document.exportSelection` without a `format` writes the format the typed extension names (`tests/saveext.rs`). From 528faa8e0af0bddc0486e0ff7f67b0374afef4bb Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Thu, 5 Nov 2026 03:05:28 +0530 Subject: [PATCH 030/196] Fix #5532: Release Type on a Path splits type on a path into point type and its path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Type Tools add-on command (Object › Plug-ins › Type Tools › Release Type on a Path…, `addon.type.releasePath`): each selected type on a path becomes point type with the same runs, character and paragraph attributes, on one straight line whose baseline starts where its first character sat, and the plain path it was set on, with its exact shape and transform, in its layer and stacking place, with no fill or stroke. `mode` keeps both, the path only or the text only; `keepOriginal` leaves the type on a path and adds the released objects above it. Other objects are left alone, nothing to release makes no undo step, the run is one undo step and the released objects are selected. The command dialog previews it as Type on a Path Options does (#5360): Cancel leaves no history, OK is one step. Tests, command_sweep cases, catalog rows in all 26 languages, docs/mcp.md and the parity docs (beyond Illustrator: scores unchanged). Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 4 +- crates/engine/src/cmd/addons/typetools.rs | 187 ++++++++- .../engine/src/cmd/addons/typetools/tests.rs | 385 +++++++++++++++++- crates/engine/tests/command_sweep.rs | 5 + crates/ui-egui/src/addons/typetools.rs | 11 +- crates/ui-egui/src/addons/typetools/tests.rs | 66 +++ crates/ui-egui/src/dialogs/command.rs | 8 +- crates/ui-egui/src/i18n/bg.tsv | 4 + crates/ui-egui/src/i18n/bs.tsv | 5 + crates/ui-egui/src/i18n/ca.tsv | 4 + crates/ui-egui/src/i18n/cs.tsv | 4 + crates/ui-egui/src/i18n/da.tsv | 4 + crates/ui-egui/src/i18n/de.tsv | 4 + crates/ui-egui/src/i18n/el.tsv | 4 + crates/ui-egui/src/i18n/es.tsv | 4 + crates/ui-egui/src/i18n/fi.tsv | 4 + crates/ui-egui/src/i18n/fr.tsv | 4 + crates/ui-egui/src/i18n/hu.tsv | 4 + crates/ui-egui/src/i18n/id.tsv | 4 + crates/ui-egui/src/i18n/it.tsv | 4 + crates/ui-egui/src/i18n/ja.tsv | 4 + crates/ui-egui/src/i18n/ka.tsv | 4 + crates/ui-egui/src/i18n/ko.tsv | 4 + crates/ui-egui/src/i18n/nl.tsv | 4 + crates/ui-egui/src/i18n/pl.tsv | 4 + crates/ui-egui/src/i18n/pt-br.tsv | 4 + crates/ui-egui/src/i18n/ru.tsv | 4 + crates/ui-egui/src/i18n/sv.tsv | 4 + crates/ui-egui/src/i18n/tr.tsv | 4 + crates/ui-egui/src/i18n/uk.tsv | 4 + crates/ui-egui/src/i18n/vi.tsv | 4 + crates/ui-egui/src/i18n/zh-hans.tsv | 4 + crates/ui-egui/src/i18n/zh-hant.tsv | 4 + docs/mcp.md | 39 +- docs/target-app-parity.md | 9 +- docs/type-parity.md | 4 +- 36 files changed, 799 insertions(+), 24 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 16bd8b1dab..e055747f18 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -11,7 +11,7 @@ **Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away -> **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-05 · **Change:** minor (Type Tools add-on: Release Type on a Path, #5532; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON @@ -131,6 +131,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged. - 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged. - 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). @@ -219,6 +220,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap | Date | Change | Summary | |---|---|---| +| 2026-11-05 | minor | Progress log row for the Type Tools add-on's Release Type on a Path (#5532); headline numbers unchanged. | | 2026-11-03 | minor | Progress log row for the Type Tools add-on's Text Tweaker (#4924); headline numbers unchanged. | | 2026-11-02 | minor | Closed font-family fields accept wheel input for selected text in Character, Properties and Control (#5253); scores and estimates unchanged. | | 2026-11-01 | minor | Progress log row for the Color Effects add-on's Find Nearest Swatch (#4923); headline numbers unchanged. | diff --git a/crates/engine/src/cmd/addons/typetools.rs b/crates/engine/src/cmd/addons/typetools.rs index a478b8c00b..bc1d4e4f25 100644 --- a/crates/engine/src/cmd/addons/typetools.rs +++ b/crates/engine/src/cmd/addons/typetools.rs @@ -2,22 +2,27 @@ //! the selected characters letter by letter, from a start value to an end value along a shape //! (straight, eased, a bow, a spike, or at random), while the text stays live. Values are set as //! the Character panel sets them (`text.setRangeStyle`), in its units and ranges -//! (). Its submenu -//! (Object › Plug-ins › Type Tools) and dialog are the UI's. +//! (). Release Type on a Path +//! splits type on a path into point type holding the same text and the plain path it was set on +//! (#5532). The reference app has no command for it, so it goes beyond parity and changes no +//! parity score. Its submenu (Object › Plug-ins › Type Tools) and dialogs are the UI's. #[cfg(test)] mod tests; use serde_json::{Value, json}; +use vectorcraft_color::Paint; use vectorcraft_color::recolor::Rng; -use vectorcraft_doc::{NodeId, TextRun}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, TextKind, TextObject, TextRun}; +use vectorcraft_geom::{Affine, ArcPath, Point}; use vectorcraft_text::edit; use super::super::menucmds::whole_or; use super::super::object::choice; use super::super::textedit::{CharChange, text_mut, text_ref, type_ranges}; use super::super::typecmd::refresh_bounds; -use super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or}; +use super::super::typemenu::text_ids; +use super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or, targets}; use crate::{EngineError, Result, Session}; /// An attribute Text Tweaker sets: its `text.setRangeStyle` param, the values it takes and its @@ -41,17 +46,33 @@ pub const SHAPES: [&str; 5] = ["straight", "ease", "bow", "spike", "random"]; const MAX_CHARS: usize = 100_000; pub fn specs() -> Vec { - vec![cmd!( - "addon.type.textTweaker", - "Text Tweaker", - ["Object", "Plug-ins", "Type Tools"], - None, - "{attribute?: \"size\" (pt 0.1..1296) | \"baselineShift\" (pt −1296..1296) | \"rotation\" (° −360..360) | \"hScale\" (% 1..10000) | \"vScale\" (% 1..10000) | \"tracking\" (1/1000 em −1000..10000) | \"leading\" (pt 0.1..5000) | \"strokeWidth\" (pt 0..1000) (\"size\"), from?: the first character's value, to?: the last character's value (each in the attribute's units and range; defaults: size 12 → 36, baselineShift 0 → 12, rotation 0 → 30, hScale and vScale 100 → 150, tracking 0 → 200, leading 12 → 36, strokeWidth 0 → 2), shape?: \"straight\" (an even ramp) | \"ease\" (slow at both ends) | \"bow\" (from at both ends, rising smoothly to `to` in the middle) | \"spike\" (from at both ends, straight up to `to` in the middle) | \"random\" (each character anywhere from `from` to `to`) (\"straight\"), seed?: whole number (0; random: the same seed and text give the same values), skipSpaces?: true (spaces and line breaks keep their values and don't count), id?, start?: byte, end?: byte (range endpoints inside a character round down to its start), ids?: [id…] (instead of id)} give the characters one character attribute letter by letter, from `from` to `to` along the shape, as the Character panel sets it, as one undo step; the text stays live and editable. The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: all its text), else every selected type object; each object gets its own ramp. Stroke weight only shows on characters with a stroke → {count (characters changed), ids}", - has_selection, - text_tweaker - )] + vec![ + cmd!( + "addon.type.textTweaker", + "Text Tweaker", + ["Object", "Plug-ins", "Type Tools"], + None, + "{attribute?: \"size\" (pt 0.1..1296) | \"baselineShift\" (pt −1296..1296) | \"rotation\" (° −360..360) | \"hScale\" (% 1..10000) | \"vScale\" (% 1..10000) | \"tracking\" (1/1000 em −1000..10000) | \"leading\" (pt 0.1..5000) | \"strokeWidth\" (pt 0..1000) (\"size\"), from?: the first character's value, to?: the last character's value (each in the attribute's units and range; defaults: size 12 → 36, baselineShift 0 → 12, rotation 0 → 30, hScale and vScale 100 → 150, tracking 0 → 200, leading 12 → 36, strokeWidth 0 → 2), shape?: \"straight\" (an even ramp) | \"ease\" (slow at both ends) | \"bow\" (from at both ends, rising smoothly to `to` in the middle) | \"spike\" (from at both ends, straight up to `to` in the middle) | \"random\" (each character anywhere from `from` to `to`) (\"straight\"), seed?: whole number (0; random: the same seed and text give the same values), skipSpaces?: true (spaces and line breaks keep their values and don't count), id?, start?: byte, end?: byte (range endpoints inside a character round down to its start), ids?: [id…] (instead of id)} give the characters one character attribute letter by letter, from `from` to `to` along the shape, as the Character panel sets it, as one undo step; the text stays live and editable. The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: all its text), else every selected type object; each object gets its own ramp. Stroke weight only shows on characters with a stroke → {count (characters changed), ids}", + has_selection, + text_tweaker + ), + cmd!( + "addon.type.releasePath", + "Release Type on a Path…", + ["Object", "Plug-ins", "Type Tools"], + None, + "{mode?: \"both\" (point type and the path) | \"path\" (the path only) | \"text\" (point type only) (\"both\"), keepOriginal?: false (true: the type on a path stays and the released objects go just above it), ids?: [id…], id? (instead of ids; neither: the selection)} split each type on a path among the objects (inside groups too) into point type and the path it was set on. The point type holds the same text with the same character and paragraph attributes, on one straight line whose baseline starts where the first character sat on the path; Type on a Path Options (effect, align to path, spacing, flip, brackets) don't apply to point type and are dropped. The path keeps its exact shape (open or closed, anchors and handles, the object's transform) and comes out with no fill and no stroke, in the type's layer and place in the stacking order. Other objects are left alone, and with no type on a path among them nothing changes and no undo step is made. One undo step; the released objects are selected → {ids (released, bottom to top), paths, texts}", + has_selection, + release_path + ), + ] } +/// Release Type on a Path's command (the id in [`specs`]). +pub const RELEASE: &str = "addon.type.releasePath"; +/// What Release Type on a Path keeps: both, the path only, or the text only. +pub const RELEASE_MODES: [&str; 3] = ["both", "path", "text"]; + /// Where along `shape` (0 at `from`, 1 at `to`) character `i` of `n` lands; `random` for the /// random shape. fn amount(shape: &str, i: usize, n: usize, random: f64) -> f64 { @@ -187,3 +208,143 @@ fn tweak(runs: Vec, changes: &[(usize, CharChange)]) -> Vec { edit::normalize(&mut out); out } + +/// Type on a path among the objects `p` names (or the selection), inside groups too, in stacking +/// order. An id that names no object is an error. +fn path_types(s: &Session, p: &Value) -> Result> { + let ids = targets(s, p)?; + let d = &s.doc()?.doc; + if let Some(id) = ids.iter().find(|id| d.node(**id).is_none()) { + return Err(EngineError::NoNode(*id)); + } + let on_path = |id: &NodeId| matches!(d.node(*id).map(|n| &n.kind), Some(NodeKind::Text(t)) if matches!(t.kind, TextKind::OnPath { .. })); + Ok(text_ids(d, &ids).into_iter().filter(on_path).collect()) +} + +/// Where the first character laid out in `lay` starts its baseline: the pen position of the first +/// glyph in text order (a list marker, which has no characters, before the character it leads). +/// None without a glyph. +fn first_pen(lay: &vectorcraft_text::TextLayout) -> Option { + lay.glyphs.iter().filter(|g| g.origin.x.is_finite() && g.origin.y.is_finite()).min_by_key(|g| (g.byte, g.len != 0)).map(|g| g.origin) +} + +/// `t`, type on a path, as point type on one straight line: the same runs and character and +/// paragraph attributes, its baseline starting where its first character sat on the path (in the +/// object's own text space, so its transform stays). Type on a Path Options are dropped. None for +/// other type, or when it can't be placed. +fn released_text(t: &TextObject) -> Option { + let TextKind::OnPath { path, .. } = &t.kind else { return None }; + let db = vectorcraft_text::FontDb::global(); + // Where the first character sat. Text that didn't fit on the path has no glyph there: it + // starts at the start bracket. + let at = first_pen(&vectorcraft_text::layout(db, t)).or_else(|| { + let ap = ArcPath::new(path); + let (from, _) = t.kind.path_span()?; + let (p, _) = ap.at(from * ap.len()); + (p.x.is_finite() && p.y.is_finite()).then_some(p) + })?; + let mut out = t.clone(); + out.kind = TextKind::Point; + out.path_effect = Default::default(); + out.path_align = Default::default(); + out.path_spacing = 0.0; + // Point type is in no thread: its first paragraph starts in it. + out.first_para_continues = false; + // Where the point type puts its own first character; the origin moves so it lands at `at`, + // whatever the paragraph's alignment and direction. + let own = first_pen(&vectorcraft_text::layout(db, &out)).unwrap_or(Point::ZERO); + let shift = at - own; + if !(shift.x.is_finite() && shift.y.is_finite()) { + return None; + } + out.xf *= Affine::translate(shift); + refresh_bounds(&mut out); + Some(out) +} + +/// The path `t` is set on, as a plain path object `id` in document space, with no fill and no +/// stroke: type paths carry no paint of their own. None for other type. +fn released_path(id: NodeId, t: &TextObject) -> Option { + Some(Node::path(id, t.type_path()?, Appearance::basic(Paint::None, Paint::None, 1.0))) +} + +fn release_path(s: &mut Session, p: &Value) -> Result { + const C: &str = RELEASE; + let mode = choice(p, C, "mode", &RELEASE_MODES)?.unwrap_or("both"); + let keep = switch_or(p, "keepOriginal", false, C)?; + let want_path = mode != "text"; + let ids = path_types(s, p)?; + if ids.is_empty() { + return Ok(json!({ "ids": [], "paths": [], "texts": [] })); + } + // The point type, worked out before the edit: one object that can't be placed fails the run. + let mut plans: Vec<(NodeId, Option)> = Vec::with_capacity(ids.len()); + { + let d = &s.doc()?.doc; + for id in ids { + let Some(NodeKind::Text(t)) = d.node(id).map(|n| &n.kind) else { continue }; + let text = match mode { + "path" => None, + _ => Some(released_text(t).ok_or_else(|| bad(C, format!("object {} can't be set as point type", id.0)))?), + }; + plans.push((id, text)); + } + } + let (paths, texts) = s.edit("Release Type on a Path", |d, sel| { + let (mut paths, mut texts) = (vec![], vec![]); + for (id, text) in plans { + let (path, text) = release_one(d, id, text, want_path, keep)?; + paths.extend(path); + texts.extend(text); + } + sel.set(paths.iter().chain(&texts).copied()); + Ok((paths, texts)) + })?; + // Bottom to top. + let d = &s.doc()?.doc; + let mut all: Vec<(Vec, NodeId)> = paths.iter().chain(&texts).map(|id| (d.index_path(*id).unwrap_or_default(), *id)).collect(); + all.sort(); + let nums = |v: &[NodeId]| v.iter().map(|i| i.0).collect::>(); + let all: Vec = all.into_iter().map(|(_, id)| id).collect(); + Ok(json!({ "ids": nums(&all), "paths": nums(&paths), "texts": nums(&texts) })) +} + +/// Release type on a path `id` in `d`: its path (`want_path`) where the type was, or just above it +/// when the original stays (`keep`), then the point type `text` (None: no text) above that. +/// Without `keep` the original goes, and released text takes its place as the same object, so a +/// frame of threaded text leaves its thread with the text it holds, as Convert To Point Type's +/// does. The released (path, text). +fn release_one(d: &mut Document, id: NodeId, text: Option, want_path: bool, keep: bool) -> Result<(Option, Option)> { + let (parent, idx, _) = d.position(id).ok_or(EngineError::NoNode(id))?; + let original = d.node(id).cloned().ok_or(EngineError::NoNode(id))?; + let NodeKind::Text(t) = &original.kind else { return Ok((None, None)) }; + let path = + if want_path { Some(released_path(d.alloc_id(), t).ok_or_else(|| bad(RELEASE, format!("object {} has no path", id.0)))?) } else { None }; + if !keep && text.is_none() { + d.remove(id)?; + } + // Where the next released object goes: above the original when it stays, else in its place. + let mut at = if keep { idx + 1 } else { idx }; + let path = match path { + Some(n) => { + at += 1; + Some(d.insert(parent, at - 1, n)?) + } + None => None, + }; + let text = match text { + None => None, + Some(text) if keep => { + let mut n = original.clone(); + n.id = d.alloc_id(); + n.kind = NodeKind::Text(Box::new(text)); + Some(d.insert(parent, at, n)?) + } + Some(text) => { + // The original, now just above the path. + d.node_mut(id).ok_or(EngineError::NoNode(id))?.kind = NodeKind::Text(Box::new(text)); + Some(id) + } + }; + Ok((path, text)) +} diff --git a/crates/engine/src/cmd/addons/typetools/tests.rs b/crates/engine/src/cmd/addons/typetools/tests.rs index 7f05cb823a..e597525c97 100644 --- a/crates/engine/src/cmd/addons/typetools/tests.rs +++ b/crates/engine/src/cmd/addons/typetools/tests.rs @@ -1,5 +1,5 @@ //! Text Tweaker: the values each shape gives each character, what it skips and changes, one undo -//! step, and bad params refused without a change. +//! step, and bad params refused without a change. Release Type on a Path ([`release`]). use serde_json::json; use vectorcraft_doc::{CharStyle, NodeId, NodeKind, TextObject}; @@ -221,3 +221,386 @@ fn it_needs_a_selection() { select(&mut s, &[]); assert!(s.execute(C, &json!({})).is_err()); } + +/// Release Type on a Path (#5532): each mode, Keep Original, mixed and empty selections, closed, +/// open, curved and flipped paths, transformed and grouped type, multi-style and unicode text, +/// undo and redo, the preview a dialog shows, and bad params. +mod release { + use serde_json::{Value, json}; + use vectorcraft_color::Paint; + use vectorcraft_doc::{Appearance, Document, Justify, NodeId, NodeKind, TextKind, TextObject}; + use vectorcraft_geom::{PathData, Point}; + + use crate::Session; + + const C: &str = "addon.type.releasePath"; + + fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s + } + + fn new_id(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) + } + + /// 12 pt type `words` on a path along `d` (SVG path data), starting where the path is nearest + /// `at`, selected. + fn path_type(s: &mut Session, d: &str, at: [f64; 2], words: &str) -> NodeId { + let pid = s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap(); + let id = new_id(&s.execute("text.createInPath", &json!({"path": pid, "mode": "onPath", "text": words, "size": 12, "at": at})).unwrap()); + select(s, &[id]); + id + } + + fn rect(s: &mut Session, x: f64) -> NodeId { + new_id(&s.execute("shape.rectangle", &json!({"x": x, "y": 20, "width": 20, "height": 20})).unwrap()) + } + + fn point_type(s: &mut Session) -> NodeId { + new_id(&s.execute("text.create", &json!({"x": 40, "y": 500, "text": "point", "size": 12})).unwrap()) + } + + fn select(s: &mut Session, ids: &[NodeId]) { + s.select(|_, sel| sel.set(ids.iter().copied())).unwrap(); + } + + fn doc(s: &Session) -> Document { + (*s.doc().unwrap().doc).clone() + } + + fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() + } + + fn selected(s: &Session) -> Vec { + s.doc().unwrap().selection.objects.clone() + } + + fn text(s: &Session, id: NodeId) -> TextObject { + match &s.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + k => panic!("not text: {k:?}"), + } + } + + fn path(s: &Session, id: NodeId) -> PathData { + match &s.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Path { path, .. } => path.clone(), + k => panic!("not a path: {k:?}"), + } + } + + /// (parent, index) of `id`. + fn place(s: &Session, id: NodeId) -> (Option, usize) { + let (parent, idx, _) = s.doc().unwrap().doc.position(id).unwrap(); + (parent, idx) + } + + /// Each glyph's pen position in the document and its baseline angle, in text order. + fn pens(t: &TextObject) -> Vec<(Point, f64)> { + let mut g: Vec<_> = + vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).glyphs.into_iter().map(|g| (g.byte, t.xf * g.origin, g.angle)).collect(); + g.sort_by_key(|g| g.0); + g.into_iter().map(|(_, p, a)| (p, a)).collect() + } + + /// How many path objects the document has. + fn paths_in(s: &Session) -> usize { + let mut n = 0; + for l in &s.doc().unwrap().doc.layers { + l.walk(&mut |c| n += usize::from(matches!(c.kind, NodeKind::Path { .. }))); + } + n + } + + fn close(a: Point, b: Point) -> bool { + (a - b).hypot() < 1e-4 + } + + fn ids(v: &Value, key: &str) -> Vec { + v[key].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() + } + + /// `after`, released from `before`: point type with the same text and attributes, on one + /// straight line whose first character starts where `before`'s did on its path, with no Type + /// on a Path Options left. + fn assert_released(before: &TextObject, after: &TextObject) { + assert_eq!(after.kind, TextKind::Point); + assert_eq!(after.runs, before.runs, "the same text and character attributes"); + assert_eq!((&after.para, &after.paras), (&before.para, &before.paras), "the same paragraph attributes"); + assert_eq!(after.plain_text(), before.plain_text()); + assert_eq!((after.path_effect, after.path_align, after.path_spacing), Default::default(), "path options dropped"); + let (was, now) = (pens(before), pens(after)); + assert!(!now.is_empty()); + if let Some((first, _)) = was.first() { + assert!(close(now[0].0, *first), "the baseline starts where the first character sat: {:?} vs {first:?}", now[0].0); + } + assert!(now.iter().all(|(_, a)| *a == 0.0), "a straight baseline"); + // On one line through the first pen, along the object's own x axis. + let [a, b, ..] = after.xf.as_coeffs(); + let axis = vectorcraft_geom::Vec2::new(a, b); + for (p, _) in &now { + let off = *p - now[0].0; + assert!(off.cross(axis).abs() < 1e-4 * axis.hypot().max(1.0) * off.hypot().max(1.0), "{p:?} is on the line"); + } + } + + #[test] + fn both_gives_point_type_and_the_path_in_the_types_place() { + let mut s = session(); + let below = rect(&mut s, 10.0); + let id = path_type(&mut s, "M100 300 C200 150 400 150 500 300", [100.0, 300.0], "Curved line"); + let above = rect(&mut s, 50.0); + select(&mut s, &[id]); + let before = text(&s, id); + let (layer, idx) = place(&s, id); + let (start, n) = (doc(&s), steps(&s)); + + let out = s.execute(C, &json!({})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + let (paths, texts) = (ids(&out, "paths"), ids(&out, "texts")); + assert_eq!((paths.len(), texts.len()), (1, 1)); + let (p, t) = (paths[0], texts[0]); + assert_eq!(ids(&out, "ids"), [p, t], "bottom to top"); + assert_eq!(selected(&s), [p, t], "the released objects are selected"); + + // The path: its exact shape, anchors and handles, with no fill and no stroke, where the type was. + assert_eq!(path(&s, p), before.type_path().unwrap()); + assert_eq!(*s.doc().unwrap().doc.node(p).unwrap().appearance, Appearance::basic(Paint::None, Paint::None, 1.0)); + assert_eq!( + (place(&s, below), place(&s, p), place(&s, t), place(&s, above)), + ((layer, idx - 1), (layer, idx), (layer, idx + 1), (layer, idx + 2)) + ); + // The text replaces the type on a path. + assert_released(&before, &text(&s, t)); + assert_eq!(t, id, "the same type object, now point type"); + + let released = doc(&s); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(doc(&s), start, "undone"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(doc(&s), released, "redone"); + } + + #[test] + fn path_only_and_text_only() { + let mut s = session(); + let id = path_type(&mut s, "M100 300 L500 300", [300.0, 300.0], "Line"); + let before = text(&s, id); + let (layer, idx) = place(&s, id); + let out = s.execute(C, &json!({"mode": "path"})).unwrap(); + let p = ids(&out, "paths")[0]; + assert!(ids(&out, "texts").is_empty()); + assert!(s.doc().unwrap().doc.node(id).is_none(), "the type is gone"); + assert_eq!((path(&s, p), place(&s, p)), (before.type_path().unwrap(), (layer, idx))); + assert_eq!(selected(&s), [p]); + + s.execute("edit.undo", &json!({})).unwrap(); + select(&mut s, &[id]); + let out = s.execute(C, &json!({"mode": "text"})).unwrap(); + assert!(ids(&out, "paths").is_empty()); + assert_eq!((ids(&out, "texts"), place(&s, id)), (vec![id], (layer, idx)), "the type stays in its place"); + assert_released(&before, &text(&s, id)); + assert_eq!(paths_in(&s), 0, "no path made"); + } + + #[test] + fn keep_original_adds_the_released_objects_above_it() { + let mut s = session(); + let id = path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "Keep"); + let (before, (layer, idx)) = (text(&s, id), place(&s, id)); + let original = s.doc().unwrap().doc.node(id).cloned().unwrap(); + let out = s.execute(C, &json!({"keepOriginal": true})).unwrap(); + let (p, t) = (ids(&out, "paths")[0], ids(&out, "texts")[0]); + assert_eq!(s.doc().unwrap().doc.node(id), Some(&original), "the type on a path stays as it is"); + assert_eq!((place(&s, id), place(&s, p), place(&s, t)), ((layer, idx), (layer, idx + 1), (layer, idx + 2))); + assert_ne!(t, id); + assert_eq!(selected(&s), [p, t], "only the released objects are selected"); + assert_released(&before, &text(&s, t)); + + // Text only, kept: the copy goes just above. + select(&mut s, &[id]); + let out = s.execute(C, &json!({"mode": "text", "keepOriginal": true})).unwrap(); + let t2 = ids(&out, "texts")[0]; + assert_eq!(place(&s, t2), (layer, idx + 1)); + assert_released(&before, &text(&s, t2)); + } + + #[test] + fn other_objects_are_left_alone() { + let mut s = session(); + let r = rect(&mut s, 10.0); + let pt = point_type(&mut s); + let a = path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "One"); + let b = path_type(&mut s, "M100 400 L500 400", [100.0, 400.0], "Two"); + let others = [r, pt].map(|id| s.doc().unwrap().doc.node(id).cloned().unwrap()); + select(&mut s, &[r, pt, a, b]); + let n = steps(&s); + let out = s.execute(C, &json!({})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step for the whole selection"); + assert_eq!((ids(&out, "paths").len(), ids(&out, "texts")), (2, vec![a, b])); + assert_eq!([r, pt].map(|id| s.doc().unwrap().doc.node(id).cloned().unwrap()), others); + assert_eq!(selected(&s).len(), 4, "the two paths and the two texts"); + assert!(!selected(&s).contains(&r) && !selected(&s).contains(&pt)); + + // `ids` picks the objects instead of the selection. + s.execute("edit.undo", &json!({})).unwrap(); + select(&mut s, &[r]); + let out = s.execute(C, &json!({"ids": [r.0, b.0]})).unwrap(); + assert_eq!(ids(&out, "texts"), [b]); + assert!(matches!(text(&s, a).kind, TextKind::OnPath { .. })); + } + + #[test] + fn nothing_to_release_changes_nothing() { + let mut s = session(); + let r = rect(&mut s, 10.0); + let pt = point_type(&mut s); + select(&mut s, &[r, pt]); + let (before, n, sel) = (doc(&s), steps(&s), selected(&s)); + assert_eq!(s.execute(C, &json!({})).unwrap(), json!({"ids": [], "paths": [], "texts": []})); + assert_eq!((doc(&s), steps(&s), selected(&s)), (before, n, sel), "no change, no step"); + } + + #[test] + fn closed_and_open_paths_keep_their_shape() { + for (d, closed) in [ + ("M200 200 L400 200 L400 400 L200 400 Z", true), + ("M100 300 C150 100 250 500 300 300 S450 100 500 300", false), + ("M300 150 C380 150 450 220 450 300 C450 380 380 450 300 450 C220 450 150 380 150 300 C150 220 220 150 300 150 Z", true), + ] { + let mut s = session(); + let id = path_type(&mut s, d, [200.0, 200.0], "Round and round"); + let before = text(&s, id); + let out = s.execute(C, &json!({})).unwrap(); + let p = path(&s, ids(&out, "paths")[0]); + assert_eq!(p, before.type_path().unwrap(), "{d}"); + assert_eq!(p.is_closed(), closed, "{d}"); + assert_released(&before, &text(&s, ids(&out, "texts")[0])); + } + } + + #[test] + fn flipped_type_releases_its_path_as_it_runs() { + let mut s = session(); + let id = path_type(&mut s, "M100 300 C200 150 400 150 500 300", [300.0, 200.0], "Flipped"); + s.execute("type.pathOptions", &json!({"flip": true, "effect": "skew", "alignToPath": "center", "spacing": 4})).unwrap(); + let before = text(&s, id); + let out = s.execute(C, &json!({})).unwrap(); + assert_eq!(path(&s, ids(&out, "paths")[0]), before.type_path().unwrap()); + assert_released(&before, &text(&s, id)); + } + + #[test] + fn transformed_type_keeps_its_transform() { + let mut s = session(); + let id = path_type(&mut s, "M100 300 C200 150 400 150 500 300", [100.0, 300.0], "Turned"); + s.execute("object.rotate", &json!({"angle": 30, "origin": [300, 300]})).unwrap(); + s.execute("object.scale", &json!({"sx": 150, "sy": 150, "origin": [300, 300]})).unwrap(); + let before = text(&s, id); + let out = s.execute(C, &json!({})).unwrap(); + assert_eq!(path(&s, ids(&out, "paths")[0]), before.type_path().unwrap(), "the transform is in the path"); + let after = text(&s, id); + assert_eq!(after.xf.as_coeffs()[..4], before.xf.as_coeffs()[..4], "turned and scaled as the type was"); + assert_released(&before, &after); + } + + #[test] + fn grouped_type_releases_inside_its_group() { + let mut s = session(); + let r = rect(&mut s, 10.0); + let id = path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "Grouped"); + select(&mut s, &[r, id]); + s.execute("object.group", &json!({})).unwrap(); + let g = place(&s, id).0.unwrap(); + assert!(matches!(s.doc().unwrap().doc.node(g).unwrap().kind, NodeKind::Group { .. })); + select(&mut s, &[g]); + let out = s.execute(C, &json!({})).unwrap(); + let (p, t) = (ids(&out, "paths")[0], ids(&out, "texts")[0]); + assert_eq!((place(&s, p).0, place(&s, t).0), (Some(g), Some(g))); + } + + #[test] + fn styles_and_unicode_text_survive() { + let mut s = session(); + let words = "Größe ✓ 日本語 éa"; + let id = path_type(&mut s, "M100 300 C200 150 400 150 500 300", [100.0, 300.0], words); + // "Gr" (bytes 0..2), and "日本" (bytes 12..18, after "Größe ✓ "). + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 2, "size": 24, "fill": "#ff0000"})).unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 12, "end": 18, "tracking": 200, "hScale": 150})).unwrap(); + // A centred paragraph: the first character still starts where it sat. + s.edit("centre", |d, _| { + if let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) { + t.para.justify = Justify::Center; + } + Ok(()) + }) + .unwrap(); + let before = text(&s, id); + assert!(before.runs.len() >= 3, "several styles: {:?}", before.runs); + let out = s.execute(C, &json!({})).unwrap(); + let after = text(&s, ids(&out, "texts")[0]); + assert_eq!(after.plain_text(), words); + assert_released(&before, &after); + } + + #[test] + fn empty_type_starts_at_its_start_bracket() { + let mut s = session(); + let id = path_type(&mut s, "M100 300 L500 300", [300.0, 300.0], ""); + let out = s.execute(C, &json!({})).unwrap(); + assert_eq!(ids(&out, "texts"), [id]); + let t = text(&s, id); + assert_eq!(t.kind, TextKind::Point); + assert!(close(t.xf * Point::ZERO, Point::new(300.0, 300.0)), "{:?}", t.xf * Point::ZERO); + } + + /// What a dialog's Preview does: each preview replaces the last, Cancel puts the type back with + /// no step of history, and OK keeps the preview as one step. + #[test] + fn previews_cancel_and_commit() { + let mut s = session(); + let id = path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "Preview"); + let (start, n, sel) = (doc(&s), steps(&s), selected(&s)); + let count = paths_in; + s.begin_interaction("Release Type on a Path").unwrap(); + s.preview(C, &json!({"mode": "both"})).unwrap(); + assert_eq!((count(&s), text(&s, id).kind), (1, TextKind::Point)); + s.preview(C, &json!({"mode": "text"})).unwrap(); + assert_eq!(count(&s), 0, "the next preview replaces the last"); + s.preview(C, &json!({"mode": "path", "keepOriginal": true})).unwrap(); + assert_eq!(count(&s), 1); + assert!(matches!(text(&s, id).kind, TextKind::OnPath { .. })); + s.cancel_interaction().unwrap(); + assert_eq!((doc(&s), steps(&s), selected(&s)), (start.clone(), n, sel), "Cancel: as it was, no step"); + + s.begin_interaction("Release Type on a Path").unwrap(); + s.preview(C, &json!({"mode": "both"})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(steps(&s), n + 1, "OK: one step"); + assert_eq!(text(&s, id).kind, TextKind::Point); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(doc(&s), start); + } + + #[test] + fn bad_params_are_refused_without_a_change() { + let mut s = session(); + path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "Bad"); + let (before, n) = (doc(&s), steps(&s)); + for p in [ + json!({"mode": "all"}), + json!({"mode": 1}), + json!({"keepOriginal": "yes"}), + json!({"ids": [999_999]}), + json!({"ids": "1"}), + json!({"id": -1}), + json!({"colour": "red"}), + ] { + assert!(s.execute(C, &p).is_err(), "{p}"); + assert_eq!((doc(&s), steps(&s)), (before.clone(), n), "{p}"); + } + } +} diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index b660831781..0db8cc655c 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -668,6 +668,11 @@ fn structured_junk() { ("addon.type.textTweaker", json!({"attribute": "rotation", "from": -360, "to": 360, "shape": "bow", "skipSpaces": false, "ids": [u64::MAX]})), ("addon.type.textTweaker", json!({"attribute": "hScale", "id": 2, "start": u64::MAX, "end": 0, "shape": "ease"})), ("addon.type.textTweaker", json!({"attribute": ["size"], "from": "x", "seed": 1e308, "skipSpaces": "no", "ids": "all"})), + ("addon.type.releasePath", json!({"mode": "both", "keepOriginal": true, "ids": [0, 1, 2, 3, 4, 5, 6, 7, 8]})), + ("addon.type.releasePath", json!({"mode": "path", "ids": [0, 1, 2, 3, 4, 5, 6, 7, 8, u64::MAX]})), + ("addon.type.releasePath", json!({"mode": "text", "keepOriginal": false, "id": 2})), + ("addon.type.releasePath", json!({"mode": ["both"], "keepOriginal": "no", "ids": "all", "id": -1})), + ("addon.type.releasePath", json!({"mode": "nope", "keepOriginal": 1e308, "ids": [1.5, null, "x"]})), ("addon.cleanup.breakText", json!({"by": "glyphs", "ids": [0, 1, 2, 3, 4, 5, 6, 7, 8, u64::MAX]})), ("addon.cleanup.breakText", json!({"by": ["lines"]})), ("addon.cleanup.breakText", json!({"by": "paragraphs"})), diff --git a/crates/ui-egui/src/addons/typetools.rs b/crates/ui-egui/src/addons/typetools.rs index f9bfa3ca36..859c69fa3d 100644 --- a/crates/ui-egui/src/addons/typetools.rs +++ b/crates/ui-egui/src/addons/typetools.rs @@ -34,9 +34,18 @@ const SEEDS: u64 = 1_000_000; const LABEL_W: f32 = 90.0; const FIELD_W: f32 = 90.0; +/// Release Type on a Path's command. Its menu item opens the generic command dialog +/// (`ui.paramDialog`) on these options, with a Preview (`dialogs::command`). +pub const RELEASE: &str = "addon.type.releasePath"; +/// Release Type on a Path › Keep: what the command's `mode` takes, by name. +pub const RELEASE_MODES: &[(&str, &str)] = &[("Text and Path", "both"), ("Path Only", "path"), ("Text Only", "text")]; + /// Object › Plug-ins › Type Tools. pub fn menu() -> Vec { - vec![Item::Cmd("Text Tweaker…", COMMAND, Value::Null)] + vec![ + Item::Cmd("Text Tweaker…", COMMAND, Value::Null), + Item::Cmd("Release Type on a Path…", RELEASE, json!({"mode": "both", "keepOriginal": false})), + ] } /// The attribute row of param `key` (the first, Font Size, for an unknown one). diff --git a/crates/ui-egui/src/addons/typetools/tests.rs b/crates/ui-egui/src/addons/typetools/tests.rs index 36e3ef2f31..e7118de082 100644 --- a/crates/ui-egui/src/addons/typetools/tests.rs +++ b/crates/ui-egui/src/addons/typetools/tests.rs @@ -60,3 +60,69 @@ fn another_attribute_starts_from_its_own_values() { let d = app.ui.dialog.as_ref().unwrap(); assert_eq!((d.fields["from"].clone(), d.fields["to"].clone()), (json!(0.0), json!(30.0))); } + +/// The kind of object `id` is, and whether it is type on a path. +fn on_path(app: &VectorcraftApp, id: NodeId) -> Option { + match &app.session.doc().unwrap().doc.node(id)?.kind { + NodeKind::Text(t) => Some(matches!(t.kind, vectorcraft_doc::TextKind::OnPath { .. })), + _ => None, + } +} + +/// #5532: Object › Plug-ins › Type Tools › Release Type on a Path… opens the command dialog on +/// Text and Path, Keep Original off, with Preview off. With Preview on the canvas shows the +/// release while the dialog is open; Cancel puts the type back with no step of history, and OK +/// keeps it as one step. +#[test] +fn release_type_on_a_path_previews_cancels_and_runs_on_ok() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + let path = app.run("path.create", json!({"d": "M100 200 C200 100 400 100 500 200"})).unwrap()["id"].as_u64().unwrap(); + let id = NodeId(app.run("text.createInPath", json!({"path": path, "mode": "onPath", "text": "Release me"})).unwrap()["id"].as_u64().unwrap()); + app.run("select.set", json!({"ids": [id.0]})).unwrap(); + let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let (start, n) = (app.session.doc().unwrap().doc.clone(), steps(&app)); + let open = |app: &mut VectorcraftApp| { + let entries = menus::menu_entries(app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Type Tools"] && e.label == "Release Type on a Path…").unwrap(); + assert!(item.enabled); + let (cmd, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + menus::invoke(app, &cmd, p); + }; + + open(&mut app); + let d = app.ui.dialog.as_ref().expect("a dialog opens"); + assert_eq!((d.str("__command"), d.str("__label")), (super::RELEASE.to_string(), "Release Type on a Path".to_string())); + assert_eq!((d.str("mode"), d.bool("keepOriginal"), d.bool("preview")), ("both".to_string(), false, false)); + assert!(crate::dialogs::accepts_field(d, "preview")); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in ["Release Type on a Path", "Mode:", "Text and Path", "Keep Original", "Preview"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + assert_eq!(on_path(&app, id), Some(true), "no preview without the checkbox"); + + // Preview on: the type is released on the canvas; another mode replaces that preview. + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "preview".into(), json!(true)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(on_path(&app, id), Some(false), "previewed as point type"); + app.ui.dialog.as_mut().unwrap().fields.insert("mode".into(), json!("path")); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(on_path(&app, id), None, "path only: the type is gone in the preview"); + + // Cancel: as it was, with no step of history. + crate::dialogs::cancel(&mut app); + assert_eq!(app.session.doc().unwrap().doc, start, "Cancel restores the type"); + assert_eq!(steps(&app), n, "and adds no undo step"); + + // OK: one step, the released objects selected. + open(&mut app); + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "preview".into(), json!(true)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(steps(&app), n + 1, "one undo step"); + assert_eq!(on_path(&app, id), Some(false)); + assert_eq!(app.session.doc().unwrap().selection.objects.len(), 2, "the path and the text are selected"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, start); +} diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 2dc8efd064..ef781fb43d 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -61,12 +61,12 @@ pub(super) const SPEC: DialogSpec = DialogSpec { /// Does this dialog show a Preview checkbox? Grid Repeat Options does: the public page for the /// grid options lists one, and the radial and mirror pages do not. Type on a Path Options does -/// too (#5360), as public tutorials of the dialog show. (Cancel rolls a preview back whichever -/// dialog started it.) +/// too (#5360), as public tutorials of the dialog show, and Type Tools › Release Type on a Path +/// works the same way (#5532). (Cancel rolls a preview back whichever dialog started it.) fn previews(d: &Dialog) -> bool { match d.str("__command").as_str() { "object.repeat.options" => d.fields.contains_key("gridType"), - "type.pathOptions" => true, + "type.pathOptions" | crate::addons::typetools::RELEASE => true, _ => false, } } @@ -114,6 +114,7 @@ fn order(command: &str) -> &'static [&'static str] { // The public Trap options' order. "object.pathfinder.trap" => &["thickness", "heightWidth", "tintReduction", "trapsWithProcessColor", "reverseTraps"], "addon.color.printFixes" => &["inkLimit", "excludePureBlack", "removeWhiteOverprint", "overprintBlack", "textOnly", "fill", "stroke"], + crate::addons::typetools::RELEASE => &["mode", "keepOriginal"], _ => &[], } } @@ -123,6 +124,7 @@ fn choices(command: &str, key: &str) -> Option { match (command, key) { ("type.pathOptions", "effect") => Some(crate::menus::PATH_EFFECTS), ("type.pathOptions", "alignToPath") => Some(PATH_ALIGN), + (crate::addons::typetools::RELEASE, "mode") => Some(crate::addons::typetools::RELEASE_MODES), ("text.areaOptions", "fit") => Some(AREA_FIT), ("text.areaOptions", "firstBaseline") => Some(FIRST_BASELINE), ("text.areaOptions", "verticalAlign") => Some(VERTICAL_ALIGN), diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 8948a14828..ee25d5057e 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6186,6 +6186,10 @@ breakText Glyphs Глифи Bow Дъга Spike Връх Skip Spaces Пропускане на интервалите + Release Type on a Path… Освобождаване на текст по пътя… + Release Type on a Path Освобождаване на текст по пътя + Text and Path Текст и път + Path Only Само път @msg The art is too large to copy as a picture: other apps get no PNG of it Графиката е твърде голяма, за да се копира като изображение: другите приложения не получават PNG от нея # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index f6410a8274..1f4ea2422b 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6220,6 +6220,11 @@ shape Open Otvoren Bow Luk Spike Šiljak Skip Spaces Preskoči razmake + Release Type on a Path… Oslobodi tekst na putanji… + Release Type on a Path Oslobodi tekst na putanji + Text and Path Tekst i putanja + Path Only Samo putanja + Text Only Samo tekst @msg The art is too large to copy as a picture: other apps get no PNG of it Grafika je prevelika da bi se kopirala kao slika: druge aplikacije ne dobijaju njen PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index afedb11f96..73df162e86 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6321,6 +6321,10 @@ breakText Glyphs Glifs Bow Arc Spike Pic Skip Spaces Omet els espais + Release Type on a Path… Allibera el text sobre un traçat… + Release Type on a Path Allibera el text sobre un traçat + Text and Path Text i traçat + Path Only Només traçat @msg The art is too large to copy as a picture: other apps get no PNG of it La il·lustració és massa gran per copiar-la com a imatge: les altres aplicacions no en reben cap PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index fc3a7c5cc1..084f68e32c 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6335,6 +6335,10 @@ breakText Glyphs Glyfy Bow Oblouk Spike Špička Skip Spaces Přeskočit mezery + Release Type on a Path… Uvolnit text na cestě… + Release Type on a Path Uvolnit text na cestě + Text and Path Text a cesta + Path Only Pouze cesta @msg The art is too large to copy as a picture: other apps get no PNG of it Kresba je příliš velká na zkopírování jako obrázek: ostatní aplikace z ní nedostanou PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index d58f0610b6..623e700387 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6202,6 +6202,10 @@ breakText Glyphs Glyffer Bow Bue Spike Spids Skip Spaces Spring mellemrum over + Release Type on a Path… Frigør tekst på kurve… + Release Type on a Path Frigør tekst på kurve + Text and Path Tekst og kurve + Path Only Kun kurve @msg The art is too large to copy as a picture: other apps get no PNG of it Grafikken er for stor til at blive kopieret som et billede: andre programmer får ingen PNG af den # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index d88d86b5f4..93c8f21d49 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5921,6 +5921,10 @@ breakText Glyphs Glyphen Bow Bogen Spike Spitze Skip Spaces Leerzeichen überspringen + Release Type on a Path… Pfadtext zurückwandeln… + Release Type on a Path Pfadtext zurückwandeln + Text and Path Text und Pfad + Path Only Nur Pfad @msg The art is too large to copy as a picture: other apps get no PNG of it Das Bildmaterial ist zu groß, um es als Bild zu kopieren: Andere Apps erhalten kein PNG davon # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 1c116fe3d6..9b0d4049d0 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6287,6 +6287,10 @@ breakText Glyphs Γλύφοι Bow Τόξο Spike Αιχμή Skip Spaces Παράλειψη κενών + Release Type on a Path… Αποδέσμευση κειμένου σε διαδρομή… + Release Type on a Path Αποδέσμευση κειμένου σε διαδρομή + Text and Path Κείμενο και διαδρομή + Path Only Μόνο διαδρομή @msg The art is too large to copy as a picture: other apps get no PNG of it Το γραφικό είναι πολύ μεγάλο για αντιγραφή ως εικόνα: οι άλλες εφαρμογές δεν λαμβάνουν PNG του # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index d9bad3fc80..cd98ba9ef5 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6277,6 +6277,10 @@ breakText Glyphs Glifos Bow Arco Spike Pico Skip Spaces Omitir espacios + Release Type on a Path… Soltar texto en trazado… + Release Type on a Path Soltar texto en trazado + Text and Path Texto y trazado + Path Only Solo trazado @msg The art is too large to copy as a picture: other apps get no PNG of it La ilustración es demasiado grande para copiarla como imagen: las demás aplicaciones no reciben un PNG de ella # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index d66e806d8a..ea55b031d3 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6365,6 +6365,10 @@ breakText Glyphs Merkit Bow Kaari Spike Piikki Skip Spaces Ohita välilyönnit + Release Type on a Path… Vapauta teksti polulta… + Release Type on a Path Vapauta teksti polulta + Text and Path Teksti ja polku + Path Only Vain polku @msg The art is too large to copy as a picture: other apps get no PNG of it Grafiikka on liian suuri kopioitavaksi kuvana: muut sovellukset eivät saa siitä PNG-kuvaa Check for Updates… Tarkista päivitykset… VectorCraft Updates VectorCraft-päivitykset diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 4ddf66a51c..0ed2c4d718 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6330,6 +6330,10 @@ breakText Glyphs Glyphes Bow Arc Spike Pointe Skip Spaces Ignorer les espaces + Release Type on a Path… Libérer le texte curviligne… + Release Type on a Path Libérer le texte curviligne + Text and Path Texte et tracé + Path Only Tracé uniquement @msg The art is too large to copy as a picture: other apps get no PNG of it L’illustration est trop grande pour être copiée en tant qu’image : les autres applications n’en reçoivent pas de PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index b42cb25bbe..a6cef2de64 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6319,6 +6319,10 @@ breakText Glyphs Glifák Bow Ív Spike Csúcs Skip Spaces Szóközök kihagyása + Release Type on a Path… Útvonalszöveg szétválasztása… + Release Type on a Path Útvonalszöveg szétválasztása + Text and Path Szöveg és útvonal + Path Only Csak útvonal @msg The art is too large to copy as a picture: other apps get no PNG of it A grafika túl nagy ahhoz, hogy képként másolható legyen: más alkalmazások nem kapnak róla PNG-t # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 843de1391c..c0c6489bf7 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6202,6 +6202,10 @@ breakText Glyphs Glif Bow Busur Spike Puncak Skip Spaces Lewati Spasi + Release Type on a Path… Lepaskan Teks pada Jalur… + Release Type on a Path Lepaskan Teks pada Jalur + Text and Path Teks dan jalur + Path Only Hanya jalur @msg The art is too large to copy as a picture: other apps get no PNG of it Gambar terlalu besar untuk disalin sebagai gambar: aplikasi lain tidak mendapatkan PNG darinya # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 2a90453d4d..d41988a0c8 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5955,6 +5955,10 @@ breakText Glyphs Glifi Bow Arco Spike Picco Skip Spaces Salta gli spazi + Release Type on a Path… Rilascia testo su tracciato… + Release Type on a Path Rilascia testo su tracciato + Text and Path Testo e tracciato + Path Only Solo tracciato @msg The art is too large to copy as a picture: other apps get no PNG of it La grafica è troppo grande per essere copiata come immagine: le altre app non ne ricevono un PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index a73e548d83..12a4442305 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -6020,6 +6020,10 @@ breakText Glyphs 字形 Bow 弓形 Spike 山形 Skip Spaces スペースをスキップ + Release Type on a Path… パス上文字を解除… + Release Type on a Path パス上文字を解除 + Text and Path テキストとパス + Path Only パスのみ @msg The art is too large to copy as a picture: other apps get no PNG of it アートワークが大きすぎるため画像としてコピーできません:他のアプリには PNG が渡されません # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 78de8173fa..2c89b17ee3 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6346,6 +6346,10 @@ font-script Japanese იაპონური Bow რკალი Spike პიკი Skip Spaces ჰარების გამოტოვება + Release Type on a Path… ტექსტის ტრაექტორიიდან მოხსნა… + Release Type on a Path ტექსტის ტრაექტორიიდან მოხსნა + Text and Path ტექსტი და ტრაექტორია + Path Only მხოლოდ ტრაექტორია @msg The art is too large to copy as a picture: other apps get no PNG of it ნახატი ზედმეტად დიდია სურათად დასაკოპირებლად: სხვა აპები მის PNG-ს ვერ მიიღებენ # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index aefbd17df5..979fdefec2 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5916,6 +5916,10 @@ breakText Glyphs 글리프 Bow 활 모양 Spike 뾰족한 모양 Skip Spaces 공백 건너뛰기 + Release Type on a Path… 패스 위 문자 해제… + Release Type on a Path 패스 위 문자 해제 + Text and Path 문자와 패스 + Path Only 패스만 @msg The art is too large to copy as a picture: other apps get no PNG of it 아트워크가 너무 커서 이미지로 복사할 수 없습니다: 다른 앱에는 PNG가 전달되지 않습니다 # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index dbb31fd127..0a5943f822 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6246,6 +6246,10 @@ breakText Glyphs Glyphs Bow Boog Spike Piek Skip Spaces Spaties overslaan + Release Type on a Path… Tekst op pad vrijgeven… + Release Type on a Path Tekst op pad vrijgeven + Text and Path Tekst en pad + Path Only Alleen pad @msg The art is too large to copy as a picture: other apps get no PNG of it Het illustratiewerk is te groot om als afbeelding te kopiëren: andere apps krijgen er geen PNG van # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 88322303be..82b042541d 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -6190,6 +6190,10 @@ breakText Glyphs Glify Bow Łuk Spike Szpic Skip Spaces Pomiń spacje + Release Type on a Path… Uwolnij tekst na ścieżce… + Release Type on a Path Uwolnij tekst na ścieżce + Text and Path Tekst i ścieżka + Path Only Tylko ścieżka @msg The art is too large to copy as a picture: other apps get no PNG of it Grafika jest zbyt duża, aby skopiować ją jako obraz: inne aplikacje nie otrzymają jej w formacie PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 0293e24e37..245d237753 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6408,6 +6408,10 @@ swatch Yellow Green Verde-amarelado Bow Arco Spike Pico Skip Spaces Ignorar espaços + Release Type on a Path… Liberar Texto em um Caminho… + Release Type on a Path Liberar Texto em um Caminho + Text and Path Texto e caminho + Path Only Somente caminho @msg The art is too large to copy as a picture: other apps get no PNG of it A arte é grande demais para ser copiada como imagem: outros aplicativos não recebem um PNG dela # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 9791fe1c38..f49a5f68b6 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6424,6 +6424,10 @@ shape Open Открытый Bow Дуга Spike Пик Skip Spaces Пропускать пробелы + Release Type on a Path… Освободить текст по контуру… + Release Type on a Path Освободить текст по контуру + Text and Path Текст и контур + Path Only Только контур @msg The art is too large to copy as a picture: other apps get no PNG of it Графика слишком велика для копирования в виде изображения: другие приложения не получат её PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 58f82f37bc..0588ec2617 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6391,6 +6391,10 @@ digits Hindi Hindi Bow Båge Spike Spets Skip Spaces Hoppa över mellanslag + Release Type on a Path… Släpp text på bana… + Release Type on a Path Släpp text på bana + Text and Path Text och bana + Path Only Endast bana @msg The art is too large to copy as a picture: other apps get no PNG of it Teckningen är för stor för att kopieras som en bild: andra appar får ingen PNG av den # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index ae5a58dd6c..f0ae591f4e 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6292,6 +6292,10 @@ breakText Glyphs Glifler Bow Yay Spike Sivri Uç Skip Spaces Boşlukları Atla + Release Type on a Path… Yoldaki Metni Ayır… + Release Type on a Path Yoldaki Metni Ayır + Text and Path Metin ve yol + Path Only Yalnızca yol @msg The art is too large to copy as a picture: other apps get no PNG of it Çizim, resim olarak kopyalanamayacak kadar büyük: diğer uygulamalar bunun PNG'sini almaz # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 363a8f6fb9..109a591763 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5935,6 +5935,10 @@ breakText Glyphs Гліфи Bow Дуга Spike Пік Skip Spaces Пропускати пробіли + Release Type on a Path… Звільнити текст за контуром… + Release Type on a Path Звільнити текст за контуром + Text and Path Текст і контур + Path Only Лише контур @msg The art is too large to copy as a picture: other apps get no PNG of it Графіка завелика, щоб скопіювати її як зображення: інші програми не отримають її PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 2275c27d8d..07ecd390eb 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5936,6 +5936,10 @@ breakText Glyphs Glyph Bow Cung Spike Đỉnh nhọn Skip Spaces Bỏ qua khoảng trắng + Release Type on a Path… Giải phóng chữ trên đường dẫn… + Release Type on a Path Giải phóng chữ trên đường dẫn + Text and Path Văn bản và đường dẫn + Path Only Chỉ đường dẫn @msg The art is too large to copy as a picture: other apps get no PNG of it Hình vẽ quá lớn để sao chép dưới dạng ảnh: các ứng dụng khác không nhận được PNG của nó # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 1d44f8cc6e..be24cce506 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -6176,6 +6176,10 @@ breakText Glyphs 字形 Bow 弓形 Spike 尖峰 Skip Spaces 跳过空格 + Release Type on a Path… 释放路径文字… + Release Type on a Path 释放路径文字 + Text and Path 文字和路径 + Path Only 仅路径 @msg The art is too large to copy as a picture: other apps get no PNG of it 图稿太大,无法作为图片复制:其他应用不会获得它的 PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 6d6b107519..777873899f 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5973,6 +5973,10 @@ breakText Glyphs 字符 Bow 弓形 Spike 尖峰 Skip Spaces 略過空格 + Release Type on a Path… 釋放路徑文字… + Release Type on a Path 釋放路徑文字 + Text and Path 文字和路徑 + Path Only 僅路徑 @msg The art is too large to copy as a picture: other apps get no PNG of it 圖稿太大,無法作為圖片複製:其他應用程式不會取得它的 PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). diff --git a/docs/mcp.md b/docs/mcp.md index 63f41074ca..797ac023b5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7037,8 +7037,8 @@ there is no step. → `{symbols: [name…], ids: [instance id…], skipped: [{la ## Type Tools add-on -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, +Type Tools is a built-in add-on for type: its commands are `addon.type.textTweaker` and `addon.type.releasePath`, and +in the desktop app it lives in Object › Plug-ins › Type Tools (#4924, #5532). 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 ([formatting type](https://helpx.adobe.com/illustrator/using/formatting-type.html)), so on scaled type it is the size shown. @@ -7063,3 +7063,38 @@ default values, and the seed starts new whenever the document has changed. {"name":"run_command","arguments":{"command":"addon.type.textTweaker","params":{"attribute":"baselineShift","from":0,"to":18,"shape":"bow"}}} {"name":"run_command","arguments":{"command":"addon.type.textTweaker","params":{"attribute":"rotation","from":-15,"to":15,"shape":"random","seed":4}}} ``` + +### Release Type on a Path + +`addon.type.releasePath` splits each type on a path (`text.createInPath` with `mode: "onPath"`) into point type that +holds the same text and the plain path it was set on (#5532). The reference app has no command for this, so it is a +VectorCraft addition and changes no parity score. + +- **The path** keeps its exact shape (open or closed, every anchor and handle, the object's transform) and goes in the + type's layer at its place in the stacking order. Type paths carry no paint of their own (making type on a path drops + the path's fill and stroke), so the released path has no fill and no stroke. +- **The text** keeps its runs with their character attributes and its paragraph attributes, and becomes point type on + one straight line along the object's own axis, with the baseline starting where the first character sat on the path + (type with no characters starts at its start bracket). Type on a Path Options (effect, align to path, spacing, flip, + brackets) don't apply to point type and are dropped. Without `keepOriginal` the type object itself becomes the point + type, keeping its id, so a frame of threaded text leaves its thread with the text it holds, as + `type.convertToPointType` does for area type. +- It acts on the type on a path among `ids` (or `id`, else the selection), groups included; other objects are left + alone. With none among them nothing changes and no undo step is made. Otherwise the whole run is one undo step and + the released objects are selected. + +| Parameter | Values (default) | +|---|---| +| `mode` | `both` (point type and the path), `path` (the path only: the type goes), `text` (point type only) (`both`) | +| `keepOriginal` | false; true: the type on a path stays as it is and the released objects go just above it | +| `ids`, `id` | the objects to release (default: the selection) | + +→ `{ids (the released objects, bottom to top), paths, texts}`. Release Type on a Path… opens the command dialog +(`ui.paramDialog`) on Mode (Text and Path, Path Only, Text Only) and Keep Original, with Preview: while Preview is on +the canvas shows the release, Cancel restores the original with no undo step, and OK applies it as one, as Type on a +Path Options' Preview does (#5360). + +```json +{"name":"run_command","arguments":{"command":"addon.type.releasePath","params":{}}} +{"name":"run_command","arguments":{"command":"addon.type.releasePath","params":{"mode":"path","keepOriginal":true}}} +``` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2f851ca410..2166985548 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-05 · **Change:** minor (Gradient panel: Delete Stop beside the ramp, #5403; 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-05 · **Change:** minor (Type Tools add-on: Release Type on a Path, a VectorCraft addition, #5532; optical kerning spaces pairs by the font's own stem spacing instead of a fixed tight gap; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -8,7 +8,7 @@ Ligature caret stops use a font's GDEF contour-point positions in horizontal and Creating a gradient from solid or empty paint uses the document's color model for its default stops, including drawing its vector with the Gradient tool. Explicit `keepModel: true` retains RGB defaults, and existing gradients keep their own colors. Scores and estimates are unchanged. -**Feature evidence last updated:** 2026-11-03. +**Feature evidence last updated:** 2026-11-05. The shared assessment status line and revision history are current upstream; this dated section records the submission's feature evidence and revisions without rescoring upstream or claiming a new combined build or runtime measurement. @@ -23,6 +23,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-05 | minor | Type Tools add-on: Release Type on a Path (a VectorCraft addition, #5532): evidence added; scores unchanged. | | 2026-11-04 | minor | Path Precision Tools add-on (a VectorCraft addition): Set Corners… and `addon.pathtools.cornerSet` `minAngle`/`maxAngle` round only the corners whose angle is in a range (#5545); evidence added; scores unchanged. | | 2026-11-04 | minor | Path Precision Tools add-on (a VectorCraft addition): Set Corners… and `addon.pathtools.cornerSet` `every` round all, the odd-numbered or the even-numbered anchors of each path (#5546); evidence added; scores unchanged. | | 2026-11-04 | minor | Transform Each's Scale has the documented Relative and Absolute radio buttons (`object.transformEach` `relative`: percentages of each object's size, or the width and height it becomes, measured on each object's own bounds) and the link that keeps the two scales in proportion; the panel lists Scale, Move, Rotate, the Options in two columns, the Reference Point and Preview (level with Copy, Cancel and OK) in the documented order. Scores and estimates unchanged. | @@ -1582,6 +1583,10 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Type Tools › Text Tweaker… gives one character attribute (size, baseline shift, character rotation, horizontal or vertical scale, tracking, leading or stroke weight) to the selected characters letter by letter, from a start value to an end value along a straight ramp, an ease in and out, a bow, a spike or at random with a seed, while the text stays live and editable (#4924). Values are set as the Character panel sets them, in its units and ranges, so scaled type takes the sizes shown; spaces and line breaks are skipped unless asked for, each type object gets its own ramp, the range is the Type tool's selection or all the text of the selected type objects, and the run is one undo step from a dialog with Preview. Tests: `cmd::addons::typetools::tests` in `vectorcraft-engine` (each shape, each attribute, skipped spaces, ranges, one ramp per object, seeded random values, scaled type, one undo step, bad params refused), `addons::typetools::tests` in `vectorcraft-ui-egui` (the submenu, the dialog, Preview and Cancel, OK) and `command_sweep`. Commands: `docs/mcp.md` › Type Tools add-on. +## Type Tools add-on: Release Type on a Path (2026-11-05) + +A VectorCraft addition, not a feature of the reference app (it has no command for this), so no area score moves. Object › Plug-ins › Type Tools › Release Type on a Path… splits each selected type on a path into point type holding the same text and the plain path it was set on, or keeps only one of them (#5532). The path keeps its exact shape (open or closed, anchors and handles, the object's transform), layer and place in the stacking order, with no fill and no stroke since type paths carry no paint of their own. The text keeps its runs, character and paragraph attributes and becomes point type on one straight line whose baseline starts where the first character sat on the path; Type on a Path Options don't apply to point type and are dropped. Keep Original leaves the type on a path and adds the released objects above it. Other objects are left alone and a selection with no type on a path makes no undo step; otherwise the run is one undo step, the released objects are selected, and the dialog's Preview works as Type on a Path Options' does (#5360). Tests: `cmd::addons::typetools::tests::release` in `vectorcraft-engine` (each mode, Keep Original, mixed and empty selections, closed, open, curved and flipped paths, transformed and grouped type, multi-style and unicode text with a centred paragraph, empty type, undo and redo, preview, cancel and commit, bad params refused), `release_type_on_a_path_previews_cancels_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Type Tools add-on › Release Type on a Path. + ## Path Precision Tools add-on: Divide into Dashes (2026-11-01) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools › Divide into Dashes… cuts the selected paths into separate open paths along the curve (arc length, not straight distance): each `dash` long (0.01 to 1000000 pt, 10 by default) with `gap` between them (0 by default: the pieces touch); the gap pieces are left out unless Remove Gaps is off. With direct-selected segments (or anchors) only those runs are divided, the pattern running on across segments that follow one another, and the rest of such a path stays as pieces of its own. Fit to Corners and Ends gives every run between corners and ends a whole number of dashes, all stretched or squeezed alike so it starts and ends on a dash (a closed path without corners holds whole periods); otherwise the lengths are exact and each run's last piece is what is left. Every piece keeps the path's appearance and is selected; one undo step; at most 100000 pieces (more is refused). The dialog takes lengths in any unit and previews on the canvas. Tests: `dashes::tests` in `vectorcraft-pathops` (exact and fitted lengths, curves measured along them, picked segments on open and closed paths, the piece cap and bad patterns), `divide_into_dashes_*` in `cmd::addons::pathtools::tests` in `vectorcraft-engine` (gaps removed or kept, fitted lengths, the stroke kept, one undo step, selected segments only, bad params and too many pieces refused), `divide_into_dashes_opens_its_dialog_previews_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. diff --git a/docs/type-parity.md b/docs/type-parity.md index 2013f513b9..d62d010f46 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-04 · **Change:** minor (Find Font's Replace With Font lists family and style rows, searchable, with its own scroll state and a refresh after each replacement; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Release Type on a Path in the Type Tools add-on, beyond Illustrator, #5532; 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 @@ -69,6 +69,7 @@ against Illustrator's public documentation; **estimated** unless noted. | No Break | done | Character panel menu (`text.setFormat` / `text.setRangeStyle {noBreak}`): the marked characters stay on one line, including across a space; a run that does not fit after earlier text moves together, and a run longer than the line stays together. Evidence: `layout::wrapping_tests::no_break_keeps_marked_characters_on_one_line`, `tests::no_break_keeps_marked_words_on_one_line`, `typecmd::no_break_is_a_character_attribute_saved_only_when_on` | | Inline symbols in text | beyond Illustrator | not scored | | Align Stroke (inside, outside) on live type's character stroke | beyond Illustrator | not scored; `stroke.set {align}` and `text.setRangeStyle {strokeOptions: {align}}`; saved natively, drawn around the glyphs on the canvas and in PDF, EPS and SVG (live text, stroke on the glyph outlines); visual bounds grow with it (#2294) | +| Release Type on a Path (Object › Plug-ins › Type Tools) | beyond Illustrator | not scored; `addon.type.releasePath` splits type on a path into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on (exact shape, place in the stacking order, no paint), or keeps only one of them, optionally leaving the original; a dialog with Preview, one undo step (#5532) | Character Styles menu New/Redefine and footer New capture the first selected character of a nonempty Type selection, including exact style-run and UTF-8 boundaries; New adds a definition without applying it. New/Redefine commands accept optional `end` for range capture. Start-only command affinity, existing UI caret/object behavior and paragraph capture at `start` remain unchanged. Pointer regressions assert captured definitions, linked-text updates and local overrides, complete-document Undo/Redo and saved state, with whole-object, collapsed-caret and range-Apply controls. Capture closes prior typing while preserving the Type selection. Live text and Select All regressions exercise menu New/Redefine and footer New, asserting that further typing retains the captured definition and that typing, capture and further typing have separate Undo/Redo steps. Focused engine and egui input tests pass for boundary capture, all three live-typing capture routes and the existing compatibility controls. Full workspace CI passes. @@ -76,6 +77,7 @@ Character Styles menu New/Redefine and footer New capture the first selected cha | Date | Change | Summary | |---|---|---| +| 2026-11-05 | minor | Release Type on a Path joins the Type Tools add-on: type on a path splits into point type and its path (#5532, beyond Illustrator). Scores and estimates unchanged. | | 2026-11-04 | minor | A Type-range Copy or Cut publishes styled art alongside plain text, so a later canvas Paste keeps its character formatting after editing ends (#5636). Scores and estimates unchanged. | | 2026-11-03 | minor | Glyphs panel adds Alternates for Current Selection. A chosen alternate changes one character's drawn glyph while keeping its Unicode text; character-style capture does not copy that per-character choice. Scores and estimates unchanged. | | 2026-11-04 | minor | Find Font's Replace With Font lists family and style rows, one click setting both, with a search over them; the list scrolls apart from the document's font list and refreshes after each replacement (#4972); scores and estimates unchanged. | From 21680cb53a1adf50fed439f50ee282db217a70e5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 19:55:07 -0800 Subject: [PATCH 031/196] =?UTF-8?q?Docs:=20Additional=20Plug-ins=20Folder'?= =?UTF-8?q?s=20Choose=E2=80=A6=20cites=20the=20preferences=20help?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The progress line for the folder preferences now cites the preferences help for Plug-ins & Scratch Disks as the place where additional plug-ins folders are set, and names the plug-ins Choose… button and the check of a typed folder on OK as VectorCraft's own rules. --- 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 27a6035895..1deff1683d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1144,7 +1144,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur PDF export writes a linear or radial gradient that mixes a spot color with process colors, or two spot colors, as a DeviceN shading of the spot inks and the process inks its stops use, so each spot ink prints on its own plate; an off-center midpoint is written as a stop with the inks halfway between its two stops. A gradient that mixes a spot color with RGB or Lab colors is still written without the spot ink, with a warning. A Perceptual gradient of spot inks is written as a Separation or DeviceN shading of the stops on its curve; a dithered gradient fill, and a Perceptual gradient with RGB or Lab stops other than white or more than 4,096 stops on its curve, are written as images in process colors, with a warning. A Lab spot color in such a shading is named by the same Separation space, with the Lab alternate, as its flat fills (`engine/src/tests/linked_stops.rs`, `engine/src/tests/labspots.rs`). PDF export writes a spot color named All or None (in a Separation space, the names of every plate and of no plate: [ISO 32000-1:2008](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf), 8.6.6.4) as the ink All Spot or None Spot (All Spot 2 and on when a spot swatch already has that name) in its fills, strokes, gradients, colorized images and Lab alternates; Registration still prints on every plate (`pdf/src/tests/output.rs`). - `.vectorcraft` (lossless JSON, compressed, atomic saves, save down to v1), Save As with a format chooser, Save a Copy, Revert, templates, Data Recovery after a crash (browser tabs hold their copies with Web Locks too, so a background tab's copies are never taken for a crash's, and a tab repairs copies another removed when it resumes: #367), background save and export. The desktop app writes its warnings and errors (graphics adapter, a lost graphics device, panics the guard recovered from) to standard error and to `logs/vectorcraft.log` next to the preferences, the two previous runs kept and each file capped at 16 MiB, so a launch without a terminal still leaves something to attach to a bug report (#465). Native documents with a lot of path data (traced or generated art, in layers, symbols or patterns) are saved as compact JSON, about a fifth of the size; small documents stay pretty-printed (#1492). Saving to a network drive on macOS falls back to a plain fsync when the share refuses a full flush (#1625, part of #1620; not confirmed on a real share), and a save still succeeds when a folder refuses the temporary file, the rename over the document or copying permissions: the content is written elsewhere first and copied in, and a failed copy keeps the temporary file and names it (#1649, part of #1620). A document opened by a relative path finds its relatively linked images, and `vectorcraft-cli convert` lists what reading the input left out as `importWarnings` (#1606, fixes #1604). - Preferences › File Handling › Data Recovery › Folder has a Choose… button on the desktop that picks the folder Data Recovery keeps its copies in ([Illustrator reference, Set Data Recovery preferences](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf)); a picked folder that Data Recovery cannot create its folders in or list is refused with a status message, and the field keeps its value. OK applies the same check to a folder typed into the field: when it fails, the dialog stays open, the status bar says why and no preference changes; an empty field (the default folder) and the folder already saved are not checked. Preferences › Plug-ins & Scratch Disks › Additional Plug-ins Folder has a Choose… button on the desktop too ([an answer describing Additional Plug-ins Folder's Choose button](https://stackoverflow.com/questions/43902576/how-to-make-adobe-illustrator-use-a-plug-in-built-in-xcode)); VectorCraft's own rule refuses a picked or typed folder whose contents can't be listed. Additional Fonts Folder and Templates Folder stay typed only. + Preferences › File Handling › Data Recovery › Folder has a Choose… button on the desktop that picks the folder Data Recovery keeps its copies in ([Illustrator reference, Set Data Recovery preferences](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf)); a picked folder that Data Recovery cannot create its folders in or list is refused with a status message, and the field keeps its value. OK applies the same check to a folder typed into the field (VectorCraft's own rule): when it fails, the dialog stays open, the status bar says why and no preference changes; an empty field (the default folder) and the folder already saved are not checked. Preferences › Plug-ins & Scratch Disks is where additional plug-ins folders are set ([Illustrator preferences help](https://helpx.adobe.com/illustrator/desktop/get-started/preferences-and-settings/set-app-preferences.html)); its Additional Plug-ins Folder has a Choose… button on the desktop as well, VectorCraft's own, matching Data Recovery's, and VectorCraft's own rule refuses a picked or typed folder whose contents can't be listed. Additional Fonts Folder and Templates Folder stay typed only. A name typed in the desktop save panel without the file type's extension gets it, and when a file of that name exists, which the panel did not ask about, Save, Save As, Save a Copy, Save as Template, the exports and every other write through a save panel ask before replacing it (dialog `replaceFile`; Cancel writes nothing). A name returned by the desktop save panel with the extension of a format the save does not write has it replaced with the saved format's: Save As of a new document saves `card.ait` and `card.png` as `card.vectorcraft`, and Save as Template saves `card.pdf` as `card.vctemplate`. An extension that names no format stays part of the name (`notes.v2` is saved as `notes.v2.vectorcraft`). Export As, Save as PDF, Save for Office Documents, Save for Web, Text Export Options, print to file, the presets' Export… and the library, swatch and Document Info saves replace a typed extension of another format than the one they write in the same way: Export As PNG writes `card.svg` as `card.png`, Save as PDF writes `card.png` as `card.pdf`, and `document.exportSelection` with a `format` suggests and adds that format's extension. An extension of the written format stays as typed in any letter case (`photo.JPEG` for JPEG), Export As SVG writes `art.svgz` compressed, and `document.exportSelection` without a `format` writes the format the typed extension names (`tests/saveext.rs`). From 815671b3a2f9e3182d9f463cf0fa141f67ac1f00 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 20:16:43 -0800 Subject: [PATCH 032/196] Render: at very large coordinates an edited path is not taken for a moved one The check that reuses a moved path's stroke outline allowed each coordinate to differ from the moved one by 4 x f64::EPSILON times the sum of the compared coordinates and the largest coordinate of the first point, about 2.7 pt near 1e15, so a 0.5 pt anchor or handle edit there drew the outline made before the edit. offset_between and anchors_moved now measure the offset on each axis at the pair of points with the smallest coordinates on that axis, then check every pair against that offset within 3 units in the last place of the pair's own coordinates. A first anchor far from the origin no longer sets the tolerance for points near it. Tests: 0.5 pt anchor and handle edits at 1e9 and 1e15 (and 0.0005 pt at 1e9); an edit near the origin of a path that starts at 1e16; a path whose coordinates shrink with each point, moved by growing amounts. --- crates/render/src/renderer.rs | 2 +- crates/render/src/renderer/paint.rs | 126 +++++++++++++++---------- crates/render/src/tests/movedstroke.rs | 84 +++++++++++++++-- 3 files changed, 154 insertions(+), 58 deletions(-) diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 534568a14c..e8aa40d3eb 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -19,7 +19,7 @@ use super::{ }; #[cfg(test)] -pub(crate) use paint::{STROKES_OUTLINED, offset_between}; +pub(crate) use paint::{STROKES_OUTLINED, anchors_moved, offset_between}; mod images; mod nodes; diff --git a/crates/render/src/renderer/paint.rs b/crates/render/src/renderer/paint.rs index 1ed98e8ed2..5228cc8817 100644 --- a/crates/render/src/renderer/paint.rs +++ b/crates/render/src/renderer/paint.rs @@ -384,71 +384,99 @@ thread_local! { pub(crate) static STROKES_OUTLINED: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// The offset that moves path `was` onto path `now`, when `now` is `was` moved (each coordinate -/// within a few units in the last place of the moved one, the error that adding the offset and -/// measuring it from the first points can make). `None` otherwise, and for an empty path. +/// The offset that moves path `was` onto path `now`, when `now` is `was` moved (each point within +/// the rounding that [`Offset::holds`] allows). `None` otherwise, and for an empty path. pub(crate) fn offset_between(was: &BezPath, now: &BezPath) -> Option { - use kurbo::PathEl; - let (was, now) = (was.elements(), now.elements()); - if was.len() != now.len() { + if !matches!(was.elements().first(), Some(kurbo::PathEl::MoveTo(_))) { return None; } - let (by, first) = match (was.first()?, now.first()?) { - (PathEl::MoveTo(a), PathEl::MoveTo(b)) => first_offset(*a, *b)?, - _ => return None, - }; - let near = |a: &kurbo::Point, b: &kurbo::Point| moved_by(*a, *b, by, first); - let moved = was.iter().zip(now).all(|pair| match pair { - (PathEl::MoveTo(a), PathEl::MoveTo(b)) | (PathEl::LineTo(a), PathEl::LineTo(b)) => near(a, b), - (PathEl::QuadTo(a0, a1), PathEl::QuadTo(b0, b1)) => near(a0, b0) && near(a1, b1), - (PathEl::CurveTo(a0, a1, a2), PathEl::CurveTo(b0, b1, b2)) => near(a0, b0) && near(a1, b1) && near(a2, b2), - (PathEl::ClosePath, PathEl::ClosePath) => true, - _ => false, - }); - moved.then_some(by) + let mut offset = Offset::new(); + (path_pairs(was, now, |a, b| offset.takes(a, b)) && path_pairs(was, now, |a, b| offset.holds(a, b))).then(|| offset.by()) } -/// The offset from first point `a` to first point `b` and the largest size of their coordinates, -/// which [`moved_by`] measures its tolerance with. `None` when the offset is not finite. -fn first_offset(a: kurbo::Point, b: kurbo::Point) -> Option<(kurbo::Vec2, f64)> { - let by = b - a; - by.is_finite().then(|| (by, a.x.abs().max(b.x.abs()).max(a.y.abs()).max(b.y.abs()))) +/// Whether `was` and `now` have the same elements, and `f` holds for each pair of their points. +/// Stops at the first pair for which `f` does not hold. +fn path_pairs(was: &BezPath, now: &BezPath, mut f: impl FnMut(kurbo::Point, kurbo::Point) -> bool) -> bool { + use kurbo::PathEl; + let (was, now) = (was.elements(), now.elements()); + was.len() == now.len() + && was.iter().zip(now).all(|pair| match pair { + (PathEl::MoveTo(a), PathEl::MoveTo(b)) | (PathEl::LineTo(a), PathEl::LineTo(b)) => f(*a, *b), + (PathEl::QuadTo(a0, a1), PathEl::QuadTo(b0, b1)) => f(*a0, *b0) && f(*a1, *b1), + (PathEl::CurveTo(a0, a1, a2), PathEl::CurveTo(b0, b1, b2)) => f(*a0, *b0) && f(*a1, *b1) && f(*a2, *b2), + (PathEl::ClosePath, PathEl::ClosePath) => true, + _ => false, + }) } -/// Whether `b` is `a` moved by `by`, each coordinate within a few units in the last place (see -/// [`offset_between`]; `first` from [`first_offset`]). -fn moved_by(a: kurbo::Point, b: kurbo::Point, by: kurbo::Vec2, first: f64) -> bool { - let close = |a: f64, by: f64, b: f64| (a + by - b).abs() <= 4.0 * f64::EPSILON * (a.abs() + b.abs() + first); - close(a.x, by.x, b.x) && close(a.y, by.y, b.y) +/// One offset between pairs of points. Pairs are read once with [`Offset::takes`], which measures +/// the offset on each axis at the pair with the smallest coordinates on that axis, and once more +/// with [`Offset::holds`], which checks every pair against that offset. +struct Offset { + by: [f64; 2], + size: [f64; 2], +} + +impl Offset { + fn new() -> Self { + Self { by: [0.0; 2], size: [f64::INFINITY; 2] } + } + + /// Whether `b` is `a` moved by the offset measured so far, on each axis within 3 units in the + /// last place of the larger of the pair's coordinates and those of the pair the offset was + /// measured at. A pair with smaller coordinates than any before it on an axis then measures the + /// offset on that axis. + fn takes(&mut self, a: kurbo::Point, b: kurbo::Point) -> bool { + [(a.x, b.x), (a.y, b.y)].into_iter().zip(self.by.iter_mut().zip(&mut self.size)).all(|((a, b), (by, size))| { + let at = a.abs().max(b.abs()); + if at.is_nan() || at >= *size { + return (b - a - *by).abs() <= 3.0 * ulp(at); + } + let near = size.is_infinite() || (b - a - *by).abs() <= 3.0 * ulp(*size); + (*by, *size) = (b - a, at); + near && by.is_finite() + }) + } + + /// Whether `b` is `a` moved by the offset, on each axis within 3 units in the last place of the + /// larger of the pair's coordinates: the most that rounding `b`, the pair the offset was measured + /// at (whose coordinates are no larger), and the two offsets can make together. + fn holds(&self, a: kurbo::Point, b: kurbo::Point) -> bool { + let near = |a: f64, b: f64, by: f64| (b - a - by).abs() <= 3.0 * ulp(a.abs().max(b.abs())); + near(a.x, b.x, self.by[0]) && near(a.y, b.y, self.by[1]) + } + + fn by(&self) -> kurbo::Vec2 { + kurbo::Vec2::new(self.by[0], self.by[1]) + } +} + +/// The distance from `x`, which is 0 or more, to the next larger `f64`. +fn ulp(x: f64) -> f64 { + f64::from_bits(x.to_bits() + 1) - x } /// Whether the anchors and handles of path `now` are those of path `was` moved by one offset, /// measured as [`offset_between`] measures it, with the same subpaths, anchor counts and closed /// subpaths. It reads the anchors without making either path ([`Node::stroke_path`]), and stops at /// the first anchor that differs. `false` for objects other than paths. -fn anchors_moved(was: &Node, now: &Node) -> bool { +pub(crate) fn anchors_moved(was: &Node, now: &Node) -> bool { let (vectorcraft_doc::NodeKind::Path { path: was, .. }, vectorcraft_doc::NodeKind::Path { path: now, .. }) = (&was.kind, &now.kind) else { return false; }; - if was.subpaths.len() != now.subpaths.len() { - return false; - } - let mut offset = None; - for (a, b) in was.subpaths.iter().zip(&now.subpaths) { - if a.closed != b.closed || a.anchors.len() != b.anchors.len() { - return false; - } - for (a, b) in a.anchors.iter().zip(&b.anchors) { - if offset.is_none() { - offset = first_offset(a.p, b.p); - } - let Some((by, first)) = offset else { return false }; - if !(moved_by(a.p, b.p, by, first) && moved_by(a.h_in, b.h_in, by, first) && moved_by(a.h_out, b.h_out, by, first)) { - return false; - } - } - } - true + let mut offset = Offset::new(); + anchor_pairs(was, now, |a, b| offset.takes(a, b)) && anchor_pairs(was, now, |a, b| offset.holds(a, b)) +} + +/// Whether `was` and `now` have the same subpaths, anchor counts and closed subpaths, and `f` holds +/// for each pair of their anchors and handles. Stops at the first pair for which `f` does not hold. +fn anchor_pairs(was: &vectorcraft_geom::PathData, now: &vectorcraft_geom::PathData, mut f: impl FnMut(kurbo::Point, kurbo::Point) -> bool) -> bool { + was.subpaths.len() == now.subpaths.len() + && was.subpaths.iter().zip(&now.subpaths).all(|(a, b)| { + a.closed == b.closed + && a.anchors.len() == b.anchors.len() + && a.anchors.iter().zip(&b.anchors).all(|(a, b)| f(a.p, b.p) && f(a.h_in, b.h_in) && f(a.h_out, b.h_out)) + }) } fn crops() -> bool { diff --git a/crates/render/src/tests/movedstroke.rs b/crates/render/src/tests/movedstroke.rs index 99d40cf487..de35aa592a 100644 --- a/crates/render/src/tests/movedstroke.rs +++ b/crates/render/src/tests/movedstroke.rs @@ -8,7 +8,7 @@ use vectorcraft_doc::{ }; use vectorcraft_geom::{PathData, Point, Vec2}; -use crate::renderer::{STROKES_OUTLINED, offset_between}; +use crate::renderer::{STROKES_OUTLINED, anchors_moved, offset_between}; use crate::*; const SIZE: u32 = 200; @@ -246,16 +246,84 @@ fn another_width_profile_outlines_the_stroke_again() { #[test] fn a_small_edit_far_from_the_origin_is_not_taken_for_a_move() { - let far = Affine::translate((1e9, -1e9)); - let was = far * zigzag(20); + for (far, edits) in [(1e9, &[0.5, 0.0005][..]), (1e15, &[0.5][..])] { + let was = Affine::translate((far, -far)) * zigzag(20); + let by = Vec2::new(0.25, 3.0); + let moved = Affine::translate(by) * was.clone(); + assert_eq!( + offset_between(&was, &moved), + Some(moved.elements()[0].end_point().unwrap() - was.elements()[0].end_point().unwrap()), + "at {far}: moved" + ); + let node = |bp: &BezPath| Node::path(NodeId(1), PathData::from_bezpath(bp), Appearance::default()); + let mut moved_node = node(&was); + moved_node.transform(Affine::translate(by), true); + assert!(anchors_moved(&node(&was), &moved_node), "at {far}: anchors moved"); + for &edit in edits { + let mut els = moved.elements().to_vec(); + if let Some(kurbo::PathEl::LineTo(p)) = els.get_mut(2) { + p.y += edit; + } + let edited = BezPath::from_vec(els); + assert_eq!(offset_between(&was, &edited), None, "at {far}: an anchor moved by {edit} pt"); + assert!(!anchors_moved(&node(&was), &node(&edited)), "at {far}: an anchor moved by {edit} pt, read from the anchors"); + // The third segment is a curve: its first handle. + let mut els = moved.elements().to_vec(); + if let Some(kurbo::PathEl::CurveTo(h, _, _)) = els.get_mut(3) { + h.x += edit; + } + assert!(!anchors_moved(&node(&was), &node(&BezPath::from_vec(els))), "at {far}: a handle moved by {edit} pt"); + } + } +} + +#[test] +fn an_edit_near_the_origin_is_not_taken_for_a_move_when_the_path_starts_far_from_it() { + // A subpath at 1e16 pt, where coordinates step by 2 pt, then one near the origin. + let mut was = BezPath::new(); + was.move_to((1e16, 1e16)); + was.line_to((1e16 + 64.0, 1e16)); + was.extend(zigzag(20)); let by = Vec2::new(0.25, 3.0); let moved = Affine::translate(by) * was.clone(); - assert_eq!(offset_between(&was, &moved), Some(moved.elements()[0].end_point().unwrap() - was.elements()[0].end_point().unwrap())); - let mut els = moved.elements().to_vec(); - if let Some(kurbo::PathEl::LineTo(p)) = els.get_mut(2) { - p.y += 0.0005; + assert_eq!(offset_between(&was, &moved), Some(by), "moved: the offset of the subpath near the origin"); + let node = |bp: &BezPath| Node::path(NodeId(1), PathData::from_bezpath(bp), Appearance::default()); + let mut moved_node = node(&was); + moved_node.transform(Affine::translate(by), true); + assert!(anchors_moved(&node(&was), &moved_node), "anchors moved"); + // The first and the third anchor of the subpath near the origin. + for at in [2, 4] { + for edit in [1.0, 0.5] { + let mut els = moved.elements().to_vec(); + if let Some(kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p)) = els.get_mut(at) { + p.y += edit; + } + let edited = BezPath::from_vec(els); + assert_eq!(offset_between(&was, &edited), None, "element {at} moved by {edit} pt"); + assert!(!anchors_moved(&node(&was), &node(&edited)), "element {at} moved by {edit} pt, read from the anchors"); + } } - assert_eq!(offset_between(&was, &BezPath::from_vec(els)), None, "an anchor moved by 0.0005 pt"); +} + +#[test] +fn points_each_near_the_one_before_are_checked_against_one_offset() { + let path = |xs: [f64; 3]| { + let mut bp = BezPath::new(); + bp.move_to((xs[0], 0.0)); + bp.line_to((xs[1], 0.0)); + bp.line_to((xs[2], 0.0)); + bp + }; + let node = |bp: &BezPath| Node::path(NodeId(1), PathData::from_bezpath(bp), Appearance::default()); + let was = path([1e16, 1e15, 1e14]); + // Coordinates step by 2, 0.125 and 0.015625 pt there. + let moved = Affine::translate((6.25, 0.0)) * was.clone(); + assert_eq!(offset_between(&was, &moved), Some(Vec2::new(6.25, 0.0)), "moved"); + assert!(anchors_moved(&node(&was), &node(&moved)), "anchors moved"); + // Each point is within rounding of the one before it, but the first did not move. + let edited = path([1e16, 1e15 + 6.0, 1e14 + 6.25]); + assert_eq!(offset_between(&was, &edited), None); + assert!(!anchors_moved(&node(&was), &node(&edited))); } #[test] From 44b828629d7ef397a9c802ea71aecd30a996b95f Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Wed, 4 Nov 2026 23:30:24 -0500 Subject: [PATCH 033/196] Rasterize: Color Model is a dropdown of the document's model, Grayscale and Bitmap (#5660) --- crates/ui-egui/src/dialogs/command.rs | 72 ++++++++++++++++++++++++++- 1 file changed, 71 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index ef781fb43d..0a722cbcf8 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -21,7 +21,9 @@ pub(super) const SPEC: DialogSpec = DialogSpec { // Area Type Options: a Row Gutter still as it opened, on rows without a gutter of their own, // follows the Gutter as it is changed. let linked = d.fields.get("__rowGutterLinked").is_some() && d.fields.get("__rowGutterLinked") == d.fields.get("rowGutter"); - form::param_fields(ui, d, &|k| lengths.contains(&k), &|k| choices(&command, k), &rank, app.session.general_unit()); + let cmyk = app.session.active().is_some_and(|s| s.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk); + let choices = |k: &str| rasterize_color_models(&command, k, cmyk).or_else(|| choices(&command, k)); + form::param_fields(ui, d, &|k| lengths.contains(&k), &choices, &rank, app.session.general_unit()); if linked && d.fields.get("rowGutter") == d.fields.get("__rowGutterLinked") && let Some(g) = d.fields.get("gutter").cloned() @@ -138,6 +140,19 @@ fn choices(command: &str, key: &str) -> Option { } } +/// Object › Rasterize › Color Model: the values `object.rasterize` takes, the document's own +/// colour model first (#5660). +fn rasterize_color_models(command: &str, key: &str, cmyk: bool) -> Option { + match (command, key) { + ("object.rasterize", "colorModel") => Some(if cmyk { RASTERIZE_CMYK } else { RASTERIZE_RGB }), + _ => None, + } +} + +/// Object › Rasterize › Color Model in an RGB and in a CMYK document. +const RASTERIZE_RGB: form::Choices = &[("RGB", "rgb"), ("Grayscale", "grayscale"), ("Bitmap", "bitmap")]; +const RASTERIZE_CMYK: form::Choices = &[("CMYK", "cmyk"), ("Grayscale", "grayscale"), ("Bitmap", "bitmap")]; + /// Type on a Path Options › Align to Path. const PATH_ALIGN: form::Choices = &[("Ascender", "ascender"), ("Descender", "descender"), ("Center", "center"), ("Baseline", "baseline")]; @@ -287,6 +302,61 @@ mod tests { assert_eq!(t.area.flow, vectorcraft_doc::TextFlow::Rows); } + /// Object › Rasterize › Color Model is a dropdown of the models `object.rasterize` takes, the + /// document's own first (#5660): every value runs, and picking Grayscale rasterizes in grays. + #[test] + fn rasterize_color_model_is_a_dropdown_of_the_models_the_command_takes() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + for (mode, own) in [("rgb", "RGB"), ("cmyk", "CMYK")] { + let models = rasterize_color_models("object.rasterize", "colorModel", mode == "cmyk").unwrap(); + assert_eq!(models.first(), Some(&(own, mode)), "the document's own model first"); + for (_, value) in models { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "colorMode": mode})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s.execute("object.rasterize", &json!({"ppi": 72, "colorModel": value})).unwrap_or_else(|e| panic!("{mode} {value}: {e}")); + } + } + assert!(rasterize_color_models("object.rasterize", "background", false).is_none()); + assert!(rasterize_color_models("document.rasterEffectsSettings", "colorModel", false).is_none()); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("paint.setFill", json!({"color": "#ff0000", "ids": [id]})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + crate::menus::invoke(&mut app, "object.rasterize", json!({})); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("colorModel"), "rgb"); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 900.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + crate::dialogs::show(app, ui.ctx()); + }, + app, + ); + h.run_steps(5); + assert!(h.query_by_role_and_label(Role::TextInput, "Color Model:").is_none(), "not a text field"); + h.get_by_role_and_label(Role::ComboBox, "Color Model:").click(); + h.run_steps(3); + h.get_by_label("Grayscale").click(); + h.run_steps(3); + assert_eq!(h.state().ui.dialog.as_ref().unwrap().str("colorModel"), "grayscale"); + let app = h.state_mut(); + crate::dialogs::confirm(app).unwrap(); + let st = app.session.active().unwrap(); + let key = st.selection.objects.iter().find_map(|id| match st.doc.node(*id).map(|n| &n.kind) { + Some(NodeKind::Image(i)) => Some(i.key.clone()), + _ => None, + }); + let img = image::load_from_memory(&st.doc.images[&key.expect("the rectangle became an image")].bytes).unwrap().to_rgba8(); + let p = img.get_pixel(img.width() / 2, img.height() / 2).0; + assert!(p[0] == p[1] && p[1] == p[2] && p[0] < 128, "red in grayscale: {p:?}"); + } + /// Graph Type › Value Axis is a dropdown of the values `graph.setType` takes, and OK puts the /// value axis on the side picked. #[test] From 1db874610f74ccee12f01dda9b5f37bfdd727bc8 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Thu, 5 Nov 2026 05:38:06 +0100 Subject: [PATCH 034/196] Keep Pencil and Paintbrush Fidelity in screen pixels at any zoom Fixes #5729 Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/draw2/freehand.rs | 4 +- crates/engine/src/tests/draw2.rs | 31 +++++++++-- crates/tools/src/draw2.rs | 8 ++- crates/tools/src/draw2/gesture.rs | 23 ++++---- crates/tools/src/draw2/gesture/tests.rs | 70 ++++++++++++++++++++++--- crates/ui-egui/src/dialogs/freehand.rs | 12 +++-- crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/control-protocol.md | 2 +- 8 files changed, 122 insertions(+), 30 deletions(-) diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index c6d974151d..8d95ee0017 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -12,7 +12,7 @@ use super::{ /// Fit a freehand polyline: drop jitter, build a spline through the samples (sharp turns stay /// corners) and simplify it to `tol`. fn fit_freehand(pts: &[Point], tol: f64, closed: bool) -> SubPath { - let min = (tol * 0.3).max(vectorcraft_tools::draw2::MIN_FIDELITY * 0.3); + let min = (tol * 0.3).max(vectorcraft_tools::draw2::MIN_FIT_TOLERANCE * 0.3); let (Some(&p0), Some(&pn)) = (pts.first(), pts.last()) else { return SubPath::new(vec![], closed) }; let mut kept: Vec = vec![p0]; for &p in pts.iter().skip(1) { @@ -150,7 +150,7 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result { } let pen = PenRecord::of_samples(&samples); let mut pts: Vec = samples.into_iter().map(|s| s.pt).collect(); - let tol = number_or(p, "fidelity", 1.5, C)?.clamp(vectorcraft_tools::draw2::MIN_FIDELITY, 100.0); + let tol = number_or(p, "fidelity", 1.5, C)?.clamp(vectorcraft_tools::draw2::MIN_FIT_TOLERANCE, 100.0); // The tolerance the stroke is fitted at; with `fit: false` it is not fitted. let fit_tol = switch_or(p, "fit", true, C)?.then_some(tol); let closed = switch_or(p, "closed", false, C)?; diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 30b1c4a3f7..f8d49b0b4d 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -3999,11 +3999,17 @@ fn pen_continue_at_a_first_anchor_in_a_compound_reverses_only_that_subpath() { /// The anchors of a closed, slightly wobbly blob drawn at `fidelity`: samples half a point apart, /// with a small tremor on top of the outline. fn blob_anchors(s: &mut Session, fidelity: f64) -> usize { + scaled_blob_anchors(s, fidelity, 1.0) +} + +/// [`blob_anchors`] with the blob scaled by `scale`: drawn the same on screen zoomed in 1 / `scale` +/// times. +fn scaled_blob_anchors(s: &mut Session, fidelity: f64, scale: f64) -> usize { let pts: Vec<_> = (0..1200) .map(|i| { let a = i as f64 / 1200.0 * std::f64::consts::TAU; let r = 90.0 + 12.0 * (3.0 * a).sin() + 0.15 * (97.0 * a).sin(); - json!([400.0 + r * a.cos(), 300.0 + r * a.sin()]) + json!([(400.0 + r * a.cos()) * scale, (300.0 + r * a.sin()) * scale]) }) .collect(); let r = s.execute("path.freehand", &json!({"points": pts, "closed": true, "fidelity": fidelity, "keepSelected": false})).unwrap(); @@ -4018,9 +4024,26 @@ fn pencil_fidelity_goes_down_to_a_hundredth_and_lower_keeps_more() { assert!(counts.windows(2).all(|w| w[0] <= w[1]), "{counts:?}"); // Below the old floor of 0.05 the stroke keeps more of itself. assert!(counts[4] > counts[2], "{counts:?}"); - // Below 0.01 is read as 0.01. - assert_eq!(blob_anchors(&mut s, 0.001), counts[4]); - assert_eq!(blob_anchors(&mut s, 0.0), counts[4]); + // Below the floor, the lowest Fidelity (0.01 px) at the highest zoom (64000 %), is read as the + // floor (#5729). + let floor = vectorcraft_tools::draw2::MIN_FIDELITY / 640.0; + let at_floor = blob_anchors(&mut s, floor); + assert!(at_floor >= counts[4], "{counts:?}"); + assert_eq!(blob_anchors(&mut s, floor / 10.0), at_floor); + assert_eq!(blob_anchors(&mut s, 0.0), at_floor); +} + +/// #5729: the tools send Fidelity / zoom, so a stroke drawn the same on screen zoomed in keeps as +/// many anchors, down to the lowest Fidelity at the highest zoom. +#[test] +fn pencil_fit_keeps_its_anchors_on_a_stroke_drawn_zoomed_in() { + let mut s = session(); + for fidelity in [1.5, 0.1, 0.01] { + let want = blob_anchors(&mut s, fidelity); + for zoom in [4.0, 64.0, 640.0] { + assert_eq!(scaled_blob_anchors(&mut s, fidelity / zoom, 1.0 / zoom), want, "{fidelity} at {zoom}x"); + } + } } /// At Fidelity 0.01 short, one-point and repeated-point strokes still draw or are refused, never diff --git a/crates/tools/src/draw2.rs b/crates/tools/src/draw2.rs index 23e61e602c..123082aa25 100644 --- a/crates/tools/src/draw2.rs +++ b/crates/tools/src/draw2.rs @@ -26,10 +26,14 @@ pub use gesture::GestureTool; /// Colour of tool feedback (Illustrator's selection blue). pub const FEEDBACK: [u8; 3] = [0x4f, 0x9d, 0xff]; -/// The lowest Fidelity (points) the Pencil and Paintbrush take (#3328); the Smooth tool keeps -/// [`SMOOTH_MIN_FIDELITY`]. +/// The lowest Fidelity the Pencil and Paintbrush take (#3328; screen pixels, points for the Blob +/// Brush); the Smooth tool keeps [`SMOOTH_MIN_FIDELITY`]. pub const MIN_FIDELITY: f64 = 0.01; +/// The finest tolerance (points) `path.freehand` fits a Pencil or Paintbrush stroke at: the lowest +/// Fidelity at the highest zoom (64000 %), whose screen pixels the tools send in points (#5729). +pub const MIN_FIT_TOLERANCE: f64 = MIN_FIDELITY / 640.0; + /// The lowest Fidelity (points) the Smooth tool takes. pub const SMOOTH_MIN_FIDELITY: f64 = 0.05; diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index 80d9ac9b1c..495e932a4b 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -66,7 +66,9 @@ pub struct GestureTool { /// Pencil/Paintbrush starting on a selected path away from its ends: (path, Edit Selected /// Paths' distance in points); the stroke redraws the section it ends on (#2850). redraw: Option<(NodeId, f64)>, - /// Fit tolerance in points (Pencil/Paintbrush/Smooth/Blob Brush "Fidelity"). + /// Fit tolerance (Pencil/Paintbrush/Smooth/Blob Brush "Fidelity"): in screen pixels for the + /// Pencil and the Paintbrush, so a stroke keeps as many points at any zoom (#5729), in points + /// for the others. pub fidelity: f64, /// Brush / eraser diameter in points (the Eraser's across its tip's long axis). pub size: f64, @@ -453,11 +455,12 @@ impl GestureTool { self.draws_path() && !self.smoothing && !self.straight && self.extend.is_none() && self.redraw.is_none() && self.ends_near_start(cx, end) } - /// Parameters of `path.freehand` for the current stroke. - pub fn freehand_params(&self, closed: bool) -> Value { + /// Parameters of `path.freehand` for the current stroke, fitted at Fidelity on screen. Only the + /// Pencil and the Paintbrush (`draws_path`) send it; the Blob Brush's Fidelity stays in points. + pub fn freehand_params(&self, cx: &ToolContext, closed: bool) -> Value { let mut v = json!({ "points": self.stroke_json(), - "fidelity": self.fidelity, + "fidelity": cx.tol(self.fidelity), "closed": closed, "style": if self.id == "paintbrush" { "brush" } else { "pencil" }, "fill": self.fill, @@ -494,7 +497,7 @@ impl GestureTool { let near = pts.last().is_some_and(|&end| self.ends_near_start(cx, end)); // A straight line has two points: closing it would draw it back over itself. let closed = !self.straight && ((m.alt && (self.id == "paintbrush" || !self.alt_smooth)) || (self.extend.is_none() && near)); - let mut params = self.freehand_params(closed); + let mut params = self.freehand_params(cx, closed); // A Pencil stroke that continues a selected path and ends on an open end of another // path selected at the press connects the two. let connect = pts.last().and_then(|&end| self.find_end(cx, end, &self.connect_to)); @@ -649,9 +652,9 @@ impl Tool for GestureTool { } // With the Pencil's Live preview off a thin line shows instead (`overlays`). if self.previews() && crate::previews_at(self.points.len()) { - let mut v = self.freehand_params(false); - let fidelity = self.fidelity.max(cx.tol(PREVIEW_FIDELITY_PX)); - v["fidelity"] = json!(fidelity); + let mut v = self.freehand_params(cx, false); + let fidelity = self.fidelity.max(PREVIEW_FIDELITY_PX); + v["fidelity"] = json!(cx.tol(fidelity)); // A preview fitted coarser than the stroke kept is stale (`deactivate`). self.previewed = if fidelity > self.fidelity { 0 } else { self.points.len() }; if !self.live_fit { @@ -748,13 +751,13 @@ impl Tool for GestureTool { fn hover_ended(&mut self, _cx: &ToolContext) { self.tip_at = None; } - fn deactivate(&mut self, _cx: &ToolContext) -> Vec { + fn deactivate(&mut self, cx: &ToolContext) -> Vec { let began = self.began; self.tip_at = None; // Drags past the last preview are in the stroke kept, too, and with Live curve fitting // off the stroke kept is fitted. let stale = (began && (self.previewed != self.points.len() || !self.live_fit) && self.draws_path() && !self.smoothing) - .then(|| Action::Preview("path.freehand".into(), self.freehand_params(false))); + .then(|| Action::Preview("path.freehand".into(), self.freehand_params(cx, false))); self.snap.clear(); self.active = false; self.near_start = false; diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 20cc489af5..c0ef91d240 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -154,7 +154,8 @@ fn pencil_with_live_curve_fitting_off_previews_the_stroke_unfitted() { /// A stroke whose Fidelity is finer than half a screen pixel previews fitted at half a pixel, which /// looks the same at a fraction of the fit's cost (#4565); the release, and another tool chosen -/// while it is drawn, fit it at its own Fidelity. A coarser Fidelity previews as it is kept. +/// while it is drawn, fit it at its own Fidelity. A coarser Fidelity previews as it is kept. Fidelity +/// is in screen pixels, so the stroke is fitted in points at Fidelity / zoom (#5729). #[test] fn fine_fidelity_previews_at_half_a_pixel() { let (d, _) = doc_with_rect(); @@ -166,26 +167,83 @@ fn fine_fidelity_previews_at_half_a_pixel() { acts.iter().filter_map(|a| if let Action::Preview(_, v) = a { v["fidelity"].as_f64() } else { None }).collect() }; for id in ["pencil", "paintbrush"] { - for (zoom, fidelity, drawn) in [(1.0, 0.01, 0.5), (4.0, 0.01, 0.125), (1.0, 1.5, 1.5)] { + for (zoom, fidelity, drawn, kept) in [(1.0, 0.01, 0.5, 0.01), (4.0, 0.01, 0.125, 0.0025), (1.0, 1.5, 1.5, 1.5), (4.0, 1.5, 0.375, 0.375)] { cx.zoom = zoom; let mut t = GestureTool::new(id); t.set_option("fidelity", &json!(fidelity)); let acts = drag(&mut t, &cx, &stroke, Mods::default()); let (release, during) = acts.split_last().unwrap(); - assert_eq!(fidelities(&during.concat()), [drawn; 3], "{id} at {zoom}x, {fidelity} pt"); - assert_eq!(fidelities(release), [fidelity], "{id} at {zoom}x, {fidelity} pt: the release"); + assert_eq!(fidelities(&during.concat()), [drawn; 3], "{id} at {zoom}x, {fidelity} px"); + assert_eq!(fidelities(release), [kept], "{id} at {zoom}x, {fidelity} px: the release"); t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 0.0, 0.0)); for &(x, y) in &stroke[1..] { t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x, y)); } let acts = t.deactivate(&cx); - let kept = if drawn > fidelity { [fidelity].to_vec() } else { vec![] }; - assert_eq!(fidelities(&acts), kept, "{id} at {zoom}x, {fidelity} pt: another tool chosen"); + let stale = if drawn > kept { [kept].to_vec() } else { vec![] }; + assert_eq!(fidelities(&acts), stale, "{id} at {zoom}x, {fidelity} px: another tool chosen"); assert_eq!(acts.last(), Some(&Action::Commit)); } } } +/// #5729: the Pencil's and the Paintbrush's Fidelity is in screen pixels. The same stroke drawn on +/// screen at 1x and at 4x is fitted at the same tolerance on screen, so it keeps as many points +/// whatever the zoom (another tool chosen mid-stroke: `fine_fidelity_previews_at_half_a_pixel`). +#[test] +fn fidelity_is_in_screen_pixels_at_any_zoom() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let mut cx = cx(&d, &s, &p); + let screen = [(0.0, 0.0), (40.0, 20.0), (80.0, 0.0), (120.0, 20.0)]; + for id in ["pencil", "paintbrush"] { + let on_screen = |cx: &ToolContext, zoom: f64| { + let pts: Vec<_> = screen.iter().map(|&(x, y)| (x / zoom, y / zoom)).collect(); + let mut t = GestureTool::new(id); + t.set_option("fidelity", &json!(1.5)); + let acts = drag(&mut t, cx, &pts, Mods::default()); + let Some(Action::Preview(_, v)) = acts.last().and_then(|a| a.first()) else { panic!("{acts:?}") }; + v["fidelity"].as_f64().unwrap() * zoom + }; + cx.zoom = 1.0; + let at_1 = on_screen(&cx, 1.0); + cx.zoom = 4.0; + let at_4 = on_screen(&cx, 4.0); + assert_eq!(at_1, 1.5, "{id}"); + assert_eq!(at_4, at_1, "{id}: fidelity in screen px at 1x vs 4x"); + } +} + +/// The Blob Brush's Fidelity stays in points (#5729 is the Pencil's and the Paintbrush's): its +/// stroke, and another tool chosen while it is drawn, send it as set at any zoom. +#[test] +fn blob_brush_fidelity_stays_in_points_at_any_zoom() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let mut cx = cx(&d, &s, &p); + let stroke = [(0.0, 0.0), (40.0, 20.0), (80.0, 0.0), (120.0, 20.0)]; + for zoom in [1.0, 4.0] { + cx.zoom = zoom; + let mut t = GestureTool::new("blobBrush"); + t.set_option("fidelity", &json!(1.5)); + let acts = drag(&mut t, &cx, &stroke, Mods::default()); + let sent: Vec<_> = acts + .concat() + .into_iter() + .filter_map(|a| if let Action::Exec(_, v) | Action::Preview(_, v) = a { v["fidelity"].as_f64() } else { None }) + .collect(); + assert_eq!(sent, [1.5], "at {zoom}x"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 0.0, 0.0)); + for &(x, y) in &stroke[1..] { + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x, y)); + } + let acts = t.deactivate(&cx); + assert!(!acts.iter().any(|a| matches!(a, Action::Preview(id, _) if id == "path.freehand")), "at {zoom}x: {acts:?}"); + } +} + /// Keep selected is on by default, and every Pencil and Paintbrush preview sends it. #[test] fn pencil_and_paintbrush_send_keep_selected() { diff --git a/crates/ui-egui/src/dialogs/freehand.rs b/crates/ui-egui/src/dialogs/freehand.rs index 7660287753..f2eb124776 100644 --- a/crates/ui-egui/src/dialogs/freehand.rs +++ b/crates/ui-egui/src/dialogs/freehand.rs @@ -3,7 +3,8 @@ //! preferences. OK sets them with `tool.setOption {tool, values}`. The Pencil also has `liveFit` //! (Live curve fitting, on: its preview fits the stroke while it is drawn). //! -//! Fields: `tool`; `fidelity` (points; Pencil, Paintbrush, Smooth and Blob Brush), `fill` (Pencil and +//! Fields: `tool`; `fidelity` (screen pixels for the Pencil and Paintbrush, points for Smooth and +//! Blob Brush), `fill` (Pencil and //! Paintbrush), `keepSelected` (Pencil, Paintbrush and Blob Brush), `mergeOnlySelection` (Blob //! Brush), `closeWithin` and `editWithin` (screen pixels, 0 turns it off; Pencil and Paintbrush), //! `angle` (degrees) and `roundness` (percent; Blob Brush and Eraser), `livePreview` (Pencil: the stroke shows @@ -166,16 +167,19 @@ fn blob_size(ui: &mut egui::Ui, d: &mut Dialog) { fn fidelity(ui: &mut egui::Ui, d: &mut Dialog) { let t = Tokens::get(ui.ctx()); let v = d.f64("fidelity", 1.5); - let rail = (vectorcraft_tools::draw2::min_fidelity(&d.str("tool")), FIDELITY_MAX); + let tool = d.str("tool"); + let rail = (vectorcraft_tools::draw2::min_fidelity(&tool), FIDELITY_MAX); + // The Pencil's and the Paintbrush's Fidelity is on screen, the same at any zoom (#5729). + let unit = if matches!(tool.as_str(), "pencil" | "paintbrush") { "px" } else { "pt" }; let rail_w = label_w(ui); let mut new = None; ui.label(egui::RichText::new(tl!("Fidelity:")).size(12.5).color(t.text)); ui.horizontal(|ui| { - let shown = widgets::SliderValue::field(v, rail.0..=rail.1, "pt", 2).with_step(fidelity_step); + let shown = widgets::SliderValue::field(v, rail.0..=rail.1, unit, 2).with_step(fidelity_step); let (x, _, keyed) = widgets::color_slider_stepped(ui, "freehand-fidelity", tl!("Fidelity:"), Some(shown), fidelity_at(v, rail), rail_w, &|_| t.input_border); new = x.map(|x| fidelity_from(x, rail)).or(keyed); - if let Some(x) = widgets::range_field_stepped(ui, "freehand-fidelity-field", v, rail.0..=100.0, "pt", 2, FIELD_W, fidelity_step) { + if let Some(x) = widgets::range_field_stepped(ui, "freehand-fidelity-field", v, rail.0..=100.0, unit, 2, FIELD_W, fidelity_step) { new = Some(x); } }); diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index a3bda35231..02fd4ba5f5 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -777,7 +777,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph (dialog `command` running graph.setType; an error without one), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (pt), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph (dialog `command` running graph.setType; an error without one), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil and paintbrush, the same at any zoom; pt for smooth and blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 04d76ae904..191be79756 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -861,7 +861,7 @@ events take `pressure` (0..1, default 1): it is the Liquify intensity while Use Freehand Tool Options: double-clicking the Pencil, Paintbrush, Smooth, Blob Brush or Eraser tool (`tool.options {tool: "pencil"}`) opens a `freehandOptions` dialog. Its fields are `tool` and the options the tool -keeps: `fidelity` (pt; Pencil, Paintbrush, Smooth, Blob Brush), `fill` (Pencil, Paintbrush), `keepSelected` (Pencil, +keeps: `fidelity` (screen pixels for the Pencil and Paintbrush, the same at any zoom; pt for Smooth and Blob Brush), `fill` (Pencil, Paintbrush), `keepSelected` (Pencil, Paintbrush, Blob Brush; on by default for the Pencil and Paintbrush and off for the Blob Brush, and while it is off the path a stroke draws, continues or merges into is not selected afterwards), `mergeOnlySelection` (Blob Brush; off by default, and while it is on a stroke merges only with selected blobs), `closeWithin` and `editWithin` From f3a00b13837184779f050262f6e3f642ffdfa58f Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 5 Nov 2026 11:51:49 +0700 Subject: [PATCH 035/196] Tests: the Pencil's Fidelity slider reads in px --- crates/ui-egui/src/dialogs/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index d369199f4c..c2a7aa2b1d 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1984,7 +1984,7 @@ fn dialog_sliders_report_the_numbers_their_fields_show() { app.run("tool.options", json!({"tool": "pencil"})).unwrap(); set(&mut app, "fidelity", json!(2.5)); let shown = tree(|ui| show(&mut app, ui.ctx())); - assert_eq!(slider_value(&shown, "Fidelity:"), v(2.5, (0.01, 20.0), "2.5pt")); + assert_eq!(slider_value(&shown, "Fidelity:"), v(2.5, (0.01, 20.0), "2.5px"), "the Pencil's Fidelity is on screen (#5729)"); // The Smooth tool's rail starts at its own lowest Fidelity. app.ui.dialog = None; app.run("tool.options", json!({"tool": "smooth"})).unwrap(); From e0645341a41f5cba0beed6ff70343520711fff61 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Thu, 5 Nov 2026 09:30:30 +0530 Subject: [PATCH 036/196] Document tabs: drag a tab along the strip to reorder the open documents (#5663) A document tab dragged sideways along the tab strip moves its document to the place an insertion line marks; the current document stays current. Dragged above or below the strip, the tab still tears off into a floating window. The views Window > New Window opened move with their document, and each document keeps its own zoom, centre and artboard. The move is the engine command `document.move {from?, to}`, so the control channel, MCP and recordings reach it, and a replay moves the document before the steps recorded after it. `sync_views` keeps the views with their documents by uid when the documents change order. Behaviour: https://helpx.adobe.com/illustrator/using/customizing-workspace.html Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/edit.rs | 26 ++++ crates/engine/src/session/documents.rs | 21 +++ crates/engine/src/tests.rs | 1 + crates/engine/src/tests/document_move.rs | 133 +++++++++++++++++ crates/engine/tests/command_sweep.rs | 4 + crates/ui-egui/src/app.rs | 2 + crates/ui-egui/src/app/view.rs | 19 +++ crates/ui-egui/src/chrome.rs | 2 +- crates/ui-egui/src/chrome/tabs.rs | 69 ++++++++- crates/ui-egui/src/chrome/tests.rs | 50 +++++++ crates/ui-egui/src/document_drag.rs | 6 + crates/ui-egui/src/lib.rs | 4 + crates/ui-egui/src/tests.rs | 1 + crates/ui-egui/src/tests/tab_reorder.rs | 173 +++++++++++++++++++++++ docs/gaps.md | 4 +- docs/target-app-parity.md | 4 +- docs/ui-parity.md | 4 +- 17 files changed, 518 insertions(+), 5 deletions(-) create mode 100644 crates/engine/src/tests/document_move.rs create mode 100644 crates/ui-egui/src/tests/tab_reorder.rs diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 41276c2326..e022998fa0 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -29,6 +29,15 @@ pub fn specs() -> Vec { ), cmd!("file.close", "Close", ["File"], Some("Cmd+W"), "{index?}", has_doc, file_close), cmd!("document.activate", "Activate Document", [], None, "{index}", always, doc_activate), + cmd!( + "document.move", + "Move Document", + [], + None, + "{from?: index (default: the current document), to: index (0 = the first tab; past the last document = the last tab)} → {index}: moves the document to tab `to`, as dragging its tab along the tab strip does; the documents between shift by one, the order Window › Next/Previous Document steps through follows, and the current document stays the current one", + has_doc, + doc_move + ), cmd!(query "document.inspect", "Inspect Document", [], None, "{depth?, childLimit?, ids?: [id…] (list just these nodes, of any level, in this order, under `nodes` in place of `layers`; an unknown id is an error; at most 10000), kind?: panel label such as Layer; Group; Path; Type or Image (exact, ignoring case; list every such node under `nodes`, each with `path`, its ancestor ids with the layer first, searching the subtrees of `ids` when given), limit?: at most this many entries of the list, offset?: entries skipped first (default 0; with `ids`, `kind`, `limit` or `offset` the reply adds `total`, the entries before paging)} → layer tree (each node: id, name, kind, visible, locked, bounds, opacity (0–1) and opacityPct (0–100 %, the scale object.setProps takes) when below 1, blend when not Normal, fill, stroke and strokeWidth of objects and compound paths; a compound path's members have compoundMember: true instead of paint, which is the compound's), artboards, selection, history (a sliced tree reports childCount); without the scope options the reply is the whole layer tree", has_doc, doc_inspect), cmd!(query "document.node", "Inspect Object", [], None, "{id, summary?: compact summary, depth?: child levels in the summary (default all), childLimit?: children shown per node (default all; a level that shows fewer reports childCount)} → one object", has_doc, doc_node), cmd!(query "document.find", "Find Objects", [], None, "{name?: substring of the Layers panel name, kind?: panel label such as Group; Path; Type or Image (exact), text?: substring of type content, within?: [x, y, width, height] (an object's geometric bounds inside this rectangle, edges included; document points as document.inspect's bounds; layers never match this or the size filters), intersects?: [x, y, width, height] (bounds touching or overlapping it), minWidth?, maxWidth?, minHeight?, maxHeight?: pt (the bounds' size), minThickness?, maxThickness?: pt (the smaller of the bounds' width and height), minArea?, maxArea?: pt² (the bounds' width × height), minAnchors?, maxAnchors?: anchor points of a path (a compound path's members together; other objects never match), select?: bool (also select the matches, leaving out hidden and locked ones, those inside another match, and a compound path's members unless the compound path is isolated; Select > Reselect repeats it), limit?: max matches listed (default 100, 0 counts only)} → {matches: [{id, name, kind, path}], total, selected (with select: the count selected)}; at least one filter, all of them matching", has_doc, doc_find), @@ -222,6 +231,23 @@ fn doc_activate(s: &mut Session, p: &Value) -> Result { if s.set_active(i) { ok() } else { Err(bad("document.activate", "no such document")) } } +fn doc_move(s: &mut Session, p: &Value) -> Result { + let n = s.documents().len(); + let from = match p.get("from") { + None | Some(Value::Null) => s.active_index().ok_or(EngineError::NoDocument)?, + Some(v) => v.as_u64().map(index).ok_or_else(|| bad("document.move", "`from` must be a non-negative integer"))?, + }; + if from >= n { + return Err(bad("document.move", "no such document")); + } + let to = p.get("to").and_then(Value::as_u64).map(index).ok_or_else(|| bad("document.move", "missing `to`: a non-negative integer"))?; + let to = to.min(n.saturating_sub(1)); + if !s.move_document(from, to) { + return Err(bad("document.move", "no such document")); + } + Ok(json!({ "index": to })) +} + fn doc_node(s: &mut Session, p: &Value) -> Result { let id = id_param(p, "id").ok_or_else(|| bad("document.node", "missing id"))?; let mut opts = slice_opts(p, "document.node")?; diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 6b048e6fa3..41946c0ebd 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -292,6 +292,27 @@ impl Session { true } + /// Move the document in tab `from` to tab `to` (a document tab dragged along the strip, + /// `document.move`); the documents between them shift by one. The current document stays the + /// current one, wherever it moves to, and its tool keeps its state: no document is switched to. + /// False, changing nothing, when either index is past the last document. + pub fn move_document(&mut self, from: usize, to: usize) -> bool { + let n = self.docs.len(); + if from >= n || to >= n { + return false; + } + if from == to { + return true; + } + let active = self.active().map(|d| d.uid); + let d = self.docs.remove(from); + self.docs.insert(to, d); + if let Some(uid) = active { + self.active = self.docs.iter().position(|d| d.uid == uid); + } + true + } + /// Commands with enablement (for menus, palette, MCP `list_commands`). pub fn commands(&self) -> Vec { command_specs().iter().map(|c| c.info(self)).collect() diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a1fa3e0487..9ec3ccaf98 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -41,6 +41,7 @@ mod cut; mod dashalign; mod distort; mod docsetup; +mod document_move; mod draw2; mod dynamic_symbols; mod editcolors; diff --git a/crates/engine/src/tests/document_move.rs b/crates/engine/src/tests/document_move.rs new file mode 100644 index 0000000000..f68c729081 --- /dev/null +++ b/crates/engine/src/tests/document_move.rs @@ -0,0 +1,133 @@ +//! `document.move` (#5663): a document tab dragged along the tab strip moves its document to +//! another place among the open documents, and the current document stays the current one. + +use serde_json::{Value, json}; + +use crate::*; + +/// A session with documents A, B, C and D, in that order, D current. +fn four() -> Session { + let mut s = Session::new(); + for name in ["A", "B", "C", "D"] { + s.execute("file.new", &json!({"name": name, "created": null})).unwrap(); + } + s +} + +fn order(s: &Session) -> String { + s.documents().iter().map(DocState::title).collect::>().join("") +} + +fn current(s: &Session) -> String { + s.active().map(DocState::title).unwrap_or_default() +} + +fn moved(s: &mut Session, p: Value) -> Value { + s.execute("document.move", &p).unwrap_or_else(|e| panic!("document.move {p}: {e}")) +} + +#[test] +fn a_document_moves_to_its_new_tab_and_the_others_shift() { + let mut s = four(); + assert_eq!(order(&s), "ABCD"); + assert_eq!(moved(&mut s, json!({"from": 0, "to": 2})), json!({"index": 2})); + assert_eq!(order(&s), "BCAD", "forward: the documents between shift left"); + assert_eq!(moved(&mut s, json!({"from": 3, "to": 0})), json!({"index": 0})); + assert_eq!(order(&s), "DBCA", "backward: the documents between shift right"); + assert_eq!(moved(&mut s, json!({"from": 1, "to": 1})), json!({"index": 1})); + assert_eq!(order(&s), "DBCA", "onto itself: nothing changes"); +} + +#[test] +fn the_current_document_stays_current_wherever_the_move_puts_it() { + let mut s = four(); + assert!(s.set_active(1)); + // The current document itself moves. + moved(&mut s, json!({"from": 1, "to": 3})); + assert_eq!((order(&s), current(&s)), ("ACDB".into(), "B".into())); + assert_eq!(s.active_index(), Some(3)); + // A document moves past the current one, which shifts by one. + moved(&mut s, json!({"from": 3, "to": 0})); + moved(&mut s, json!({"from": 3, "to": 0})); + assert_eq!((order(&s), current(&s)), ("DBAC".into(), "B".into())); + assert_eq!(s.active_index(), Some(1)); + // A move on one side of the current document leaves it where it is. + moved(&mut s, json!({"from": 2, "to": 3})); + assert_eq!((order(&s), current(&s)), ("DBCA".into(), "B".into())); + assert_eq!(s.active_index(), Some(1)); +} + +#[test] +fn without_from_the_current_document_moves() { + let mut s = four(); + assert!(s.set_active(2)); + moved(&mut s, json!({"to": 0})); + assert_eq!((order(&s), current(&s)), ("CABD".into(), "C".into())); +} + +#[test] +fn a_move_past_the_last_tab_ends_there_and_bad_indices_change_nothing() { + let mut s = four(); + assert_eq!(moved(&mut s, json!({"from": 0, "to": 99})), json!({"index": 3})); + assert_eq!(order(&s), "BCDA"); + assert_eq!(moved(&mut s, json!({"from": 0, "to": u64::MAX})), json!({"index": 3})); + assert_eq!(order(&s), "CDAB"); + for p in [ + json!({"from": 4, "to": 0}), + json!({"from": u64::MAX, "to": 0}), + json!({"from": 0}), + json!({"from": -1, "to": 0}), + json!({"from": 0, "to": "1"}), + ] { + assert!(s.execute("document.move", &p).is_err(), "{p} is refused"); + assert_eq!(order(&s), "CDAB", "{p} changes nothing"); + } + assert!(!s.move_document(0, 4)); + assert!(!s.move_document(4, 0)); + assert_eq!(order(&s), "CDAB"); +} + +#[test] +fn moving_needs_an_open_document_and_one_document_stays_put() { + let mut s = Session::new(); + assert!(s.execute("document.move", &json!({"to": 0})).is_err(), "no document open"); + s.execute("file.new", &json!({"name": "A", "created": null})).unwrap(); + assert_eq!(moved(&mut s, json!({"to": 5})), json!({"index": 0})); + assert_eq!((order(&s), current(&s)), ("A".into(), "A".into())); +} + +#[test] +fn a_move_keeps_the_tool_and_the_documents_edits() { + let mut s = four(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let resets = s.tool_resets; + let nodes = s.doc().unwrap().doc.node_count(); + let history = super::history(&s); + moved(&mut s, json!({"from": 3, "to": 0})); + assert_eq!(super::history(&s), history, "a move is no undo step, and it keeps Redo"); + assert_eq!(s.tool_resets, resets, "no document was switched to, so the tool is not reset"); + assert_eq!(s.doc().unwrap().doc.node_count(), nodes); + assert!(s.doc().unwrap().is_dirty(), "the document keeps its unsaved edit"); +} + +/// A recording replays the move before the steps after it, so an `index` they name is the same +/// document as when they were recorded. +#[test] +fn a_journaled_move_replays_in_order() { + let mut s = four(); + for (id, p) in [ + ("document.move", json!({"from": 0, "to": 3})), + ("document.activate", json!({"index": 3})), + ("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})), + ] { + s.execute(id, &p).unwrap(); + } + assert_eq!((order(&s), current(&s)), ("BCDA".into(), "A".into())); + let mut r = Session::new(); + for (id, p) in &s.journal { + r.execute(id, p).unwrap(); + } + assert_eq!((order(&r), current(&r)), ("BCDA".into(), "A".into())); + let counts = |s: &Session| s.documents().iter().map(|d| d.doc.node_count()).collect::>(); + assert_eq!(counts(&r), counts(&s), "the rectangle is in the same document after the replay"); +} diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 0db8cc655c..b8b360b804 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -526,6 +526,10 @@ fn structured_junk() { ("document.open", json!({"name": "x.pdf", "dataBase64": "JVBERi0xLjQK"})), ("document.open", json!({"name": "x.vectorcraft", "dataBase64": "e30="})), ("document.activate", json!({"index": 99})), + ("document.move", json!({"from": 99, "to": 0})), + ("document.move", json!({"from": 0, "to": u64::MAX})), + ("document.move", json!({"from": -1, "to": 1e308})), + ("document.move", json!({"from": "x", "to": null})), ("file.close", json!({"index": 99})), ("file.new", json!({"width": -1, "height": 0, "artboards": 1000000})), ("command.batch", json!({"commands": [{"command": 5}, {"params": 3}]})), diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 7826cdfe32..c3869c5990 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -54,11 +54,13 @@ impl VectorcraftApp { // ([`place::place_from_cursor`]). session.place_cursor_requests = true; let views = session.documents().iter().map(View::of).collect(); + let view_uids = session.documents().iter().map(|d| d.uid).collect(); let known = session.documents().iter().map(|d| d.uid).collect(); Self { session, ui: UiState::default(), views, + view_uids, services, canvas: CanvasCache { renderer: vectorcraft_render::Renderer::new(), diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index 6b5db4fb5b..a1c898b719 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -4,13 +4,32 @@ impl VectorcraftApp { /// Keep `views` aligned with the session's documents (a new one starts at its saved view, and /// opens in a floating window while Open Documents As Tabs is cleared). The views Window › New /// Window opened go with their documents. + /// + /// A view stays with its document when the documents change order (`document.move`, also in a + /// recording or a batch, #5663): while every view still has the document it was synced with, + /// they are put in the documents' order by uid. Code that removed a view by hand (closing a + /// document) leaves them aligned by index, as before. pub fn sync_views(&mut self) { let docs = self.session.documents(); + if self.view_uids.len() == self.views.len() + && docs.len() == self.views.len() + && docs.iter().map(|d| d.uid).ne(self.view_uids.iter().copied()) + && docs.iter().all(|d| self.view_uids.contains(&d.uid)) + { + let mut old: Vec> = std::mem::take(&mut self.views).into_iter().map(Some).collect(); + self.views = docs + .iter() + .map(|d| { + self.view_uids.iter().position(|u| *u == d.uid).and_then(|k| old.get_mut(k)).and_then(Option::take).unwrap_or_else(|| View::of(d)) + }) + .collect(); + } self.views.truncate(docs.len()); self.views.extend(docs.iter().skip(self.views.len()).map(View::of)); for (view, doc) in self.views.iter_mut().zip(docs) { view.artboard = view.artboard.min(doc.doc.artboards.len().saturating_sub(1)); } + self.view_uids = docs.iter().map(|d| d.uid).collect(); crate::doc_windows::retain_views(self); crate::doc_windows::opened(self); // Undo can remove the Artboard tool's active or additionally selected boards. Repair only diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index eecaa22fd3..41d73ffaef 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -28,7 +28,7 @@ pub use status_bar::status_bar; #[cfg(test)] use status_bar::{StatusReadoutWidths, status_readouts}; #[cfg(test)] -use tabs::{CLOSE_BEFORE_TITLE, first_tab_shown, tab_title}; +use tabs::{CLOSE_BEFORE_TITLE, first_tab_shown, tab_drop, tab_groups, tab_title}; pub use tabs::{doc_tabs, isolation_bar, step_document}; pub(crate) use tabs::{document_window_title, show_document, window_tab}; diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index d81e2fb973..4d5f75821b 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -79,6 +79,40 @@ fn tear_off(ui: &Ui, resp: &egui::Response, strip: egui::Rect) -> Option Vec<(usize, egui::Rangef)> { + let mut groups: Vec<(usize, egui::Rangef)> = vec![]; + for &(i, r) in slots { + match groups.last_mut() { + Some((d, span)) if *d == i => span.max = span.max.max(r.right()), + _ => groups.push((i, egui::Rangef::new(r.left(), r.right()))), + } + } + groups +} + +/// Where document `from`'s tabs, dragged along the strip to `x`, go among the other documents' +/// tabs in `groups` ([`tab_groups`]): before the first whose middle is right of `x`, else after +/// the last. → the document's new index among all the open documents (floating ones and those +/// whose tabs don't fit included) and the x of the gap the drop goes in; `None` when the drop +/// leaves the document where it is, or there is no other tab to drop beside. +pub(super) fn tab_drop(groups: &[(usize, egui::Rangef)], from: usize, x: f32) -> Option<(usize, f32)> { + let others: Vec<&(usize, egui::Rangef)> = groups.iter().filter(|(d, _)| *d != from).collect(); + let slot = others.iter().filter(|(_, span)| span.center() < x).count(); + let (to, gap) = match others.get(slot) { + // Before document `d`: it shifts left by one when `from` was before it. + Some(&&(d, span)) => (if from < d { d - 1 } else { d }, span.min), + // After the last tab shown. + None => { + let &&(d, span) = others.last()?; + (if from < d { d } else { d + 1 }, span.max) + } + }; + (to != from).then_some((to, gap)) +} + /// Whether a document tab's × comes before its title (macOS) rather than after it (Windows, /// Linux and the web). pub(super) const CLOSE_BEFORE_TITLE: bool = cfg!(target_os = "macos"); @@ -100,7 +134,9 @@ pub(super) fn first_tab_shown(widths: &[f32], active: Option, room: f32) /// Each view Window › New Window opened has a tab of its own. Windows floating have no tab /// ([`crate::doc_windows`]); while the current window is a floating one, the tab of the window the /// strip shows is the highlighted one. A tab dragged more than [`crate::doc_windows::TEAR_OFF`] -/// above or below the strip floats its view in a window under the pointer. +/// above or below the strip floats its view in a window under the pointer; one dragged along the +/// strip moves its document among the others (`document.move`, #5663), a line marking where it +/// will go. pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { /// The width of the » button. const MORE: f32 = 30.0; @@ -133,6 +169,10 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { let mut close = None; let mut float = None; let mut hovering_art = false; + // The tabs shown, by document and rect, and the document whose tab is dragged (and whether + // the drag just ended), for moving it along the strip. + let mut slots: Vec<(usize, egui::Rect)> = vec![]; + let mut dragged = None; for (k, ((_, galley), w)) in tabs.iter().zip(&widths).enumerate().skip(first) { if x + w > strip.left() + room && Some(k) != active { break; @@ -142,6 +182,10 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { let is_active = Some(k) == active; let r = egui::Rect::from_min_size(egui::pos2(x, strip.top()), vec2(*w, strip.height() - 1.0)); let resp = ui.interact(r, ui.scope_id().with(("tab", i, win.1)), Sense::click_and_drag()); + slots.push((i, r)); + if resp.dragged() || resp.drag_stopped() { + dragged = Some((i, resp.drag_stopped())); + } if is_active { ui.painter().rect_filled(r, 0.0, t.panel); } else if resp.hovered() { @@ -166,6 +210,25 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { x += w; } crate::document_drag::finish_tabs(ui.ctx(), hovering_art); + // A tab dragged along the strip (not off it, which floats it) moves its document: a line marks + // the gap it goes in, and the release moves it there. Artwork dragged over the tabs never does. + let mut reorder = None; + if let Some((from, released)) = dragged + && !crate::document_drag::carrying_artwork(ui.ctx()) + && let Some(p) = ui.input(|i| i.pointer.interact_pos().or(i.pointer.latest_pos())) + && !crate::doc_windows::torn_off(strip, p) + { + let drop = tab_drop(&tab_groups(&slots), from, p.x); + if released { + reorder = drop.map(|(to, _)| (from, to)); + } else { + ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); + if let Some((_, gap)) = drop { + let gap = gap.clamp(strip.left() + 1.0, strip.right() - 1.0); + ui.painter().vline(gap, strip.y_range().shrink(4.0), Stroke::new(2.0, t.accent)); + } + } + } // The » button: every window, floating ones included, the current one checked. The list // scrolls once it reaches the bottom of the window, so every document of a large session stays // reachable (#4017). @@ -197,6 +260,10 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { if let Err(e) = app.run("window.arrange.floatInWindow", json!({"index": i, "view": n, "at": [at.x, at.y]})) { app.status(e); } + } else if let Some((from, to)) = reorder { + if let Err(e) = app.run("document.move", json!({"from": from, "to": to})) { + app.status(e); + } } else if let Some(w) = activate { crate::doc_windows::show_window(app, w); } diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index c9109a17fc..710f3ba0c0 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -7,6 +7,56 @@ fn the_active_tab_stays_in_view() { assert_eq!(super::first_tab_shown(&widths, None, 350.0), 0); assert_eq!(super::first_tab_shown(&widths, Some(4), 50.0), 4, "a tab wider than the room still shows"); } + +/// Tabs 100 wide at 0, 100, 200…, for documents `docs` (a document listed twice has two views). +fn slots(docs: &[usize]) -> Vec<(usize, egui::Rect)> { + docs.iter().enumerate().map(|(k, &d)| (d, egui::Rect::from_min_size(egui::pos2(k as f32 * 100.0, 0.0), egui::vec2(100.0, 30.0)))).collect() +} + +/// A document's view tabs make one group, which moves as one (#5663). +#[test] +fn a_documents_view_tabs_make_one_group() { + let groups = super::tab_groups(&slots(&[0, 1, 1, 2])); + let spans: Vec<(usize, f32, f32)> = groups.iter().map(|(d, s)| (*d, s.min, s.max)).collect(); + assert_eq!(spans, vec![(0, 0.0, 100.0), (1, 100.0, 300.0), (2, 300.0, 400.0)]); + assert!(super::tab_groups(&[]).is_empty()); +} + +/// A dragged tab drops past the middles of the tabs it crossed, as an index among all the open +/// documents (#5663). +#[test] +fn a_dragged_tab_drops_past_the_middles_it_crossed() { + let groups = super::tab_groups(&slots(&[0, 1, 2, 3])); + let drop = |from, x| super::tab_drop(&groups, from, x); + assert_eq!(drop(0, 40.0), None, "still over itself"); + assert_eq!(drop(0, 140.0), None, "not yet past the next tab's middle"); + assert_eq!(drop(0, 160.0), Some((1, 200.0)), "past the second tab's middle: between it and the third"); + assert_eq!(drop(0, 900.0), Some((3, 400.0)), "past the end: last"); + assert_eq!(drop(3, -50.0), Some((0, 0.0)), "before the start: first"); + assert_eq!(drop(3, 120.0), Some((1, 100.0)), "between the first two"); + assert_eq!(drop(2, 260.0), None, "between its neighbours: where it is"); + assert_eq!(super::tab_drop(&super::tab_groups(&slots(&[0])), 0, 500.0), None, "no other tab"); + assert_eq!(super::tab_drop(&[], 0, 500.0), None); +} + +/// Documents without a tab on the strip (floating, or past its end) keep their places in the +/// documents' order; the drop names an index among all of them (#5663). +#[test] +fn a_drop_counts_the_documents_the_strip_does_not_show() { + // Documents 0, 2 and 5 have tabs; 1, 3 and 4 float. + let groups = super::tab_groups(&slots(&[0, 2, 5])); + let drop = |from, x| super::tab_drop(&groups, from, x).map(|(to, _)| to); + assert_eq!(drop(0, 260.0), Some(5), "after document 5: last, as 0 leaves its place"); + assert_eq!(drop(0, 160.0), Some(4), "between 2 and 5: just before 5, which is index 4 once 0 has left its place"); + assert_eq!(drop(5, -10.0), Some(0), "before document 0"); + assert_eq!(drop(5, 60.0), Some(2), "before document 2: index 2, the floating document 1 stays before it"); + assert_eq!(drop(2, 260.0), Some(5), "after document 5"); + // With view tabs: document 1 has two, side by side; it moves as one. + let groups = super::tab_groups(&slots(&[0, 1, 1, 2])); + assert_eq!(super::tab_drop(&groups, 1, 20.0), Some((0, 0.0)), "both views' document goes first"); + assert_eq!(super::tab_drop(&groups, 0, 220.0), Some((1, 300.0)), "past document 1's middle, which both its tabs span"); + assert_eq!(super::tab_drop(&groups, 0, 190.0), None, "not yet past it"); +} use std::sync::Arc; use super::{StatusReadoutWidths, status_readouts}; diff --git a/crates/ui-egui/src/document_drag.rs b/crates/ui-egui/src/document_drag.rs index e85e95ae78..2784f29eef 100644 --- a/crates/ui-egui/src/document_drag.rs +++ b/crates/ui-egui/src/document_drag.rs @@ -44,6 +44,12 @@ fn activated_at_id() -> Id { Id::unique("document-drag-activated-at") } +/// Whether a Selection drag is carrying artwork across the document tabs, which then switch +/// documents and never move along the strip. +pub(crate) fn carrying_artwork(ctx: &Context) -> bool { + egui::DragAndDrop::payload::(ctx).is_some() +} + /// Record the Selection drag source and grab point, clearing any previous tab-hover timer. pub(crate) fn begin(app: &VectorcraftApp, ctx: &Context, grab: Point) { ctx.data_mut(|d| { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index bdfcaffffa..48b4e8dd3e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -126,6 +126,10 @@ pub struct VectorcraftApp { pub session: Session, pub ui: UiState, pub views: Vec, + /// The document ([`vectorcraft_engine::DocState::uid`]) each of `views` belonged to at the last + /// [`VectorcraftApp::sync_views`], which puts the views back with their documents after + /// `document.move` reorders them (#5663). + pub(crate) view_uids: Vec, pub services: Services, pub canvas: CanvasCache, pub perf: Perf, diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index f0c779f646..2593115f60 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -51,6 +51,7 @@ mod sysclip_emf; mod sysclip_guides; mod sysclip_probe; mod tab_overflow; +mod tab_reorder; mod taskbar; mod toolescape; mod trace_runs; diff --git a/crates/ui-egui/src/tests/tab_reorder.rs b/crates/ui-egui/src/tests/tab_reorder.rs new file mode 100644 index 0000000000..167addce0a --- /dev/null +++ b/crates/ui-egui/src/tests/tab_reorder.rs @@ -0,0 +1,173 @@ +//! Document tabs dragged along the tab strip move their documents (#5663); dragged off it, they +//! still float them. + +use egui::{Event, PointerButton, Pos2}; +use serde_json::json; +use vectorcraft_engine::Session; + +use crate::{VectorcraftApp, chrome}; + +const SIZE: egui::Vec2 = egui::vec2(1000.0, 700.0); +const NAMES: [&str; 4] = ["Alpha", "Bravo", "Charlie", "Delta"]; + +/// Run a tab-strip frame; → the tabs' titles with their rects, and the frame's output. +fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64, events: Vec) -> (Vec<(String, egui::Rect)>, egui::FullOutput) { + let mut out = ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, SIZE)), time: Some(time), events, ..Default::default() }, + |ui| { + egui::CentralPanel::default().show(ui, |ui| chrome::doc_tabs(app, ui)); + }, + ); + out.textures_delta.clear(); + fn walk(s: &egui::Shape, v: &mut Vec<(String, egui::Rect)>) { + match s { + egui::Shape::Text(t) => v.push((t.galley.text().to_owned(), egui::Rect::from_min_size(t.pos, t.galley.size()))), + egui::Shape::Vec(list) => list.iter().for_each(|s| walk(s, v)), + _ => {} + } + } + let mut texts = vec![]; + for c in &out.shapes { + walk(&c.shape, &mut texts); + } + (texts, out) +} + +fn button(at: Pos2, pressed: bool) -> Event { + Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() } +} + +/// An app with documents Alpha, Bravo, Charlie and Delta, Delta current, and a context that has +/// drawn the strip once. +fn app() -> (VectorcraftApp, egui::Context) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + for name in NAMES { + app.run("file.new", json!({"width": 100, "height": 100, "name": name})).unwrap(); + } + app.sync_views(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![]); + (app, ctx) +} + +fn order(app: &VectorcraftApp) -> Vec { + app.session.documents().iter().map(|d| d.title()).collect() +} + +fn current(app: &VectorcraftApp) -> String { + app.session.active().map(|d| d.title()).unwrap_or_default() +} + +/// The middle of the title of `name`'s tab. +fn tab(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64, name: &str) -> Pos2 { + let (texts, _) = frame(app, ctx, time, vec![]); + texts.iter().find(|(t, _)| t.starts_with(name)).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("{name}'s tab: {texts:?}")) +} + +/// Press at `from`, move to `to` in steps, and release there; → the output of the frame before +/// the release (while the tab is still dragged). +fn drag(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64, from: Pos2, to: Pos2) -> egui::FullOutput { + frame(app, ctx, time, vec![Event::PointerMoved(from)]); + frame(app, ctx, time + 0.05, vec![button(from, true)]); + let mut last = None; + for k in 1..=8 { + let p = from + (to - from) * (k as f32 / 8.0); + last = Some(frame(app, ctx, time + 0.05 + 0.02 * f64::from(k), vec![Event::PointerMoved(p)]).1); + } + frame(app, ctx, time + 0.3, vec![button(to, false)]); + frame(app, ctx, time + 0.35, vec![]); + last.unwrap() +} + +#[test] +fn a_tab_dragged_along_the_strip_moves_its_document_and_the_current_one_stays() { + let (mut app, ctx) = app(); + assert_eq!(current(&app), "Delta"); + let alpha = tab(&mut app, &ctx, 0.1, "Alpha"); + let delta = tab(&mut app, &ctx, 0.15, "Delta"); + let during = drag(&mut app, &ctx, 0.2, alpha, delta + egui::vec2(80.0, 0.0)); + assert_eq!(during.platform_output.cursor_icon, egui::CursorIcon::Grabbing, "the tab is held while it moves"); + assert_eq!(order(&app), ["Bravo", "Charlie", "Delta", "Alpha"]); + assert_eq!(current(&app), "Delta", "a move is not a switch"); + // The tabs are drawn in the new order. + let xs: Vec = NAMES.iter().map(|n| tab(&mut app, &ctx, 1.0, n).x).collect(); + assert!(xs[1] < xs[2] && xs[2] < xs[3] && xs[3] < xs[0], "Bravo, Charlie, Delta, Alpha: {xs:?}"); + + // And back to the start, before Bravo. + let alpha = tab(&mut app, &ctx, 1.1, "Alpha"); + let bravo = tab(&mut app, &ctx, 1.15, "Bravo"); + drag(&mut app, &ctx, 1.2, alpha, bravo - egui::vec2(80.0, 0.0)); + assert_eq!(order(&app), NAMES); + assert_eq!(current(&app), "Delta"); +} + +#[test] +fn a_document_keeps_its_own_zoom_after_its_tab_moves() { + let (mut app, ctx) = app(); + for (k, v) in app.views.iter_mut().enumerate() { + v.zoom = 1.0 + k as f64; + } + let bravo = tab(&mut app, &ctx, 0.1, "Bravo"); + let delta = tab(&mut app, &ctx, 0.15, "Delta"); + drag(&mut app, &ctx, 0.2, bravo, delta + egui::vec2(80.0, 0.0)); + assert_eq!(order(&app), ["Alpha", "Charlie", "Delta", "Bravo"]); + let zooms: Vec = app.views.iter().map(|v| v.zoom).collect(); + assert_eq!(zooms, [1.0, 3.0, 4.0, 2.0], "each view went with its document"); + assert_eq!(app.view().map(|v| v.zoom), Some(4.0), "the current document's view is still Delta's"); +} + +/// A move from outside the strip (MCP, the control channel, a recording) keeps the views with +/// their documents too. +#[test] +fn views_follow_a_move_made_by_the_engine_command() { + let (mut app, _ctx) = app(); + for (k, v) in app.views.iter_mut().enumerate() { + v.zoom = 1.0 + k as f64; + } + app.session.execute("document.move", &json!({"from": 3, "to": 0})).unwrap(); + app.sync_views(); + assert_eq!(order(&app), ["Delta", "Alpha", "Bravo", "Charlie"]); + assert_eq!(app.views.iter().map(|v| v.zoom).collect::>(), [4.0, 1.0, 2.0, 3.0]); + // Closing a document still leaves the others' views with them. + app.run("file.close", json!({"index": 1})).unwrap(); + app.sync_views(); + assert_eq!(order(&app), ["Delta", "Bravo", "Charlie"]); + assert_eq!(app.views.iter().map(|v| v.zoom).collect::>(), [4.0, 2.0, 3.0]); +} + +#[test] +fn a_tab_dragged_off_the_strip_still_floats_and_moves_nothing() { + let (mut app, ctx) = app(); + let alpha = tab(&mut app, &ctx, 0.1, "Alpha"); + drag(&mut app, &ctx, 0.2, alpha, alpha + egui::vec2(150.0, 300.0)); + assert_eq!(order(&app), NAMES, "the documents keep their order"); + let uid = app.session.documents()[0].uid; + assert!(app.ui.floating.iter().any(|w| w.uid == uid), "Alpha floats in a window"); +} + +#[test] +fn next_document_steps_through_the_tabs_in_their_new_order() { + let (mut app, ctx) = app(); + let delta = tab(&mut app, &ctx, 0.1, "Delta"); + let alpha = tab(&mut app, &ctx, 0.15, "Alpha"); + drag(&mut app, &ctx, 0.2, delta, alpha - egui::vec2(80.0, 0.0)); + assert_eq!(order(&app), ["Delta", "Alpha", "Bravo", "Charlie"]); + assert_eq!(current(&app), "Delta"); + app.run("window.nextDocument", json!({})).unwrap(); + assert_eq!(current(&app), "Alpha", "after Delta, now first, comes Alpha"); + app.run("window.previousDocument", json!({})).unwrap(); + app.run("window.previousDocument", json!({})).unwrap(); + assert_eq!(current(&app), "Charlie", "before the first tab comes the last"); +} + +#[test] +fn a_click_on_a_tab_still_switches_to_it() { + let (mut app, ctx) = app(); + let bravo = tab(&mut app, &ctx, 0.1, "Bravo"); + frame(&mut app, &ctx, 0.2, vec![Event::PointerMoved(bravo)]); + frame(&mut app, &ctx, 0.25, vec![button(bravo, true)]); + frame(&mut app, &ctx, 0.3, vec![button(bravo, false)]); + assert_eq!(current(&app), "Bravo"); + assert_eq!(order(&app), NAMES); +} diff --git a/docs/gaps.md b/docs/gaps.md index d754fe7740..2c730d0b8c 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (document tabs are reordered by dragging them along the tab strip; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -611,6 +611,7 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall - **Done:** Window › Arrange › Tile (`window.arrange.tile`) shows every open document in its own pane, edge to edge in the document area, and Consolidate All Windows (`window.arrange.consolidateAllWindows`) goes back to one document under its tab, on the desktop and the web. Estimate unchanged. - **Done:** Window › Arrange › Float in Window (`window.arrange.floatInWindow`), Float All in Windows (`window.arrange.floatAllInWindows`) and Cascade (`window.arrange.cascade`) move documents out of the tab strip into floating windows of their own, OS windows on the desktop and windows inside the app's window on the web and on Wayland; Cascade stacks them from the upper left to the lower right. Consolidate All Windows brings them back under the tabs. Estimate unchanged. - **Done:** a document tab dragged off the tab strip floats its document in a window under the pointer, and a document window dragged by its title bar (an OS window by the tab at its top) onto the tab strip goes back under the tabs. Estimate unchanged. +- **Done (#5663):** a document tab dragged along the tab strip moves its document among the others ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html)), a line marking where it goes; the current document stays current, each document keeps its own view, the views Window › New Window opened move with their document, and Window › Next/Previous Document follow the new order. `document.move` does the same from MCP and the control channel. Estimate unchanged. - **Done (#4116):** Window › New Window (`window.newWindow`) opens another view of the current document, with its own zoom, center, rotation, artboard and Outline or Preview, as a tab titled with the view's number ("Name:2"); Tile, Cascade, Float in Window, Float All in Windows and Consolidate All Windows arrange each view as they arrange a document. Closing a view leaves the document open until its last view closes. Estimate unchanged. - **Estimate:** 15–25 h. @@ -735,6 +736,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-05 | minor | G7: document tabs are dragged along the tab strip to reorder them (`document.move`, #5663). Estimate unchanged. | | 2026-11-02 | minor | G15: the renderer keeps a compound path's assembled path between frames and drops unused geometry entries after a few frames however few there are. Estimate unchanged. | | 2026-11-02 | minor | G15: hit testing culls paths and compound paths by their control points' box and tests a compound path's outline and fill against only its members near the click; the same objects are hit. Estimate unchanged. | | 2026-11-03 | minor | Symbol editing shows draggable 9-slice guides within the artwork (#5280). Guides outside the artwork remain unsupported. The G5 estimate remains 14–24 h. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 1deff1683d..086ad771b6 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-05 · **Change:** minor (Type Tools add-on: Release Type on a Path, a VectorCraft addition, #5532; optical kerning spaces pairs by the font's own stem spacing instead of a fixed tight gap; 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-05 · **Change:** minor (document tabs are reordered by dragging them along the tab strip; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -560,6 +560,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Window › Arrange › Tile (G7):** Tile (`window.arrange.tile`) shows every open document at once, edge to edge in the document area ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)), one pane each in a grid of as many columns as the square root of the number of documents, rounded up, each fitted to its pane. The current document's pane is the canvas; the other panes draw their documents with their artboards, guides and selected objects, and a press in one makes its document the current one. Consolidate All Windows (`window.arrange.consolidateAllWindows`) shows one document under its tab again. The grid and when the two items are enabled (Tile with two documents or more, Consolidate All Windows while they are tiled) are VectorCraft's own. Tests: `crates/ui-egui/src/canvas/panes/tests.rs`. - **Window › Arrange › Float in Window, Float All in Windows and Cascade (G7):** documents float in windows of their own, out of the tab strip ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html)). Float in Window (`window.arrange.floatInWindow`) floats the current document, Float All in Windows (`window.arrange.floatAllInWindows`) every tabbed one, and Cascade (`window.arrange.cascade`) floats every document and stacks the windows from the upper left to the lower right ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). On the desktop each window is an OS window; on the web and on Wayland it is a window inside the app's window. The window of the current document holds the canvas; the others draw their documents as Tile's panes do, and a press in one makes its document the current one. Closing a window closes its document, asking to save unsaved changes. Consolidate All Windows brings every document back under the tabs, and Tile brings them back into its grid. The cascade's 30 pt step, the windows' size and when the items are enabled (Cascade with two documents or more, Float in Window for a tabbed current document, Float All in Windows while a document is tabbed, Consolidate All Windows while documents are tiled or floating) are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Dragging a document tab out and a document window back (G7):** a document tab dragged more than 24 pt above or below the tab strip floats its document in a window under the pointer, and a document window dragged onto the tab strip goes back under the tabs ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html)). A window inside the app's window is dragged by its title bar; an OS window by the document's tab at its top, and the window follows the pointer. The 24 pt distance and the tab at the top of an OS window are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. +- **Reordering document tabs (G7, #5663):** a document tab dragged along the tab strip moves its document among the others ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html)); a line marks the gap it goes in. The current document stays current, each document keeps its own zoom, centre and artboard, the views Window › New Window opened move with their document, and Window › Next/Previous Document follow the new order. `document.move` (`{from?, to}`) does the same from MCP, the control channel and recordings. `crates/ui-egui/src/tests/tab_reorder.rs`, `crates/engine/src/tests/document_move.rs`. - **Preferences › User Interface › Open Documents As Tabs (G7, #394):** checked by default, documents open under tabs in one document window ([public source](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/workspace-overview.html)). With the box cleared, each document opened or created afterwards opens in a floating window of its own, at the next cascade place, as Float in Window floats it; documents already open stay where they are, and checking the box again leaves floating documents in their windows. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Window › New Window (G7, #4116):** New Window (`window.newWindow`) opens another view of the current document ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html) describes showing one document in several windows at once), with its own zoom, center, rotation, artboard and Outline or Preview, as a tab of its own; an edit in one view shows in every view. Tile, Cascade, Float in Window, Float All in Windows and Consolidate All Windows arrange each view as they arrange a document, and Next and Previous Document step through the views. Closing a view leaves the document open; closing its last view closes the document, asking to save it first. The view's number after the name in its tab ("Name:2", while the document has more than one view) is VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. @@ -1646,6 +1647,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-05 | minor | View & navigation: document tabs are reordered by dragging them along the tab strip (`document.move`, #5663); evidence added; scores unchanged. | | 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-11-01 | minor | Batch Trace Folder (`imageTrace.batchFolder`, #4921); evidence added; scores unchanged. | | 2026-11-01 | minor | Copy and paste ruler guides (#3226); evidence added; scores unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 3bf5440192..ef71d5ce02 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Path Precision Tools: Set Corners… rounds only the corners in an angle range; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (document tabs are reordered by dragging them along the tab strip; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) ## Feature submission evidence @@ -300,6 +300,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Interaction | Status | Evidence | |---|---|---| | Selection artwork drag hovers a visible document tab to activate it, then drops editable artwork on its canvas | done | `tests_document_drag`, `edit.dropSelection`, lossless resource and one-step Undo regressions; overflow and cross-window drag remain separate | +| A document tab dragged along the tab strip moves its document; a line marks where it goes, the current document and every document's view stay as they were, and a drag off the strip still floats it | done | #5663, [public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html); `document.move`; `tests::tab_reorder`, `chrome::tests` (drop index with floating and view tabs), `engine` `tests::document_move` | | Behaviour | Status | Notes | |---|---|---| @@ -435,6 +436,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-05 | minor | Document tabs are reordered by dragging them along the tab strip (`document.move`, #5663). | | 2026-11-04 | minor | Path Precision Tools add-on (a VectorCraft addition): Set Corners… rounds only the corners in an angle range (#5545); scores and estimates unchanged | | 2026-11-04 | minor | Path Precision Tools add-on (a VectorCraft addition): Set Corners… rounds all, the odd-numbered or the even-numbered anchors (#5546); scores and estimates unchanged | | 2026-11-04 | minor | New Document: the units chosen in Preset Details belong to the chosen document, as the pane's options are listed "for the selected preset" ([public source](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/create-and-save-custom-document-presets.html)); the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units (#2078); scores and estimates unchanged | From bddb834231ea0c6fa26e2823ae68fabb703227a8 Mon Sep 17 00:00:00 2001 From: jo-quast Date: Thu, 5 Nov 2026 12:17:33 +0700 Subject: [PATCH 037/196] Part of #394: each run hyphenates in its own language; Default Language sets new type's Squashed from #2818 onto main. --- crates/doc/src/text/char_style.rs | 7 ++- crates/engine/src/cmd/create.rs | 7 ++- crates/engine/src/cmd/prefscmds.rs | 42 ++++++++++++++---- crates/engine/src/prefs.rs | 13 +++++- crates/engine/src/tests/prefs.rs | 54 ++++++++++++++++++++++++ crates/text/src/hyphen.rs | 45 ++++++++++++++++++++ crates/text/src/layout.rs | 2 +- crates/text/src/layout/breaking.rs | 7 +-- crates/text/src/layout/wrapping_tests.rs | 1 + crates/text/src/shape.rs | 4 ++ crates/text/src/tests/typo.rs | 27 ++++++++++++ docs/gaps.md | 11 +++-- docs/target-app-parity.md | 5 ++- docs/ui-parity.md | 3 +- 14 files changed, 204 insertions(+), 24 deletions(-) diff --git a/crates/doc/src/text/char_style.rs b/crates/doc/src/text/char_style.rs index 731480fed0..67ccb60a44 100644 --- a/crates/doc/src/text/char_style.rs +++ b/crates/doc/src/text/char_style.rs @@ -143,8 +143,11 @@ pub struct CharStyle { pub no_break: bool, /// Language (Character panel): the BCP 47 tag of one of [`crate::setup::LANGUAGES`] these /// characters are shaped in, so that the font uses that language's forms (OpenType `locl`). - /// `None`: the default language, English: USA, shaped without a language. New type takes the - /// document's language (Document Setup). Saved only when set. + /// `None`: the default language, English: USA, shaped without a language, which is what text + /// saved without one reads as. A tag the list doesn't have, from a file, is kept and has no + /// hyphenation. New type takes the document's language (Document Setup), else the default + /// language of Preferences › Hyphenation. Saved only when set. Each run hyphenates in its own + /// language (`vectorcraft_text::hyphen`). #[serde(default, skip_serializing_if = "Option::is_none")] pub language: Option, /// Another glyph of the font for the run's first character (Glyphs panel › Show › Alternates diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 00ea88ea64..ab3dc966ce 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -833,7 +833,10 @@ pub(crate) fn new_type_style(s: &Session, p: &Value) -> CharStyle { None if !s.paint.fill.is_none() && s.paint.fill != vectorcraft_color::Paint::solid(vectorcraft_color::Color::WHITE) => s.paint.fill.clone(), None => vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), }; - // In the document's language (Document Setup), none for the default. - style.language = s.doc().ok().and_then(|d| vectorcraft_doc::setup::char_language(&d.doc.setup.language).ok().flatten()).map(str::to_string); + // In the language Document Setup chose, else Preferences › Hyphenation › Default Language; none + // for the default. Type already in a document keeps its own. + let chosen = |name: &str| vectorcraft_doc::setup::char_language(name).ok().flatten(); + let document = s.doc().ok().and_then(|d| chosen(&d.doc.setup.language)); + style.language = document.or_else(|| chosen(&s.prefs.hyphenation_language)).map(str::to_string); style } diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index ad24afacbc..029f3608f6 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -260,14 +260,40 @@ pub const PREF_SPECS: &[PrefSpec] = &[ "", "Default Language", choice(&[ - ("English: USA", "English: USA"), - ("English: UK", "English: UK"), - ("French", "French"), - ("German", "German"), - ("Spanish", "Spanish"), - ("Italian", "Italian"), - ("Dutch", "Dutch"), - ("Portuguese", "Portuguese") + ("en-US", "English: USA"), + ("en-GB", "English: UK"), + ("de", "German"), + ("de-CH", "German: Swiss"), + ("fr", "French"), + ("it", "Italian"), + ("es", "Spanish"), + ("ca", "Catalan"), + ("pt", "Portuguese"), + ("nl", "Dutch"), + ("da", "Danish"), + ("sv", "Swedish"), + ("fi", "Finnish"), + ("nb", "Norwegian"), + ("pl", "Polish"), + ("cs", "Czech"), + ("ru", "Russian"), + ("sr-Cyrl", "Serbian: Cyrillic"), + ("sr-Latn", "Serbian: Latin"), + ("hr", "Croatian"), + ("tr", "Turkish"), + ("ja", "Japanese"), + ("zh", "Chinese"), + ("hi", "Hindi"), + ("mr", "Marathi"), + ("gu", "Gujarati"), + ("bn", "Bengali"), + ("pa", "Punjabi"), + ("ta", "Tamil"), + ("te", "Telugu"), + ("kn", "Kannada"), + ("ml", "Malayalam"), + ("or", "Odia"), + ("ur", "Urdu") ]) ), p!("hyphenationExceptions", "Hyphenation", "", "Exceptions (comma separated)", text), diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 5deb00ddde..ce7c5e4a62 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -10,6 +10,14 @@ pub enum DrawMode { Inside, } +/// A saved Default Language as its tag: older preferences hold the language's name, and one the list +/// no longer has reads as the default. +fn language_tag<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result { + let saved = ::deserialize(d)?; + let tag = vectorcraft_doc::setup::char_language(&saved).ok().flatten(); + Ok(tag.or_else(|| vectorcraft_doc::setup::LANGUAGES.first().map(|(_, t, _)| *t)).unwrap_or_default().to_string()) +} + /// Application preferences (Edit → Preferences). Every field is reachable through `prefs.get` / /// `prefs.set {key, value}` (camelCase keys, validated against [`cmd::prefscmds::PREF_SPECS`]). #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] @@ -114,6 +122,9 @@ pub struct Prefs { pub show_slice_numbers: bool, pub slice_line_color: String, // Hyphenation + /// Default Language: the BCP 47 tag of the language new type takes when its document's language + /// is the default ([`vectorcraft_doc::setup::LANGUAGES`]). + #[serde(deserialize_with = "language_tag")] pub hyphenation_language: String, pub hyphenation_exceptions: String, /// Type › Options › Additional Fonts Folder: a folder (read with its subfolders) whose fonts @@ -404,7 +415,7 @@ impl Default for Prefs { snap_perpendicular: true, show_slice_numbers: true, slice_line_color: s("#ff3f3f"), - hyphenation_language: s("English: USA"), + hyphenation_language: s("en-US"), hyphenation_exceptions: String::new(), fonts_folder: String::new(), plugins_folder: String::new(), diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index 87b943d6c1..ae8609cd69 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -582,6 +582,60 @@ fn set_pref(s: &mut Session, key: &str, value: Value) { s.execute("prefs.set", &json!({"key": key, "value": value})).unwrap(); } +/// New type with the session's defaults: its id and language. +fn new_type(s: &mut Session) -> (NodeId, Option) { + let id = NodeId(s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Hello"})).unwrap()["id"].as_u64().unwrap()); + (id, type_language(s, id)) +} + +fn type_language(s: &Session, id: NodeId) -> Option { + let Some(NodeKind::Text(t)) = s.doc().unwrap().doc.node(id).map(|n| &n.kind) else { panic!("not text") }; + t.runs[0].style.language.clone() +} + +/// Preferences › Hyphenation › Default Language (#394) is the language of new type, stored as its +/// tag. Type already there keeps its language, and a language chosen in Document Setup comes first. +#[test] +fn default_language_is_the_language_of_new_type() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let (before, language) = new_type(&mut s); + assert_eq!(language, None, "the default language isn't stored"); + + set_pref(&mut s, "hyphenationLanguage", json!("German")); + assert_eq!(s.prefs.hyphenation_language, "de", "a name is stored as its tag"); + assert_eq!(new_type(&mut s).1.as_deref(), Some("de")); + assert_eq!(type_language(&s, before), None, "type already there stays as it is"); + + s.execute("document.setup", &json!({"language": "French"})).unwrap(); + assert_eq!(new_type(&mut s).1.as_deref(), Some("fr"), "the document's own language comes first"); + + set_pref(&mut s, "hyphenationLanguage", json!("en-US")); + s.execute("document.setup", &json!({"language": "English: USA"})).unwrap(); + assert_eq!(new_type(&mut s).1, None); +} + +/// Preferences saved before the language was a tag hold its name; a language no longer in the list +/// reads as the default. +#[test] +fn a_saved_default_language_reads_as_its_tag() { + let read = |v: &str| serde_json::from_value::(json!({"hyphenationLanguage": v})).unwrap().hyphenation_language; + assert_eq!(read("German"), "de"); + assert_eq!(read("English: USA"), "en-US"); + assert_eq!(read("de"), "de"); + assert_eq!(read("Klingon"), "en-US"); + assert_eq!(Prefs::default().hyphenation_language, "en-US"); +} + +/// The preference offers every language the Character panel and Document Setup do. +#[test] +fn default_language_offers_every_language() { + let spec = PREF_SPECS.iter().find(|p| p.key == "hyphenationLanguage").unwrap(); + let crate::cmd::prefscmds::PrefKind::Choice(options) = spec.kind else { panic!("a choice") }; + let languages: Vec<(&str, &str)> = vectorcraft_doc::setup::LANGUAGES.iter().map(|(name, tag, _)| (*tag, *name)).collect(); + assert_eq!(options, languages.as_slice()); +} + fn gesture(s: &mut Session, v: ViewInfo, events: &[(vectorcraft_tools::PointerKind, f64, f64)]) { for (k, x, y) in events { s.pointer(&vectorcraft_tools::PointerEvent::new(*k, *x, *y), v).unwrap(); diff --git a/crates/text/src/hyphen.rs b/crates/text/src/hyphen.rs index 16aa674ca6..bcf758706d 100644 --- a/crates/text/src/hyphen.rs +++ b/crates/text/src/hyphen.rs @@ -7,6 +7,11 @@ //! Preferences › Hyphenation › Exceptions (comma separated) override the points for named words: //! `typography` never breaks, `ty-pog-ra-phy` breaks only where the hyphens mark. See //! [`set_hyphenation_exceptions`]. +//! +//! Each run hyphenates in its own language ([`vectorcraft_doc::CharStyle::language`]). English is +//! the only language with break points so far: text in any other language, or in a language a +//! file names that isn't known, doesn't hyphenate, apart from the words in the Exceptions list +//! ([`language_has_patterns`]). use std::collections::HashMap; use std::sync::{Mutex, MutexGuard, OnceLock}; @@ -144,6 +149,12 @@ fn onset_pair(a: char, b: char) -> bool { ) } +/// Whether text in `language` (a [`vectorcraft_doc::CharStyle::language`]: a BCP 47 tag, `None` for +/// the default, English: USA) has break points of its own. +pub fn language_has_patterns(language: Option<&str>) -> bool { + language.is_none_or(|l| l.get(..2).is_some_and(|p| p.eq_ignore_ascii_case("en")) && matches!(l.as_bytes().get(2), None | Some(b'-'))) +} + /// Allowed hyphenation points in `word`, as char indices (a hyphen goes *before* the char), with /// the default Hyphenation options. pub fn hyphen_points(word: &str) -> Vec { @@ -157,12 +168,21 @@ pub fn hyphen_points(word: &str) -> Vec { /// (other than a trailing apostrophe) are not hyphenated. Preferences exceptions override the /// pattern and these options for a matching word. pub fn hyphen_points_with(word: &str, opts: &HyphenationOptions) -> Vec { + hyphen_points_in(word, opts, true) +} + +/// [`hyphen_points_with`] for a word in a language with or without break points of its own +/// ([`language_has_patterns`]): without them, only a word in the Exceptions list breaks. +pub fn hyphen_points_in(word: &str, opts: &HyphenationOptions, patterns: bool) -> Vec { if let Some(ex) = exception_for(word) { return match ex { Exception::Never => vec![], Exception::Only(pts) => lowercase_points_to_word(word, &pts), }; } + if !patterns { + return vec![]; + } let c: Vec = word.chars().collect(); let n = c.len(); let longer_than = usize::try_from(opts.words_longer_than).unwrap_or(usize::MAX); @@ -235,6 +255,31 @@ mod tests { with_hyphenation_exceptions_for_test(source, f); } + /// #394: English in any region has break points; other languages, and a tag from a file that + /// isn't a known language, have none. + #[test] + fn only_english_has_break_points() { + for l in [None, Some("en-US"), Some("en-GB"), Some("EN-gb"), Some("en")] { + assert!(language_has_patterns(l), "{l:?}"); + } + for l in [Some("de"), Some("fr"), Some("pt"), Some("eng"), Some("x-unknown"), Some(""), Some("é")] { + assert!(!language_has_patterns(l), "{l:?}"); + } + } + + /// #394: a language without break points leaves words whole, but the Exceptions list is the + /// user's own and applies in every language. + #[test] + fn a_language_without_break_points_keeps_only_the_exceptions() { + let opts = HyphenationOptions::default(); + assert_eq!(hyphen_points_in("typography", &opts, true), vec![4, 7]); + assert!(hyphen_points_in("typography", &opts, false).is_empty()); + with_exceptions("ty-pog-ra-phy, happen", || { + assert_eq!(hyphen_points_in("typography", &opts, false), vec![2, 5, 7]); + assert!(hyphen_points_in("happen", &opts, false).is_empty()); + }); + } + /// #394 Preferences › Hyphenation › Exceptions contract (parse + override). #[test] fn hyphenation_exceptions_override_the_pattern() { diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index b814506e6d..50e1ce0b27 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -14,7 +14,7 @@ use vectorcraft_geom::{ArcPath, PathData}; use crate::GlyphBend; use crate::composer::{Breakpoint, Params, compose}; use crate::fontdb::FontDb; -use crate::hyphen::hyphen_points_with; +use crate::hyphen::hyphen_points_in; use crate::justify::{Flex, LineFit, apply_desired, fit_line, is_word_space}; use crate::kashida; use crate::shape::{ diff --git a/crates/text/src/layout/breaking.rs b/crates/text/src/layout/breaking.rs index 54d8941e83..90d6555a00 100644 --- a/crates/text/src/layout/breaking.rs +++ b/crates/text/src/layout/breaking.rs @@ -1,7 +1,7 @@ use super::region::Region; use super::{ Affine, BezPath, Breakpoint, Burasagari, EPS, FirstBaseline, FontDb, HyphenationOptions, Kinsoku, LeadingModel, SGlyph, hyphen_glyph, - hyphen_points_with, no_line_end, no_line_start, soft_line_start, + hyphen_points_in, no_line_end, no_line_start, soft_line_start, }; /// Vertical metrics of a line: (ascent, descent, leading, cap height, x height). @@ -518,7 +518,8 @@ fn soft_kinsoku_lets_small_kana_and_the_prolonged_sound_mark_start_a_line() { } } -/// Glyph indices inside `g[ws..we]` (a word) where a hyphenated break may go under `opts`. +/// Glyph indices inside `g[ws..we]` (a word) where a hyphenated break may go under `opts`, in the +/// language of the word's first letter. fn hyphen_breaks(text: &str, g: &[SGlyph], ws: usize, we: usize, opts: &HyphenationOptions) -> Vec { // Strip leading/trailing punctuation (quotes, commas). let (mut a, mut b) = (ws, we); @@ -542,7 +543,7 @@ fn hyphen_breaks(text: &str, g: &[SGlyph], ws: usize, we: usize, opts: &Hyphenat starts.entry(g[k].byte).or_insert(k); } } - hyphen_points_with(word, opts).into_iter().filter_map(|ci| starts.get(offs.get(ci)?).copied()).collect() + hyphen_points_in(word, opts, g[a].hyphenates).into_iter().filter_map(|ci| starts.get(offs.get(ci)?).copied()).collect() } /// Break candidates for the every-line composer: hyphenation points under `hyphenate` (the diff --git a/crates/text/src/layout/wrapping_tests.rs b/crates/text/src/layout/wrapping_tests.rs index 9f1a048b38..cdf5855390 100644 --- a/crates/text/src/layout/wrapping_tests.rs +++ b/crates/text/src/layout/wrapping_tests.rs @@ -39,6 +39,7 @@ fn synthetic_glyphs(specs: &[(usize, usize, f64, char)]) -> Vec { no_break: false, vertical_roman: false, cursive: false, + hyphenates: true, }) .collect() } diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index 6ecd515db3..f37c7443ec 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -80,6 +80,8 @@ pub(crate) struct SGlyph { /// decided for the whole segment it was shaped in ([`joins`]): on a curved path it is bent /// along the path so its joins meet. pub cursive: bool, + /// The glyph's language has hyphenation break points ([`crate::hyphen::language_has_patterns`]). + pub hyphenates: bool, } /// Does `script` join its letters (a cursive script, whose neighbouring glyphs touch)? @@ -947,6 +949,7 @@ fn inline_glyph( no_break: st.no_break, vertical_roman: false, cursive: false, + hyphenates: false, } } @@ -1327,6 +1330,7 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe no_break: gst.no_break, vertical_roman: gst.standard_vertical_roman, cursive, + hyphenates: crate::hyphen::language_has_patterns(gst.language.as_deref()), }); } } diff --git a/crates/text/src/tests/typo.rs b/crates/text/src/tests/typo.rs index f92ce67a6a..478bc9c97b 100644 --- a/crates/text/src/tests/typo.rs +++ b/crates/text/src/tests/typo.rs @@ -1013,6 +1013,33 @@ fn hyphenation_rules() { } } +/// #394: each run hyphenates in its own language. English breaks words, a language without break +/// points doesn't, and text saved without a language breaks as it always did. +#[test] +fn each_run_hyphenates_in_its_own_language() { + let text = "Extraordinarily comprehensive typographical considerations notwithstanding everything."; + let frame = Rect::new(0.0, 0.0, 120.0, 600.0); + let hyphens = |language: Option<&str>| { + let st = CharStyle { language: language.map(str::to_string), ..style(14.0) }; + let mut t = area(text, st, frame, Justify::Left); + t.para.hyphenate = true; + layout(db(), &t).glyphs.iter().filter(|g| g.len == 0).count() + }; + let saved_without_one = hyphens(None); + assert!(saved_without_one > 0, "some words hyphenated"); + assert_eq!(hyphens(Some("en-GB")), saved_without_one); + assert_eq!(hyphens(Some("de")), 0, "German has no break points yet"); + assert_eq!(hyphens(Some("x-from-a-file")), 0, "a tag that isn't known has no hyphenation"); + + // both in one paragraph: the English run breaks and the German one doesn't + let mut t = area(&format!("{text} {text}"), style(14.0), frame, Justify::Left); + t.para.hyphenate = true; + edit::style_range(&mut t.runs, text.len(), 2 * text.len() + 1, |s| s.language = Some("de".into())); + let l = layout(db(), &t); + let at: Vec = l.glyphs.iter().filter(|g| g.len == 0).map(|g| g.byte).collect(); + assert!(!at.is_empty() && at.iter().all(|b| *b < text.len()), "hyphens only in the English run: {at:?}"); +} + #[test] fn hyphenated_layout_adds_hyphens() { let text = "Extraordinarily comprehensive typographical considerations notwithstanding everything."; diff --git a/docs/gaps.md b/docs/gaps.md index 2c730d0b8c..7dc084a0a0 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (document tabs are reordered by dragging them along the tab strip; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -28,6 +28,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-05 | minor | G12: Hyphenation › Default Language sets the language of new type unless Document Setup chose one, stored as a tag; each run hyphenates in its own language, English only so far, so 2 Preferences options stay unused (#394) | | 2026-11-03 | minor | New gradients use CMYK default stops in CMYK documents, including Gradient tool creation. Scores and estimates unchanged. | | 2026-11-02 | minor | Font-family fields step selected text with the mouse wheel (#5253); no scored gap or estimate reassessed. | | 2026-10-24 | minor | G12: General › Corner Radius is the Rounded Rectangle tool's radius, a change while the tool is active reaches it, and the radius ↑/↓ set while drawing (or a Tool Options value) becomes the preference, within 0–1296 pt (#394, `crates/engine/src/tests/constrain_tools.rs`); no entry closed, estimate unchanged. | @@ -437,9 +438,11 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall - **Done:** User Interface › Open Documents As Tabs: with the box cleared, each document opened or created afterwards opens in a floating window of its own (G7's Float in Window); documents already open stay where they are. Estimate unchanged. -- **Missing:** 3 Preferences options stored but not acted on (#394), each waiting on a subsystem of its own: - Hyphenation › Default Language (hyphenation is English-only, with no per-language - dictionaries), Plug-ins & Scratch Disks › Primary and Secondary (documents are kept in memory; nothing pages to +- **Done:** Hyphenation › Default Language is the language of new type, unless Document Setup chose one, and each + run hyphenates in its own language (Character panel). Only English has break points so far: text in another + language stays whole, apart from the Exceptions list (#394). +- **Missing:** 2 Preferences options stored but not acted on (#394), each waiting on a subsystem of its own: + Plug-ins & Scratch Disks › Primary and Secondary (documents are kept in memory; nothing pages to disk), and Clipboard Handling › Legacy vector clipboard with its Preserve Paths / Preserve Appearance and Overprints choice (Illustrator's own clipboard flavour, which has no public specification). Also Properties panel per context, context menus beyond the canvas, Layers panel row menus and Collect for Export, SVG diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 086ad771b6..343b650e47 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -23,6 +23,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-05 | minor | G12: Hyphenation › Default Language sets the language of new type unless Document Setup chose one, stored as a tag; each run hyphenates in its own language, English only so far, so 2 Preferences options stay unused (#394) | | 2026-11-05 | minor | Type Tools add-on: Release Type on a Path (a VectorCraft addition, #5532): evidence added; scores unchanged. | | 2026-11-04 | minor | Path Precision Tools add-on (a VectorCraft addition): Set Corners… and `addon.pathtools.cornerSet` `minAngle`/`maxAngle` round only the corners whose angle is in a range (#5545); evidence added; scores unchanged. | | 2026-11-04 | minor | Path Precision Tools add-on (a VectorCraft addition): Set Corners… and `addon.pathtools.cornerSet` `every` round all, the odd-numbered or the even-numbered anchors of each path (#5546); evidence added; scores unchanged. | @@ -182,7 +183,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | anti-aliasing ghost borders (#983); TIFF choices and settings are implemented | 2–4 | estimated | | Print, colour management, separations, flattener | 3 | 80% | print preview fidelity | 2–4 | estimated | | Automation (Actions, Variables, scripting, batch) | 3 | 60% | a scripting surface (Illustrator: JavaScript/ExtendScript), Batch, image and graph variables, dataset import/export | 8–14 | estimated; MCP `add_text` exposes existing vertical type; score and hours unchanged | -| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, 4 Preferences options stored but unused (#394, audited 2026-10-30: Open Documents As Tabs, hyphenation Default Language, Scratch Disks, legacy vector clipboard), SVG Interactivity, context menus beyond the canvas, accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; numeric-field focus and normal text drags regression-tested (#1326, in part); movements below the click threshold still select all; artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged) | +| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, 3 Preferences options stored but unused (#394, audited 2026-10-30: Open Documents As Tabs, Scratch Disks, legacy vector clipboard), SVG Interactivity, context menus beyond the canvas, accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; numeric-field focus and normal text drags regression-tested (#1326, in part); movements below the click threshold still select all; artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged) | | Libraries, Links, Package | 2 | 82% | shared libraries, linked graphics, gradients and patterns as library items (no cloud by design) | 2–3 | estimated | | Generative AI (Text to Vector, Generative Recolor, Shape Fill, Concept to Vector, Prompt to Edit, Rewrite Text) | 2 | 0% | a pluggable provider and the panels; needs an owner decision on models | 30–60 | measured (absent) | | **Feature depth** | **105** | **~75%** | | **~250–420** | | @@ -679,7 +680,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The desktop app keeps the Color panel's Show Options or Hide Options between sessions, and `ui.colorPanel` sets its mode and options as its panel menu does. - Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns, Align and Distribute, art moved or duplicated with an artboard, and objects moved whole with direct-selected anchors) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: Pixel Preview draws images with each pixel taking its nearest image pixel). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). Then Smart Guides › Spacing Guides (moves space the selection evenly with its row or column, see Drawing aids). Then Hyphenation › Exceptions (comma-separated words that never break, or break only at their hyphens; `prefs.set` and restore push them into the hyphenator, #394). Then Type › Show Font Names in English (off, font menus label a family by its native-language name when the font has one; documents still use the English family, #394). Then General › Display Print Size at 100% Zoom (off by default: View › Actual Size is one document point per screen point; on, one document inch fills 96 screen points, an inch at the reference density display scaling is set against; `view.actualSize` / `prefs.set`, #394). Then Guides & Grid › Gridline every and Subdivisions (changing either sets the grid of every open document; new and opened documents take that grid too, except a native file and the native document an SVG, PDF, `.ai` or EPS file carries, which open with the grid they were saved with; `file.new`, `document.open`, `file.newFromTemplate`, `file.revert`, #394). Then Appearance of Black › On Screen (Display All Blacks Accurately by default: pure CMYK black shows through the CMYK profile, a dark grey; Display All Blacks as Rich Black shows it on the canvas as RGB black, also in CMYK documents drawn by ink planes, while rich blacks, black tints and images show as before; `RenderOptions::rich_black`, #394). Then Appearance of Black › Printing / Exporting (Output All Blacks Accurately by default; Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB raster exports and Print as Bitmap; CMYK ink exports and the document stay unchanged; `prefs.blackOutput` / `richBlack`, #394). Then Units › Identify Objects By (Object Name by default: Layers, Variables and Layer Options show and edit free names; XML ID shows and edits AI-style XML ids, `_` for a space and `_xHH_` escapes, and `layer.setProps` / rename refuse invalid ids; the document still stores the object name, #394). Then Units › East Asian Type (the bullet below). Then User Interface › Open Documents As Tabs (see Window › Arrange). Three stored options still do nothing yet (the audit below). - Preferences › Type › Highlight Substituted Fonts (on by default) paints pink behind text drawn in a substitute for a missing font in every document, and turning it off removes that highlight everywhere (`prefs.set highlightSubstitutedFonts`); Document Setup keeps Highlight Substituted Glyphs ([help](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/edit-text-without-replacing-missing-fonts.html)). - - Preferences audit (2026-10-30, #394): every Preferences dialog option is read by shipped code, by its field or its key, except Hyphenation › Default Language, Plug-ins & Scratch Disks › Primary and Secondary, and Clipboard Handling › Legacy vector clipboard and its mode, which are stored only (Units › East Asian Type and User Interface › Open Documents As Tabs, stored only on the day of the audit, act now: East Asian Type since 2026-10-31, Open Documents As Tabs as the Window › Arrange bullet says); [gaps.md G12](gaps.md#g12-preferences-and-panels-that-dont-act-yet) says what each waits on. + - Preferences audit (2026-10-30, #394): every Preferences dialog option is read by shipped code, by its field or its key, except Plug-ins & Scratch Disks › Primary and Secondary, and Clipboard Handling › Legacy vector clipboard and its mode, which are stored only (Units › East Asian Type and User Interface › Open Documents As Tabs, stored only on the day of the audit, act now: East Asian Type since 2026-10-31, Open Documents As Tabs as the Window › Arrange bullet says); [gaps.md G12](gaps.md#g12-preferences-and-panels-that-dont-act-yet) says what each waits on. - Units › East Asian Type (#394, `unitsAsianType`): Points by default; it offers every unit and Q and Ha, a quarter of a millimetre each (0.709 pt: the [Illustrator Scripting Guide](https://ai-scripting.docsforadobe.dev/scripting/measurementUnits/); `q` and `h` are the field suffixes [InDesign's notation table](https://helpx.adobe.com/in/indesign/desktop/layout-and-grid-tools/rulers-and-measure-tools/change-ruler-measurement-units.html) lists), and only it lists them: rulers, Document Setup and the other Units preferences keep their ten. The public pages do not say which fields follow it, so no field uses it yet and that waits for a source. The model stays in points; any length field reads `13q`/`13h`. Evidence: `q_and_ha_are_a_quarter_millimetre`, `east_asian_type_unit_*` (`crates/engine/src/tests/units.rs`). - Preferences audit (2026-10-30, #394): every Preferences dialog option is read by shipped code, by its field or its key, except User Interface › Open Documents As Tabs, Units › East Asian Type, Hyphenation › Default Language, Plug-ins & Scratch Disks › Primary and Secondary, and Clipboard Handling › Legacy vector clipboard and its mode, which are stored only; [gaps.md G12](gaps.md#g12-preferences-and-panels-that-dont-act-yet) says what each waits on. - With Performance › Real-time Drawing and Editing off, the bounding box moves with a Selection-tool move drag and the object moves when the button is released ([help](https://web.archive.org/web/20220324053041id_/https://helpx.adobe.com/illustrator/using/real-time-editing.html); `real_time_drawing_off_moves_the_bounding_box_with_a_move_drag`). diff --git a/docs/ui-parity.md b/docs/ui-parity.md index ef71d5ce02..7b50110245 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -30,6 +30,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-05 | minor | G12: Hyphenation › Default Language sets the language of new type unless Document Setup chose one, stored as a tag; each run hyphenates in its own language, English only so far, so 2 Preferences options stay unused (#394) | | 2026-11-05 | minor | Gradient panel: Delete Stop sits at the right end of the ramp, so it shows whenever the ramp does instead of under the stop fields, where a short panel hid it (#5403); scores and estimates unchanged | | 2026-11-04 | minor | Artboards panel: a Shift- or Ctrl/Cmd-click on a row selects several artboards with any tool, switching to the Artboard tool first, so a preset, orientation, size or Fill set in Properties or the Control bar goes to every selected artboard; Fill used to set the active artboard only (#5698); scores and estimates unchanged | | 2026-11-04 | minor | Isolation mode: once the layer, or a group, around the isolated object is locked or hidden, a click or a marquee with the Selection tool no longer selects the isolated art (part of #5309); scores and estimates unchanged | @@ -367,7 +368,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Swatch, graphic style and symbol library panels: each library opens in a panel of its own, several at once, that floats, groups, docks and closes like any panel; opening an open library brings its panel forward; Previous / Next Library change the library in place; the panel menu's Persistent reopens the panel at startup with its view and find field (a library loaded from a file is read again; when its file is missing the panel reopens showing the file's path with Locate Library…, and the status bar names the file) | done | #2603; panel ids `library::`, `ui.libraryPanel {panel, library?, view?, showFind?, persistent?}`, `ui.libraryPanel.locate {panel, path?}`; the library panels have no sort option, as before | | DXF export/import preserves intended curve closure | done | #1299; R13–2018 closed SPLINE bit set/read; an open curve ending at its start stays open; knots and control points unchanged; native CIRCLE/ARC export and CNC preset remain pending | | macOS save sheet: choose the format from a menu | done | #866; the save panel is VectorCraft's own `NSSavePanel` with its Format menu set before the sheet opens (`apps/vectorcraft/src/mac_save_format.rs`); #1855 had withdrawn the menu that was added after the sheet began, which made Save As, Save a Copy and the first Save show no sheet | -| Preferences: every option acts | partial | 3 stored but unused (#394, audited 2026-10-30): Hyphenation › Default Language, Scratch Disks, Legacy vector clipboard; the rest act (Units › East Asian Type since 2026-10-31; Open Documents As Tabs: cleared, new documents open in floating windows). General › Corner Radius drives the Rounded Rectangle tool and follows its ↑/↓ (2026-10-24) | +| Preferences: every option acts | partial | 2 stored but unused (#394, audited 2026-10-30): Scratch Disks, Legacy vector clipboard; the rest act (Units › East Asian Type since 2026-10-31; Open Documents As Tabs: cleared, new documents open in floating windows). General › Corner Radius drives the Rounded Rectangle tool and follows its ↑/↓ (2026-10-24) | | Preferences › General › Constrain Angle | done | arrow keys and Shift drags along the turned axes; the Rectangle, Rounded Rectangle, Ellipse and grid tools, point and area type and the shape size dialogs draw along them with the bounding box turned; Shift-drawn polygons and stars keep the turned base orientation; the Line Segment tool's Shift steps count from it (#394, ); arcs, spirals, flares and Pen paths are not turned | | Tabs panel: a stop drags from where the press landed, a stop just added included | done | #1458 | | Outline view keeps template layers in Preview, dimmed | done | #1486; a picture placed to be traced stays visible under the outlines | From 30a2d85658ce9d56c7fb45ccd556b9d864934855 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 21:03:08 -0800 Subject: [PATCH 038/196] Global Edit: the enabled check decides without normalizing every anchor The Control bar asks whether Select > Start Global Edit can run every frame it shows a one-object selection. For a path, compound path or symbol instance that check built the object's form: a copy of every anchor and handle, normalized into a unit box. On a 200,000-anchor path it took about 2.2 to 3.0 ms a frame. The check now walks the object the same way and measures only the box of those points, then applies the same size test, so it gives the same answer for every object without allocating. Starting Global Edit still builds the forms it compares. --- crates/engine/src/cmd/globaledit.rs | 251 +++++++++++++++++++++++++++- docs/target-app-parity.md | 1 + 2 files changed, 249 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/globaledit.rs b/crates/engine/src/cmd/globaledit.rs index b958f51c16..2b0e214cc0 100644 --- a/crates/engine/src/cmd/globaledit.rs +++ b/crates/engine/src/cmd/globaledit.rs @@ -262,7 +262,59 @@ impl Form { /// type, linked files, objects with an opacity mask, clipping paths or guides (the help page lists /// images, text, masks and links as unsupported). fn supported(n: &Node) -> bool { - n.extras().mask.is_none() && Form::of(n).is_some() + n.extras().mask.is_none() && has_form(n) +} + +/// Does [`Form::of`] give `n` a form? The same walk and the same box, without collecting the +/// points or placing them in a unit box. +fn has_form(n: &Node) -> bool { + let mut b = None; + form_box(n, 0, &mut b).is_some() + && b.is_some_and(|b: Rect| { + let side = b.width().max(b.height()); + side.is_finite() && side > 1e-9 + }) +} + +/// [`Form::add`] without the form: `b` grows by each point it would add; `None` when `n` isn't +/// supported. +fn form_box(n: &Node, depth: usize, b: &mut Option) -> Option<()> { + match &n.kind { + NodeKind::Path { path, clipping, guide: false, .. } if !*clipping || depth > 0 => grow_by_path(b, path), + NodeKind::Compound { children, .. } => { + for c in children { + grow_by_path(b, c.path_data()?); + } + } + NodeKind::SymbolInstance { xf, .. } => { + for p in [*xf * Point::ZERO, *xf * Point::new(1.0, 0.0), *xf * Point::new(0.0, 1.0)] { + grow(b, p); + } + } + NodeKind::Group { children, .. } if plain_group(n) && depth < vectorcraft_doc::MAX_DEPTH => { + for c in children { + if c.extras().mask.is_some() { + return None; + } + form_box(c, depth + 1, b)?; + } + } + _ => return None, + } + Some(()) +} + +fn grow_by_path(b: &mut Option, path: &PathData) { + for a in path.subpaths.iter().flat_map(|sp| &sp.anchors) { + for p in [a.p, a.h_in, a.h_out] { + grow(b, p); + } + } +} + +/// `b` grown to take in `p`, as [`Form::of`] measures its points. +fn grow(b: &mut Option, p: Point) { + *b = Some(b.unwrap_or(Rect::from_points(p, p)).union_pt(p)); } /// A plain group (a clip group too), not one that is live art (a graph, Shaper group, dimension, @@ -374,8 +426,9 @@ fn can_toggle(s: &Session) -> std::result::Result<(), String> { let [id] = st.selection.objects.as_slice() else { return Err(if st.selection.is_empty() { "nothing selected" } else { "select one object" }.into()); }; - // A group's contents are checked when Global Edit starts: building its shape here would walk - // every object in it each time the menu or the Properties panel asks. + // A group's contents are checked when Global Edit starts: measuring them here would walk + // every object in it each time the menu or the Properties panel asks. Other objects are + // measured ([`supported`]), not reduced to their form: the Control bar asks every frame. match st.doc.node(*id) { Some(n) if n.extras().mask.is_none() && plain_group(n) => Ok(()), Some(n) if supported(n) => Ok(()), @@ -750,3 +803,195 @@ pub fn highlights(s: &Session) -> Outlines { *ge.outlines.borrow_mut() = Some((st.revision, out.clone())); out } + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + use vectorcraft_doc::OpacityMask; + use vectorcraft_geom::{Anchor, SubPath}; + + /// Global Edit's support as it was decided by building the form. + fn by_form(n: &Node) -> bool { + n.extras().mask.is_none() && Form::of(n).is_some() + } + + /// A small seeded generator (xorshift64*), so that a failure repeats. + struct Rng(u64); + + impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_f491_4f6c_dd1d) + } + fn below(&mut self, n: u64) -> u64 { + self.next() % n + } + fn unit(&mut self) -> f64 { + (self.next() >> 11) as f64 / (1u64 << 53) as f64 + } + /// A spread for the points of one object: none, below and around the smallest size a form + /// takes, ordinary, or past every bound. + fn spread(&mut self) -> f64 { + [0.0, 1e-10, 5e-10, 1e-9, 2e-9, 1.0, 1.0, 100.0, 100.0, 100.0, f64::INFINITY, f64::NAN][self.below(12) as usize] + } + fn point(&mut self, base: Point, spread: f64) -> Point { + let mut c = |b: f64| match self.below(400) { + 0 => f64::NAN, + 1 => f64::INFINITY, + 2 => f64::NEG_INFINITY, + _ => b + (self.unit() - 0.5) * spread, + }; + Point::new(c(base.x), c(base.y)) + } + } + + fn path_data(r: &mut Rng) -> PathData { + let (base, spread) = (Point::new(r.unit() * 200.0, r.unit() * 200.0), r.spread()); + let subpaths = (0..r.below(3)) + .map(|_| { + let anchors = (0..r.below(4)) + .map(|_| Anchor { p: r.point(base, spread), h_in: r.point(base, spread), h_out: r.point(base, spread), ..Anchor::corner(base) }) + .collect(); + SubPath::new(anchors, r.below(2) == 0) + }) + .collect(); + PathData::new(subpaths) + } + + /// A random object: paths (clipping paths and guides too), compound paths, symbol instances, + /// groups (clip groups, live art, members with an opacity mask), type, blends and intertwined + /// objects, any of them with an opacity mask. + fn object(r: &mut Rng, d: &mut Document, text: &Node, depth: usize) -> Node { + let leaf = depth >= 3; + let mut n = match r.below(if leaf { 4 } else { 8 }) { + 0 | 1 => { + let mut n = Node::path(d.alloc_id(), path_data(r), Appearance::default()); + if let NodeKind::Path { clipping, guide, .. } = &mut n.kind { + *clipping = r.below(6) == 0; + *guide = r.below(8) == 0; + } + n + } + 2 => { + let xf = match r.below(4) { + 0 => Affine::scale(0.0), + 1 => Affine::scale(1e-10), + _ => Affine::translate((r.unit() * 100.0, r.unit() * 100.0)) * Affine::scale(r.spread()), + }; + Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "s".into(), xf }) + } + 3 => { + let mut t = text.clone(); + t.id = d.alloc_id(); + t + } + 4 => { + let children = (0..r.below(4)) + .map(|_| match r.below(5) { + 0 => Arc::new(object(r, d, text, depth + 1)), + _ => Arc::new(Node::path(d.alloc_id(), path_data(r), Appearance::default())), + }) + .collect(); + Node::new(d.alloc_id(), NodeKind::Compound { children, rule: vectorcraft_geom::FillRule::NonZero }) + } + 5 => { + let children = (0..r.below(3)).map(|_| Arc::new(object(r, d, text, depth + 1))).collect(); + Node::new(d.alloc_id(), NodeKind::Blend { children, spec: Box::default() }) + } + _ => { + let children = (0..r.below(4)).map(|_| Arc::new(object(r, d, text, depth + 1))).collect(); + let mut g = Node::new(d.alloc_id(), NodeKind::Group { children, clip: r.below(3) == 0 }); + if r.below(8) == 0 { + g.extras_mut().trace = Some(Box::new(Value::Null)); + } + g + } + }; + if r.below(10) == 0 { + n.extras_mut().mask = Some(Box::new(OpacityMask::new(Node::path(d.alloc_id(), path_data(r), Appearance::default()), true))); + } + n + } + + /// `n` and every object in it. + fn every(n: &Node) -> Vec { + let mut out = vec![]; + n.walk(&mut |c| out.push(c.clone())); + out + } + + #[test] + fn support_is_decided_as_building_the_form_decides() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + let t = NodeId(s.execute("text.create", &json!({"x": 50, "y": 50, "text": "Hi"})).unwrap()["id"].as_u64().unwrap()); + let text = s.doc().unwrap().doc.node(t).unwrap().clone(); + let layer = s.doc().unwrap().doc.layers[0].id; + let (mut checked, mut taken, mut asked) = (0, 0, 0); + for seed in 1..=400u64 { + let mut r = Rng(seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1); + let n = object(&mut r, Arc::make_mut(&mut s.doc_mut().unwrap().doc), &text, 0); + for c in every(&n) { + assert_eq!(supported(&c), by_form(&c), "seed {seed}: {c:?}"); + checked += 1; + taken += usize::from(by_form(&c)); + } + // The enabled check of Start Global Edit on it, and Start Global Edit itself. + let id = Arc::make_mut(&mut s.doc_mut().unwrap().doc).insert(Some(layer), usize::MAX, n.clone()).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + if s.doc().unwrap().selection.objects != [id] { + continue; + } + asked += 1; + let today = n.extras().mask.is_none() && plain_group(&n) || by_form(&n); + assert_eq!(can_toggle(&s).is_ok(), today, "seed {seed}"); + match s.execute(C, &json!({})) { + Ok(_) => { + assert!(by_form(&n), "seed {seed}"); + s.execute(C, &json!({})).unwrap(); + } + Err(e) => assert_eq!(e.to_string().contains(UNSUPPORTED), !by_form(&n), "seed {seed}: {e}"), + } + } + // Both answers came up often, and most objects could be selected alone. + assert!(taken > 100 && checked - taken > 100 && asked > 200, "{taken} of {checked}, {asked} selected"); + } + + #[test] + fn support_of_empty_degenerate_and_deep_objects_is_decided_as_building_the_form_decides() { + let mut d = Document::new(800.0, 600.0); + let corner = |x: f64, y: f64| Anchor::corner(Point::new(x, y)); + let path = |d: &mut Document, subpaths: Vec| Node::path(d.alloc_id(), PathData::new(subpaths), Appearance::default()); + let mut cases = vec![ + path(&mut d, vec![]), + path(&mut d, vec![SubPath::new(vec![], true)]), + path(&mut d, vec![SubPath::new(vec![corner(5.0, 5.0)], false)]), + path(&mut d, vec![SubPath::new(vec![corner(0.0, 0.0), corner(0.0, 1e-9)], false)]), + path(&mut d, vec![SubPath::new(vec![corner(0.0, 0.0), corner(0.0, 2e-9)], false)]), + path(&mut d, vec![SubPath::new(vec![corner(0.0, 0.0), corner(f64::INFINITY, 0.0)], false)]), + path(&mut d, vec![SubPath::new(vec![corner(f64::NAN, 0.0), corner(10.0, 0.0), corner(0.0, 0.0)], false)]), + path(&mut d, vec![SubPath::new(vec![corner(f64::NAN, f64::NAN)], false)]), + Node::new(d.alloc_id(), NodeKind::Compound { children: vec![], rule: Default::default() }), + Node::group(d.alloc_id(), vec![]), + Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "s".into(), xf: Affine::scale(0.0) }), + Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "s".into(), xf: Affine::IDENTITY }), + ]; + // A group as deep as the walk goes, and one level deeper. + let mut deep = path(&mut d, vec![SubPath::new(vec![corner(0.0, 0.0), corner(10.0, 10.0)], false)]); + for _ in 0..=vectorcraft_doc::MAX_DEPTH { + deep = Node::group(d.alloc_id(), vec![Arc::new(deep)]); + cases.push(deep.clone()); + } + let expected = [false, false, false, false, true, false, true, false, false, false, false, true]; + for (i, n) in cases.iter().enumerate() { + assert_eq!(supported(n), by_form(n), "case {i}: {n:?}"); + if let Some(e) = expected.get(i) { + assert_eq!(supported(n), *e, "case {i}"); + } + } + assert!(supported(&cases[cases.len() - 2]) && !supported(&cases[cases.len() - 1])); + } +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 343b650e47..17db9d3f2e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -512,6 +512,7 @@ since 2026-10-01. - **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`. - **Global Edit Options in the Control bar:** while Select › Start Global Edit can run, the Control bar shows a Global Edit Options dropdown that opens the same options as the Properties panel's (Match: Appearance, Size; On Artboards; Include Objects On Canvas; Result(s)); both set the same options. The dropdown is off while Global Edit is on; it sits after Recolor Artwork, ahead of the X/Y/W/H fields ([Edit similar objects globally](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-similar-objects.html)). Regression test: `the_control_bar_shows_the_global_edit_options` in `crates/ui-egui/src/chrome/tests.rs`. +- **Global Edit's enabled check on large paths:** the check that decides whether Select › Start Global Edit can run on the selected path, compound path or symbol instance (which the Control bar makes every frame) measures the box of its anchors and handles instead of building and normalizing a copy of every anchor, with the same answer. On a 200,000-anchor path the check takes 0.7 ms instead of 2.2 to 3.0 ms. Regression tests: `support_*` in `crates/engine/src/cmd/globaledit.rs`. - **Control bar's inline X, Y, W and H fields fit the bar:** the Control bar shows the inline X, Y, W and H fields only when all four, their labels as drawn in the current language and the W/H link fit inside the bar's margin; otherwise it shows the Transform link alone. This is VectorCraft's own layout rule. Regression test: `the_control_bar_shows_the_inline_transform_fields_only_when_they_fit` in `crates/ui-egui/src/chrome/tests.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. From 8584bf1ab667c2134242f69b2eda1d98f42a2aef Mon Sep 17 00:00:00 2001 From: Kindmark <39938776+Kindmark@users.noreply.github.com> Date: Wed, 4 Nov 2026 14:52:14 -0600 Subject: [PATCH 039/196] Contour: live offset tool with a floating bar and its own icon Add a Contour tool (Modify group). Dragging away from a selected path or shape's edge makes a copy of it that carries a live Offset Path effect, grown by the drag; dragging toward the inside shrinks it. The result is one undo step and stays editable until baked with Expand Appearance. A second drag on a selected Contour changes its distance instead of nesting another effect. - object.contour: the command behind it (offset, sharp/round/square corners, miter limit), usable over MCP and the control channel too. - Contour tool: live preview, Shift rounds to whole points, Escape cancels, a dashed guide with a white halo shows the outline the shape had, and a pill shows the distance. - Contour bar: a floating bar above the selection with the offset box, Sharp / Round / Square and Bake (Expand Appearance). - Toolbar slot under Modify (Basic and Advanced) and dc-contour.svg, an original icon with its ASSETS.md row. - Tests for the command, the tool's pointer gestures and the bar; the border-with-a-gap recipe (two Contours, bake, Minus Front) is covered end to end. - Docs: beyond-Illustrator row, revision histories and the ROADMAP log. Beyond Illustrator: a VectorCraft design built on Offset Path. Scores and estimates unchanged. Co-Authored-By: Claude Sonnet 5.5 --- ASSETS.md | 1 + ROADMAP.md | 4 +- assets/icons/dc-contour.svg | 1 + crates/engine/src/cmd.rs | 2 + crates/engine/src/cmd/contour.rs | 82 ++++++ crates/engine/src/tests.rs | 1 + crates/engine/src/tests/contour.rs | 337 +++++++++++++++++++++++ crates/tools/src/catalog.rs | 1 + crates/tools/src/contour.rs | 232 ++++++++++++++++ crates/tools/src/lib.rs | 2 + crates/ui-egui/src/canvas.rs | 4 + crates/ui-egui/src/canvas/contour_bar.rs | 133 +++++++++ crates/ui-egui/src/canvas/tests.rs | 74 +++++ crates/ui-egui/src/edit_toolbar.rs | 2 +- crates/ui-egui/src/icon_data.rs | 1 + crates/ui-egui/src/icons.rs | 1 + crates/ui-egui/src/toolbar.rs | 1 + docs/gaps.md | 3 +- docs/target-app-parity.md | 4 +- docs/ui-parity.md | 3 +- 20 files changed, 884 insertions(+), 5 deletions(-) create mode 100644 assets/icons/dc-contour.svg create mode 100644 crates/engine/src/cmd/contour.rs create mode 100644 crates/engine/src/tests/contour.rs create mode 100644 crates/tools/src/contour.rs create mode 100644 crates/ui-egui/src/canvas/contour_bar.rs diff --git a/ASSETS.md b/ASSETS.md index e4a17c7640..b6f5fa007f 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -115,6 +115,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-center-show.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-clear.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-color-guide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-contour.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a solid rounded square inside four corner arcs, its offset outline); not derived from any other application's icon | MIT OR Apache-2.0 | | | `assets/icons/dc-crystallize.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-cube.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-dash-align.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | diff --git a/ROADMAP.md b/ROADMAP.md index e055747f18..e7000874f5 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,5 +1,7 @@ # VectorCraft Roadmap +- Contour tool (beyond Illustrator): drag a selected shape's edge outward or inward for a live, editable offset copy, with a floating bar for distance and Sharp, Round or Square corners; Bake turns it into paths. Scores and estimates unchanged. + - Paint: new gradients use the document's color model for default stops, including Gradient tool creation. Scores and estimates unchanged. - PDF.R1: editable PDF import uses the shared reader, scans page content in windows, and rejects known incomplete input before returning a document. @@ -11,7 +13,7 @@ **Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Type Tools add-on: Release Type on a Path, #5532; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Contour tool, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON diff --git a/assets/icons/dc-contour.svg b/assets/icons/dc-contour.svg new file mode 100644 index 0000000000..61c1f2ed82 --- /dev/null +++ b/assets/icons/dc-contour.svg @@ -0,0 +1 @@ + diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index b1b9efd60b..e59331691f 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -12,6 +12,7 @@ mod colorcmds; pub mod colormgmt; pub mod colortheme; mod compoundshape; +pub(crate) mod contour; pub(crate) mod create; mod css; mod cut; @@ -262,6 +263,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(xform::specs()); v.extend(effectcmd::specs()); v.extend(pathops::specs()); + v.extend(contour::specs()); v.extend(compoundshape::specs()); v.extend(typecmd::specs()); v.extend(menucmds::specs()); diff --git a/crates/engine/src/cmd/contour.rs b/crates/engine/src/cmd/contour.rs new file mode 100644 index 0000000000..5bbf5652bb --- /dev/null +++ b/crates/engine/src/cmd/contour.rs @@ -0,0 +1,82 @@ +//! `object.contour`: the Contour tool's command. A Contour is a copy of a selected shape that +//! carries a live Offset Path effect, so it grows or shrinks the shape without baking anything: its +//! fill, stroke and effect stay editable, and Expand Appearance bakes it into plain paths. The +//! original stays where it is. Running the command on an object that already carries an Offset +//! Path effect (a Contour made earlier) changes that effect instead of nesting another one. + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeKind; +use vectorcraft_render::effects; + +use super::edit::{copy_above, selected_roots}; +use super::pathops::{len_param, num_param}; +use super::{CommandSpec, EngineError, NodeId, Result, Session, bad, cmd, has_selection, str_param}; + +const C: &str = "object.contour"; +/// The live effect that does the offsetting (the one Effect › Path › Offset Path applies). +const EFFECT: &str = "path.offsetPath"; +/// The largest offset, in points; Offset Path takes the same. +const MAX_OFFSET: f64 = 1e5; + +pub fn specs() -> Vec { + vec![cmd!( + "object.contour", + "Contour", + [], + None, + "{offset: pt (negative insets), corners?: \"sharp\"|\"round\"|\"square\" (default sharp; square cuts each corner off flat), miterLimit?: 1..500 (4; sharp corners only)} make a copy of each selected path or shape directly above it with a live Offset Path effect, or, for a selected object that already has one (a Contour), change that effect: nothing is baked (Expand Appearance bakes it) and the original is kept → {ids, created, updated}", + has_selection, + contour + )] +} + +/// The Offset Path join a Contour corner style stands for. +fn joins_for(corners: Option<&str>) -> Result<&'static str> { + match corners.map(str::to_ascii_lowercase).as_deref() { + None | Some("sharp") => Ok("miter"), + Some("round") => Ok("round"), + Some("square") => Ok("bevel"), + Some(other) => Err(bad(C, format!("`corners` must be sharp, round or square, not `{other}`"))), + } +} + +fn contour(s: &mut Session, p: &Value) -> Result { + let offset = len_param(p, "offset").ok_or_else(|| bad(C, "missing `offset` (a distance in points)"))?; + if offset.abs() > MAX_OFFSET { + return Err(bad(C, "offset out of range")); + } + let joins = joins_for(str_param(p, "corners"))?; + let miter = num_param(p, "miterLimit").unwrap_or(4.0).clamp(1.0, 500.0); + let effect = effects::new_effect(EFFECT, &json!({"offset": offset, "joins": joins, "miterLimit": miter})) + .ok_or_else(|| EngineError::Other("Contour: the Offset Path effect is not available".into()))?; + let roots = selected_roots(s)?; + let (updated, created) = s.edit("Contour", |d, sel| { + // A shape that already carries Offset Path is a Contour: change it. Any other path or + // shape gets a Contour copy above it. Type, images and the rest are left alone. + let (mut again, mut fresh) = (vec![], vec![]); + for id in roots { + let Some(n) = d.node(id) else { continue }; + if !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) { + continue; + } + if n.appearance.effects.iter().any(|e| e.id == EFFECT) { + again.push(id); + } else { + fresh.push(id); + } + } + if again.is_empty() && fresh.is_empty() { + return Err(EngineError::Other("Contour: select paths or shapes".into())); + } + for id in &again { + if let Some(e) = d.node_mut(*id).and_then(|n| n.appearance.effects.iter_mut().rev().find(|e| e.id == EFFECT)) { + e.params = effect.params.clone(); + } + } + let made = copy_above(d, &fresh, |_, _, copy| copy.appearance.effects.push(effect.clone()))?; + sel.set(again.iter().chain(made.iter()).copied()); + Ok((again, made)) + })?; + let list = |ids: &[NodeId]| ids.iter().map(|i| i.0).collect::>(); + Ok(json!({ "ids": list(&[updated.as_slice(), created.as_slice()].concat()), "created": list(&created), "updated": list(&updated) })) +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 9ec3ccaf98..e78d828dc0 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -36,6 +36,7 @@ mod compoundpaint; mod constrain_new; mod constrain_tools; mod containers; +mod contour; mod css; mod cut; mod dashalign; diff --git a/crates/engine/src/tests/contour.rs b/crates/engine/src/tests/contour.rs new file mode 100644 index 0000000000..8ec0d7f454 --- /dev/null +++ b/crates/engine/src/tests/contour.rs @@ -0,0 +1,337 @@ +//! Tests for `object.contour`: a live Offset Path copy of a shape that stays editable until baked. + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeKind; +use vectorcraft_geom::Rect; + +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + let r = s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap(); + NodeId(r["id"].as_u64().unwrap()) +} + +fn ids_of(v: &Value, key: &str) -> Vec { + v[key].as_array().unwrap().iter().map(|x| NodeId(x.as_u64().unwrap())).collect() +} + +fn node(s: &Session, id: NodeId) -> vectorcraft_doc::Node { + s.doc().unwrap().doc.node(id).cloned().unwrap() +} + +fn effects_of(s: &Session, id: NodeId) -> Vec<(String, Value)> { + node(s, id).appearance.effects.iter().map(|e| (e.id.clone(), e.params.clone())).collect() +} + +fn bounds(s: &Session, id: NodeId) -> Rect { + node(s, id).geometric_bounds().unwrap() +} + +fn node_count(s: &Session) -> usize { + s.doc().unwrap().doc.node_count() +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +#[test] +fn contour_is_a_live_copy_above_the_original() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0); + let before = bounds(&s, a); + let r = s.execute("object.contour", &json!({"offset": 10})).unwrap(); + let (made, updated) = (ids_of(&r, "created"), ids_of(&r, "updated")); + assert_eq!((made.len(), updated.len()), (1, 0)); + // The original is untouched, the copy is above it and selected, and nothing is baked: the + // copy's own path is still the original's, with the effect on top. + assert!(effects_of(&s, a).is_empty()); + assert_eq!(bounds(&s, a), before); + assert_eq!(s.doc().unwrap().selection.objects, made); + let d = &s.doc().unwrap().doc; + assert!(d.index_path(made[0]).unwrap() > d.index_path(a).unwrap()); + assert_eq!(bounds(&s, made[0]), before); + let fx = effects_of(&s, made[0]); + assert_eq!(fx.len(), 1); + assert_eq!(fx[0].0, "path.offsetPath"); + assert_eq!(fx[0].1["offset"], json!(10.0)); + assert_eq!(fx[0].1["joins"], json!("miter")); +} + +#[test] +fn baking_a_contour_gives_the_grown_and_the_shrunk_shape() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0); + for (offset, want) in [(10.0, Rect::new(90.0, 90.0, 160.0, 150.0)), (-5.0, Rect::new(105.0, 105.0, 145.0, 135.0))] { + select(&mut s, &[a]); + s.execute("object.contour", &json!({"offset": offset})).unwrap(); + let baked = ids_of(&s.execute("effect.expandAppearance", &json!({})).unwrap(), "ids"); + let b = bounds(&s, baked[0]); + // The default stroke widens the baked art by its weight; compare the fill's edges. + let fill = baked_fill_bounds(&s, baked[0]); + assert!((fill.x0 - want.x0).abs() < 1e-2 && (fill.y1 - want.y1).abs() < 1e-2, "{offset}: {fill:?} vs {want:?} ({b:?})"); + } +} + +/// The bounds of the fill path inside a baked object (a group of its fill and stroke), or of the +/// object itself when it is one path. +fn baked_fill_bounds(s: &Session, id: NodeId) -> Rect { + match &node(s, id).kind { + NodeKind::Group { children, .. } => children.iter().filter_map(|c| c.geometric_bounds()).next().unwrap(), + _ => bounds(s, id), + } +} + +#[test] +fn a_second_drag_changes_the_contour_instead_of_nesting_one() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0); + let made = ids_of(&s.execute("object.contour", &json!({"offset": 10})).unwrap(), "created"); + let count = node_count(&s); + // The Contour is selected: the next call edits it. + let r = s.execute("object.contour", &json!({"offset": -4, "corners": "round"})).unwrap(); + assert_eq!(ids_of(&r, "updated"), made); + assert!(ids_of(&r, "created").is_empty()); + assert_eq!(node_count(&s), count, "no new object"); + let fx = effects_of(&s, made[0]); + assert_eq!(fx.len(), 1, "one Offset Path, not two"); + assert_eq!((fx[0].1["offset"].clone(), fx[0].1["joins"].clone()), (json!(-4.0), json!("round"))); + assert!(effects_of(&s, a).is_empty()); +} + +#[test] +fn corner_styles_choose_the_join() { + for (corners, joins) in [("sharp", "miter"), ("round", "round"), ("square", "bevel"), ("Round", "round")] { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 30.0, 30.0); + let made = ids_of(&s.execute("object.contour", &json!({"offset": 3, "corners": corners})).unwrap(), "created"); + assert_eq!(effects_of(&s, made[0])[0].1["joins"], json!(joins), "{corners}"); + } +} + +#[test] +fn contour_keeps_the_color_and_stroke_editable_on_the_copy() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 30.0, 30.0); + let made = ids_of(&s.execute("object.contour", &json!({"offset": 6})).unwrap(), "created"); + let original = node(&s, a).appearance.items.clone(); + assert_eq!(node(&s, made[0]).appearance.items, original, "the copy starts with the shape's own paint"); + // Recolouring the Contour (it is the selection) changes its fill only: the live effect stays + // and the original keeps its paint. + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + assert_ne!(node(&s, made[0]).appearance.items, original, "the copy took the new fill"); + assert_eq!(node(&s, a).appearance.items, original, "the original is untouched"); + assert_eq!(effects_of(&s, made[0]).len(), 1); +} + +#[test] +fn contour_is_one_undo_step() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 30.0, 30.0); + let count = node_count(&s); + s.execute("object.contour", &json!({"offset": 6})).unwrap(); + assert_eq!(node_count(&s), count + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(node_count(&s), count); + assert!(effects_of(&s, a).is_empty()); +} + +#[test] +fn contour_refuses_what_it_cannot_offset() { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 30.0, 30.0); + let count = node_count(&s); + for params in [json!({}), json!({"offset": "abc"}), json!({"offset": 1e300}), json!({"offset": 5, "corners": "pointy"})] { + assert!(s.execute("object.contour", ¶ms).is_err(), "{params}"); + } + // Nothing was added by the refused calls. + assert_eq!(node_count(&s), count); + // Type is not a path to offset. + s.execute("text.create", &json!({"x": 10, "y": 10, "text": "Hi"})).unwrap(); + let err = s.execute("object.contour", &json!({"offset": 5})).unwrap_err().to_string(); + assert!(err.contains("select paths or shapes"), "{err}"); +} + +/// The border-with-a-gap recipe: two Contours of one shape (the gap, then the border), baked, then +/// the gap taken out of the border with Minus Front, leaves a ring between the two. +#[test] +fn border_with_a_gap_from_two_contours_and_minus_front() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0); + // Strip the default stroke so the areas are plain. + s.execute("paint.setStroke", &json!({"none": true})).ok(); + // The gap first (+8), then the border (+20) from the same shape: both land directly above it, + // the later one lower, so the gap ends up in front of the border. + select(&mut s, &[a]); + let gap = ids_of(&s.execute("object.contour", &json!({"offset": 8})).unwrap(), "created")[0]; + select(&mut s, &[a]); + let border = ids_of(&s.execute("object.contour", &json!({"offset": 20})).unwrap(), "created")[0]; + let d = &s.doc().unwrap().doc; + assert!(d.index_path(gap).unwrap() > d.index_path(border).unwrap(), "the gap is in front of the border"); + select(&mut s, &[border, gap]); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + let both: Vec = s.doc().unwrap().selection.objects.to_vec(); + assert_eq!(both.len(), 2); + let ring = ids_of(&s.execute("object.pathfinder.minusFront", &json!({})).unwrap(), "ids"); + assert_eq!(ring.len(), 1); + // 90 x 80 outer minus 66 x 56 inner, with sharp corners. + let area = vectorcraft_pathops::area(&ring_path(&s, ring[0]).0, ring_path(&s, ring[0]).1); + assert!((area - (90.0 * 80.0 - 66.0 * 56.0)).abs() < 1.0, "{area}"); +} + +fn ring_path(s: &Session, id: NodeId) -> (vectorcraft_geom::PathData, vectorcraft_geom::FillRule) { + match &node(s, id).kind { + NodeKind::Path { path, rule, .. } => (path.clone(), *rule), + NodeKind::Compound { children, rule } => { + (vectorcraft_geom::PathData::new(children.iter().flat_map(|c| c.path_data().unwrap().subpaths.clone()).collect()), *rule) + } + NodeKind::Group { children, .. } => children.first().map(|c| ring_path(s, c.id)).unwrap(), + _ => panic!("not a path"), + } +} + +mod tool { + use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + + use super::*; + use crate::tooling::ViewInfo; + + fn view() -> ViewInfo { + ViewInfo { smart_guides: false, ..Default::default() } + } + + fn at(s: &mut Session, kind: PointerKind, x: f64, y: f64, mods: Mods) { + s.pointer(&PointerEvent::new(kind, x, y).with_mods(mods), view()).unwrap(); + } + + fn undo_depth(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() + } + + /// A 50 x 40 rectangle at (100, 100), selected, with the Contour tool active. + fn ready() -> (Session, NodeId) { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0); + select(&mut s, &[a]); + s.select_tool("contour", view()).unwrap(); + (s, a) + } + + fn offset_of(s: &Session, id: NodeId) -> f64 { + effects_of(s, id)[0].1["offset"].as_f64().unwrap() + } + + #[test] + fn dragging_out_previews_live_and_commits_one_undo_step() { + let (mut s, a) = ready(); + let (before, nodes) = (undo_depth(&s), node_count(&s)); + // Press on the right edge and pull 10 pt away from the shape. + at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Drag, 160.0, 120.0, Mods::default()); + assert!(s.in_interaction(), "the Contour is previewed while the button is down"); + at(&mut s, PointerKind::Up, 160.0, 120.0, Mods::default()); + assert!(!s.in_interaction()); + assert_eq!(undo_depth(&s), before + 1); + assert_eq!(node_count(&s), nodes + 1); + assert_eq!(s.journal.last().map(|j| j.0.as_str()), Some("object.contour")); + let made = s.doc().unwrap().selection.objects.clone(); + assert_eq!(made.len(), 1); + assert_ne!(made[0], a); + assert!((offset_of(&s, made[0]) - 10.0).abs() < 1e-6, "{}", offset_of(&s, made[0])); + assert!(effects_of(&s, a).is_empty(), "the original is kept as it was"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(node_count(&s), nodes); + } + + #[test] + fn dragging_in_shrinks_and_a_second_drag_continues_from_where_the_contour_stands() { + let (mut s, _) = ready(); + // From inside, 5 pt toward the middle of the right edge's neighbourhood. + at(&mut s, PointerKind::Down, 145.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Drag, 140.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Up, 140.0, 120.0, Mods::default()); + let contour = s.doc().unwrap().selection.objects[0]; + assert!((offset_of(&s, contour) + 5.0).abs() < 1e-6); + // The Contour is selected: pressing at the edge and pulling out 12 pt adds to its -5. + let nodes = node_count(&s); + at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Drag, 162.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Up, 162.0, 120.0, Mods::default()); + assert_eq!(node_count(&s), nodes, "the same Contour changed, none was nested"); + assert_eq!(s.doc().unwrap().selection.objects, vec![contour]); + assert_eq!(effects_of(&s, contour).len(), 1); + assert!((offset_of(&s, contour) - 7.0).abs() < 1e-6, "{}", offset_of(&s, contour)); + } + + #[test] + fn escape_and_a_plain_click_change_nothing() { + let (mut s, _) = ready(); + let (before, nodes) = (undo_depth(&s), node_count(&s)); + at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Drag, 170.0, 120.0, Mods::default()); + assert!(s.in_interaction()); + s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap(); + at(&mut s, PointerKind::Up, 170.0, 120.0, Mods::default()); + assert!(!s.in_interaction()); + assert_eq!((undo_depth(&s), node_count(&s)), (before, nodes)); + // A click with no movement. + at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Up, 150.0, 120.0, Mods::default()); + assert_eq!((undo_depth(&s), node_count(&s)), (before, nodes)); + } + + #[test] + fn shift_rounds_to_whole_points_and_the_corner_option_is_used() { + let (mut s, _) = ready(); + s.set_tool_option("corners", &json!("round")); + let shift = Mods { shift: true, ..Mods::default() }; + at(&mut s, PointerKind::Down, 150.0, 120.0, shift); + at(&mut s, PointerKind::Drag, 160.4, 120.0, shift); + at(&mut s, PointerKind::Up, 160.4, 120.0, shift); + let contour = s.doc().unwrap().selection.objects[0]; + assert_eq!(offset_of(&s, contour), 10.0); + assert_eq!(effects_of(&s, contour)[0].1["joins"], json!("round")); + } + + /// The outline a Contour was made from shows as a dashed guide over a solid halo (so it reads + /// over any fill); a shape that is not a Contour yet has none. + #[test] + fn a_selected_contour_shows_the_outline_it_was_made_from() { + use vectorcraft_tools::Overlay; + let (mut s, _) = ready(); + let paths = |s: &mut Session| -> Vec<(bool, f32)> { + s.overlays(view()) + .into_iter() + .filter_map(|o| match o { + Overlay::Path { dashed, width, .. } => Some((dashed, width)), + _ => None, + }) + .collect() + }; + assert!(paths(&mut s).is_empty(), "a plain shape has no guide"); + at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Drag, 160.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Up, 160.0, 120.0, Mods::default()); + // The solid halo first, the dashes on top of it. + assert_eq!(paths(&mut s), [(false, 3.0), (true, 1.0)]); + } + + #[test] + fn nothing_selected_does_nothing() { + let mut s = session(); + rect(&mut s, 100.0, 100.0, 50.0, 40.0); + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("contour", view()).unwrap(); + let before = undo_depth(&s); + at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Drag, 170.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Up, 170.0, 120.0, Mods::default()); + assert_eq!(undo_depth(&s), before); + } +} diff --git a/crates/tools/src/catalog.rs b/crates/tools/src/catalog.rs index 9bbd7cbdfb..49fe557ea9 100644 --- a/crates/tools/src/catalog.rs +++ b/crates/tools/src/catalog.rs @@ -94,6 +94,7 @@ pub const TOOL_GROUPS: &[&[ToolInfo]] = &[ t("livePaintBucket", "Live Paint Bucket", Some("K"), "tool-bucket"), t("livePaintSelection", "Live Paint Selection Tool", Some("Shift+L"), "tool-live-select"), ], + &[t("contour", "Contour Tool", None, "tool-contour")], &[ t("perspectiveGrid", "Perspective Grid Tool", Some("Shift+P"), "tool-perspective"), t("perspectiveSelection", "Perspective Selection Tool", Some("Shift+V"), "tool-perspective-select"), diff --git a/crates/tools/src/contour.rs b/crates/tools/src/contour.rs new file mode 100644 index 0000000000..a23329b7b8 --- /dev/null +++ b/crates/tools/src/contour.rs @@ -0,0 +1,232 @@ +//! The Contour tool: drag away from a selected shape's edge to grow a live copy of it, or toward the +//! inside to shrink it (`object.contour`). The copy is the original's outline offset by the distance +//! the pointer has moved from the edge, previewed while the button is down and kept as one undo step +//! on release. Nothing is baked: the copy carries a live Offset Path effect, so it keeps being +//! editable (a second drag on a selected Contour changes its distance instead of nesting another), +//! and Expand Appearance bakes it. While a Contour is selected the tool draws the outline the +//! shape had before as a dashed guide. +//! +//! The distance is how far the pointer has moved from the shape's edge since the press, so a press +//! anywhere changes nothing until the pointer moves, and a Contour that already stands at some +//! distance continues from there. Shift rounds the distance to whole points. + +use serde_json::{Value, json}; +use vectorcraft_doc::{Node, NodeKind}; +use vectorcraft_geom::{BezPath, FillRule, Point, hit}; + +use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; + +/// The live effect a Contour is made of (the one `object.contour` applies). +const EFFECT: &str = "path.offsetPath"; +/// The largest distance, in points, `object.contour` accepts. +const MAX_OFFSET: f64 = 1e5; +/// The guide showing the shape a Contour was made from. +const GUIDE: [u8; 3] = [0x1e, 0x88, 0xe5]; + +/// A selected shape's outline, in the document. +struct Base { + path: BezPath, + rule: FillRule, +} + +fn base_of(n: &Node) -> Option { + match &n.kind { + NodeKind::Path { path, rule, .. } => Some(Base { path: path.to_bezpath(), rule: *rule }), + NodeKind::Compound { children, rule } => { + let mut path = BezPath::new(); + for c in children { + if let Some(p) = c.path_data() { + path.extend(p.to_bezpath().elements().iter().copied()); + } + } + Some(Base { path, rule: *rule }) + } + _ => None, + } +} + +/// The Offset Path distance of a Contour (a shape that carries the effect). +fn contour_offset(n: &Node) -> Option { + let e = n.appearance.effects.iter().rev().find(|e| e.id == EFFECT)?; + Some(e.params.get("offset").and_then(Value::as_f64).unwrap_or(0.0)) +} + +/// How far `p` is from the nearest of `bases`' edges: positive outside, negative inside. +fn signed_distance(bases: &[Base], p: Point) -> Option { + let mut nearest = f64::INFINITY; + let mut inside = false; + for b in bases { + nearest = nearest.min(hit::distance_to_outline(&b.path, p)); + inside |= hit::fill_contains(&b.path, b.rule, p); + } + nearest.is_finite().then_some(if inside { -nearest } else { nearest }) +} + +/// A press in progress. +struct Drag { + bases: Vec, + /// Where the pointer stood against the edge at the press. + pressed_at: f64, + /// The Contour's distance at the press (0 for a shape that is not one yet). + start: f64, + /// The distance last previewed. + last: Option, + /// Where the pointer is, for the distance label. + pos: Point, +} + +#[derive(Default)] +pub struct ContourTool { + drag: Option, + corners: Corners, + miter_limit: Option, +} + +/// How a Contour treats the corners of the shape. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum Corners { + /// Pointed (mitered) corners. + #[default] + Sharp, + Round, + /// Corners cut off flat. + Square, +} + +impl Corners { + fn id(self) -> &'static str { + match self { + Corners::Sharp => "sharp", + Corners::Round => "round", + Corners::Square => "square", + } + } + + fn parse(s: &str) -> Option { + [Corners::Sharp, Corners::Round, Corners::Square].into_iter().find(|c| c.id().eq_ignore_ascii_case(s)) + } +} + +impl ContourTool { + fn params(&self, offset: f64) -> Value { + let mut p = json!({"offset": offset, "corners": self.corners.id()}); + if let Some(m) = self.miter_limit { + p["miterLimit"] = json!(m); + } + p + } +} + +/// The selected shapes a Contour can be made of. +fn selected_shapes<'a>(cx: &'a ToolContext) -> Vec<&'a Node> { + cx.selection + .objects + .iter() + .filter_map(|id| cx.doc.node(*id)) + .filter(|n| matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })) + .collect() +} + +fn round_distance(v: f64, mods: Mods) -> f64 { + let v = if mods.shift { v.round() } else { (v * 100.0).round() / 100.0 }; + v.clamp(-MAX_OFFSET, MAX_OFFSET) +} + +impl Tool for ContourTool { + fn id(&self) -> &'static str { + "contour" + } + + fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + match ev.kind { + PointerKind::Down => { + let shapes = selected_shapes(cx); + let start = shapes.first().and_then(|n| contour_offset(n)).unwrap_or(0.0); + let bases: Vec = shapes.into_iter().filter_map(base_of).collect(); + let Some(pressed_at) = signed_distance(&bases, ev.pos) else { return vec![] }; + self.drag = Some(Drag { bases, pressed_at, start, last: None, pos: ev.pos }); + vec![Action::Begin("Contour".into())] + } + PointerKind::Drag => { + let mut params = self.params(0.0); + let Some(drag) = self.drag.as_mut() else { return vec![] }; + drag.pos = ev.pos; + let Some(now) = signed_distance(&drag.bases, ev.pos) else { return vec![] }; + let offset = round_distance(drag.start + now - drag.pressed_at, ev.mods); + if !offset.is_finite() || drag.last == Some(offset) { + return vec![]; + } + drag.last = Some(offset); + params["offset"] = json!(offset); + vec![Action::Preview("object.contour".into(), params)] + } + PointerKind::Up => match self.drag.take() { + Some(d) if d.last.is_some() => vec![Action::Commit], + Some(_) => vec![Action::Cancel], + None => vec![], + }, + _ => vec![], + } + } + + fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + match key { + ToolKey::Escape if self.drag.take().is_some() => vec![Action::Cancel], + _ => vec![], + } + } + + fn overlays(&self, cx: &ToolContext) -> Vec { + let mut out = vec![]; + // The outline each selected Contour was made from. + for n in selected_shapes(cx) { + if contour_offset(n).is_none() { + continue; + } + if let Some(b) = base_of(n) { + // A white halo under the dashes, so the guide shows over any fill. + out.push(Overlay::Path { path: b.path.clone(), color: [255, 255, 255], width: 3.0, dashed: false }); + out.push(Overlay::Path { path: b.path, color: GUIDE, width: 1.0, dashed: true }); + } + } + if let Some(d) = &self.drag + && let Some(offset) = d.last + { + out.push(Overlay::Measure { p: d.pos, text: format!("{offset:+.2} pt") }); + } + out + } + + fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor { + Cursor::Crosshair + } + + fn options(&self) -> Value { + json!({"corners": self.corners.id(), "miterLimit": self.miter_limit.unwrap_or(4.0)}) + } + + fn set_option(&mut self, key: &str, value: &Value) { + match key { + "corners" => { + if let Some(c) = value.as_str().and_then(Corners::parse) { + self.corners = c; + } + } + "miterLimit" => { + if let Some(m) = value.as_f64().filter(|m| m.is_finite()) { + self.miter_limit = Some(m.clamp(1.0, 500.0)); + } + } + _ => {} + } + } + + fn busy(&self) -> bool { + self.drag.is_some() + } +} + +/// The Contour tool, for [`crate::create`]. +pub fn create(id: &str) -> Option> { + (id == "contour").then(|| Box::new(ContourTool::default()) as Box) +} diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index ee00fdbe97..d14e43c675 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -11,6 +11,7 @@ pub mod addons; pub mod bbox; pub mod builder; pub mod catalog; +pub mod contour; pub mod corners; pub mod cropimage; pub mod cut; @@ -296,6 +297,7 @@ pub fn create(id: &str) -> Box { .or_else(|| printtiling::create(other)) .or_else(|| cropimage::create(other)) .or_else(|| cut::create(other)) + .or_else(|| contour::create(other)) .or_else(|| intertwine::create(other)) .or_else(|| objects_on_path::create(other)) .or_else(|| touchtype::create(other)) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 0b563c24c5..f99c524f12 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -17,6 +17,7 @@ use crate::{CacheKey, VectorcraftApp, now_ms, widgets}; mod artboards; mod context; +mod contour_bar; mod cursor; mod drag; mod fill; @@ -360,6 +361,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if app.ui.task_bar && !revolve_edit && !dragging && app.ui.screen_mode < 3 && !strip { task_bar(app, ui, &xf); } + if app.ui.screen_mode < 3 { + contour_bar::contour_bar(app, ui, &xf); + } if app.ui.screen_mode < 3 { crate::free_transform::show(app, ui, xf.rect); } diff --git a/crates/ui-egui/src/canvas/contour_bar.rs b/crates/ui-egui/src/canvas/contour_bar.rs new file mode 100644 index 0000000000..443fdc2aa9 --- /dev/null +++ b/crates/ui-egui/src/canvas/contour_bar.rs @@ -0,0 +1,133 @@ +//! The Contour bar: a floating bar above the selection while the Contour tool is active. It has the +//! Contour's distance in a number box, its corner style (Sharp, Round or Square) and Bake, which +//! turns the live Contour into plain paths. It acts through `object.contour` and +//! `effect.expandAppearance`, so everything it does is a command with its own undo step. + +use serde_json::Value; +use vectorcraft_doc::{Node, NodeKind}; + +use super::{CornerRadius, Stroke, Tokens, Ui, VectorcraftApp, Xf, json, pos2, vec2}; + +/// The live effect a Contour is made of. +const EFFECT: &str = "path.offsetPath"; + +fn bar_id() -> egui::Id { + egui::Id::unique("contour-bar") +} + +/// Where the Contour bar was last drawn (none while it isn't shown). +#[cfg(test)] +pub(super) fn bar_rect(ctx: &egui::Context) -> Option { + let id = bar_id(); + ctx.memory(|m| m.areas().is_visible(&egui::LayerId::new(egui::Order::Middle, id)).then(|| m.area_rect(id)).flatten()) +} + +/// A selected Contour's distance and corner style, read from its Offset Path effect. +struct Standing { + offset: f64, + corners: &'static str, +} + +fn standing(n: &Node) -> Option { + let e = n.appearance.effects.iter().rev().find(|e| e.id == EFFECT)?; + let offset = e.params.get("offset").and_then(Value::as_f64).unwrap_or(0.0); + let corners = match e.params.get("joins").and_then(Value::as_str) { + Some("round") => "round", + Some("bevel") => "square", + _ => "sharp", + }; + Some(Standing { offset, corners }) +} + +/// The Contour bar, over the selection's top edge (under it when the top is off the canvas). +pub(super) fn contour_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { + if app.session.tool_id() != "contour" { + return; + } + let Some(b) = app.selection_bounds() else { return }; + let Some(st) = app.session.active() else { return }; + let shapes: Vec<&Node> = st + .selection + .objects + .iter() + .filter_map(|id| st.doc.node(*id)) + .filter(|n| matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })) + .collect(); + if shapes.is_empty() { + return; + } + let stand = shapes.first().and_then(|n| standing(n)); + drop(shapes); + let tool_corners = app.session.tool_options().get("corners").and_then(Value::as_str).unwrap_or("sharp").to_string(); + let corners = stand.as_ref().map_or(tool_corners.as_str(), |s| s.corners); + let shown = stand.as_ref().map_or(0.0, |s| s.offset); + // A grown Contour reaches past the outline it was made from: keep the bar clear of it. + let b = b.inflate(shown.max(0.0), shown.max(0.0)); + + let t = Tokens::get(ui.ctx()); + let quad = xf.quad(b); + let top = quad.iter().map(|c| c.y).fold(f32::INFINITY, f32::min); + let bottom = quad.iter().map(|c| c.y).fold(f32::NEG_INFINITY, f32::max); + let size = egui::AreaState::load(ui.ctx(), bar_id()).and_then(|s| s.size).unwrap_or(vec2(330.0, 40.0)); + let area = xf.rect.shrink(8.0); + let above = top - size.y - 12.0; + let y = if above >= area.top() { above } else { bottom + 12.0 }; + let at = pos2(xf.to_screen(b.center()).x - size.x / 2.0, y); + let at = at.clamp(area.min, (area.max - size).max(area.min)); + + let mut run: Option<(&str, Value)> = None; + let mut corner_pick: Option<&str> = None; + egui::Area::new(bar_id()).order(egui::Order::Middle).fixed_pos(at).show(ui.ctx(), |ui| { + egui::Frame::NONE + .fill(t.panel) + .stroke(Stroke::new(1.0, t.tool_active)) + .corner_radius(CornerRadius::same(5)) + .inner_margin(egui::Margin::symmetric(8, 6)) + .shadow(egui::epaint::Shadow { offset: [0, 3], blur: 10, spread: 0, color: egui::Color32::from_black_alpha(70) }) + .show(ui, |ui| { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 6.0; + ui.label(egui::RichText::new(tl!("Contour")).color(t.text_strong)); + // The distance: a drag or typed value is applied when it ends, as one step. + let key = egui::Id::unique("contour-bar-offset"); + let mut v = ui.data(|d| d.get_temp::(key)).unwrap_or(shown); + let resp = ui.add(egui::DragValue::new(&mut v).speed(0.5).range(-1e5..=1e5).suffix(" pt")); + if resp.dragged() || resp.has_focus() { + ui.data_mut(|d| d.insert_temp(key, v)); + } + if resp.drag_stopped() || resp.lost_focus() { + ui.data_mut(|d| d.remove_temp::(key)); + if (v - shown).abs() > 1e-9 { + run = Some(("object.contour", json!({"offset": v, "corners": corners}))); + } + } + for (label, id) in [(tl!("Sharp"), "sharp"), (tl!("Round"), "round"), (tl!("Square"), "square")] { + if ui.selectable_label(corners == id, label).clicked() { + corner_pick = Some(id); + } + } + let bake = ui.add_enabled(stand.is_some(), egui::Button::new(tl!("Bake"))); + if bake.on_hover_text(tl!("Turn the Contour into plain paths")).clicked() { + run = Some(("effect.expandAppearance", json!({}))); + } + }); + }); + }); + if let Some(id) = corner_pick { + // The tool keeps the style for the next Contour; a selected Contour changes now. + let mut result = app.run("tool.setOption", json!({"key": "corners", "value": id})); + if result.is_ok() + && let Some(s) = &stand + { + result = app.run("object.contour", json!({"offset": s.offset, "corners": id})); + } + if let Err(e) = result { + app.ui.status = e; + } + } + if let Some((cmd, params)) = run + && let Err(e) = app.run(cmd, params) + { + app.ui.status = e; + } +} diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index edfeebca41..da52ed353f 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -8988,3 +8988,77 @@ fn poll_worker_accepts_frames_not_older_than_displayed_and_discards_obsolete_fra assert_eq!(set_count, 1, "settled frame 10 is uploaded to texture"); assert_eq!(app.canvas.key.as_ref().unwrap().revision, 10, "settled frame 10 is uploaded"); } + +/// The labels the Contour bar draws in a headless frame, with their rects; none while it isn't +/// shown. +fn contour_bar_labels(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec<(String, egui::Rect)> { + egui_extras::install_image_loaders(ctx); + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + let Some(bar) = contour_bar::bar_rect(ctx) else { return vec![] }; + out.shapes + .iter() + .filter_map(|c| match &c.shape { + egui::Shape::Text(t) if bar.contains(t.visual_bounding_rect().center()) => Some((t.galley.text().to_string(), t.visual_bounding_rect())), + _ => None, + }) + .collect() +} + +/// A click on the centre of the label `name` of the Contour bar, laid out by one frame before it. +fn click_contour_bar(app: &mut VectorcraftApp, ctx: &egui::Context, name: &str) { + let labels = contour_bar_labels(app, ctx, vec![]); + let at = labels.iter().find(|(t, _)| t == name).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{name}` in {labels:?}")); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + contour_bar_labels(app, ctx, vec![egui::Event::PointerMoved(at)]); + contour_bar_labels(app, ctx, vec![button(true), button(false)]); +} + +/// The Contour bar shows with the Contour tool and a shape selected: Sharp, Round and Square set the +/// corner style (of a selected Contour at once, else of the next one), and Bake turns a Contour into +/// plain paths. +#[test] +fn the_contour_bar_sets_corners_and_bakes() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 80, "height": 60})).unwrap(); + let ctx = egui::Context::default(); + + // Only the Contour tool shows it. + app.select_tool("selection"); + assert!(contour_bar_labels(&mut app, &ctx, vec![]).is_empty()); + app.select_tool("contour"); + contour_bar_labels(&mut app, &ctx, vec![]); + let names: Vec = contour_bar_labels(&mut app, &ctx, vec![]).into_iter().map(|(t, _)| t).collect(); + for want in ["Contour", "Sharp", "Round", "Square", "Bake"] { + assert!(names.iter().any(|n| n == want), "{want} in {names:?}"); + } + let offsets = |app: &VectorcraftApp| { + let mut found = vec![]; + app.session.active().unwrap().doc.walk(|n| { + if let Some(e) = n.appearance.effects.iter().find(|e| e.id == "path.offsetPath") { + found.push(e.params["joins"].as_str().unwrap_or_default().to_string()); + } + }); + found + }; + + // No Contour yet: Round is kept for the next one, and Bake does nothing. + let steps = app.session.active().unwrap().history.undo.len(); + click_contour_bar(&mut app, &ctx, "Round"); + assert_eq!(app.session.tool_options()["corners"], json!("round")); + click_contour_bar(&mut app, &ctx, "Bake"); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps, "nothing to bake"); + assert!(offsets(&app).is_empty()); + + // A Contour made now has round corners; Square changes the selected Contour in place. + app.session.execute("object.contour", &json!({"offset": 8, "corners": "round"})).unwrap(); + assert_eq!(offsets(&app), ["round"]); + click_contour_bar(&mut app, &ctx, "Square"); + assert_eq!(offsets(&app), ["bevel"], "the selected Contour changed, none was added"); + + // Bake: the live effect is gone and the art stays. + click_contour_bar(&mut app, &ctx, "Bake"); + assert!(offsets(&app).is_empty(), "baked"); +} diff --git a/crates/ui-egui/src/edit_toolbar.rs b/crates/ui-egui/src/edit_toolbar.rs index eb79cf3570..dcec1ffc5b 100644 --- a/crates/ui-egui/src/edit_toolbar.rs +++ b/crates/ui-egui/src/edit_toolbar.rs @@ -410,7 +410,7 @@ fn heading(id: &str) -> &'static str { _ if id.starts_with("perspective") => "Perspective", "artboard" => "Artboards", "slice" | "sliceSelection" => "Slices", - "objectsOnPath" => "Modify", + "objectsOnPath" | "contour" => "Modify", _ => "More", } } diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs index 579df2187b..78eb6149d1 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -60,6 +60,7 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-center-show", include_bytes!("../../../assets/icons/dc-center-show.svg")), ("dc-clear", include_bytes!("../../../assets/icons/dc-clear.svg")), ("dc-color-guide", include_bytes!("../../../assets/icons/dc-color-guide.svg")), + ("dc-contour", include_bytes!("../../../assets/icons/dc-contour.svg")), ("dc-crystallize", include_bytes!("../../../assets/icons/dc-crystallize.svg")), ("dc-cube", include_bytes!("../../../assets/icons/dc-cube.svg")), ("dc-dash-align", include_bytes!("../../../assets/icons/dc-dash-align.svg")), diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index a3601af18d..e352653279 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -85,6 +85,7 @@ pub fn tool_icon(name: &str) -> &'static str { "tool-eyedropper" => "pipette", "tool-measure" => "dc-measure", "tool-dimension" => "dc-dimension", + "tool-contour" => "dc-contour", "tool-blend" => "dc-blend", "tool-objects-on-path" => "dc-objects-on-path", "tool-symbol" => "dc-symbol-sprayer", diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 94054a0d46..fcb9a1cc9e 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -59,6 +59,7 @@ pub const BASIC: &[(&str, &[&[&str]])] = &[ &["rotate", "reflect", "scale", "shear", "reshape", "freeTransform", "puppetWarp"], &["shapeBuilder", "livePaintBucket", "livePaintSelection", "blend"], &["dimension"], + &["contour"], ], ), ("Type", &[&["areaType", "typeOnPath", "verticalAreaType", "verticalTypeOnPath"], &["type", "verticalType", "touchType"]]), diff --git a/docs/gaps.md b/docs/gaps.md index 7dc084a0a0..92ee96cb97 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Contour tool, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -28,6 +28,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | Contour tool (beyond Illustrator): drag away from a selected shape's edge to grow a live copy of it, or toward the inside to shrink it; the copy carries a live Offset Path effect, so it stays editable until Bake (Expand Appearance), a second drag changes the same Contour instead of nesting one, and a floating bar sets the distance and the Sharp, Round or Square corners. `object.contour` is the command behind it. A VectorCraft design built on Offset Path; no other application was inspected. Scores and estimates unchanged. | | 2026-11-05 | minor | G12: Hyphenation › Default Language sets the language of new type unless Document Setup chose one, stored as a tag; each run hyphenates in its own language, English only so far, so 2 Preferences options stay unused (#394) | | 2026-11-03 | minor | New gradients use CMYK default stops in CMYK documents, including Gradient tool creation. Scores and estimates unchanged. | | 2026-11-02 | minor | Font-family fields step selected text with the mouse wheel (#5253); no scored gap or estimate reassessed. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 17db9d3f2e..76c4c4ab2d 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-05 · **Change:** minor (document tabs are reordered by dragging them along the tab strip; 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-05 · **Change:** minor (Contour tool, beyond Illustrator; scores and estimates unchanged; Select by Artboards add-on selects by overlap, inside or outside several artboards; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -482,6 +482,7 @@ since 2026-10-01. | **Agent automation** | beyond Illustrator | Every command, gesture and dialog is drivable over MCP, the CLI and the control channel; synthetic-input counts, pending events and per-frame control requests are bounded (#1709); what an agent reads and writes on disk can be confined to chosen folders (`--automation-read-root` / `--automation-write-root`, as in PhotoCraft, #832) | | **Scrubby numeric fields** | beyond Illustrator | As in Photoshop, dragging a numeric field's label (`W:`, `Opacity:`, the Character panel's icons) left or right steps its value live; one undo step per drag, Escape cancels (#400) | | **Align Stroke on live type** | beyond Illustrator | The Stroke panel's Align Stroke works on type's character stroke: inside or outside the glyphs without Create Outlines, the type staying editable (as InDesign does; users have asked Illustrator for it since 2010, e.g. [redd.it/1dwhos6](https://redd.it/1dwhos6)). Canvas, PDF and EPS clip it to its side of the glyphs; SVG keeps the text live and draws the stroke on the glyph outlines (#2294) | +| **Contour tool** | beyond Illustrator | Drag away from a selected shape's edge to grow a live copy of it, or toward the inside to shrink it (Shift: whole points); the copy carries a live Offset Path effect so it stays editable, with its own fill and stroke, until Bake (Expand Appearance). A second drag on a selected Contour changes it instead of nesting another; Escape cancels. A floating bar above the selection sets the distance and the corners (Sharp, Round, Square); `object.contour` makes or changes one over MCP and the control channel. Two Contours baked and combined with Minus Front give a border with a gap. Paths, shapes and compound paths only; type isn't offset. Tests: `crates/engine/src/tests/contour.rs`, `crates/ui-egui/src/canvas/tests.rs` | ## Evidence: what ships today, by area @@ -1649,6 +1650,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | Contour tool (beyond Illustrator): drag away from a selected shape's edge to grow a live copy of it, or toward the inside to shrink it; the copy carries a live Offset Path effect, so it stays editable until Bake (Expand Appearance), a second drag changes the same Contour instead of nesting one, and a floating bar sets the distance and the Sharp, Round or Square corners. `object.contour` is the command behind it. A VectorCraft design built on Offset Path; no other application was inspected. Scores and estimates unchanged. | | 2026-11-05 | minor | View & navigation: document tabs are reordered by dragging them along the tab strip (`document.move`, #5663); evidence added; scores unchanged. | | 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-11-01 | minor | Batch Trace Folder (`imageTrace.batchFolder`, #4921); evidence added; scores unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 7b50110245..282eea9b6a 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (document tabs are reordered by dragging them along the tab strip; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Contour tool, beyond Illustrator; scores and estimates unchanged; Select by Artboards add-on selects by overlap, inside or outside several artboards; Cmd+Space keeps the active drawing cursor during its drag; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) ## Feature submission evidence @@ -437,6 +437,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | Contour tool (beyond Illustrator): drag away from a selected shape's edge to grow a live copy of it, or toward the inside to shrink it; the copy carries a live Offset Path effect, so it stays editable until Bake (Expand Appearance), a second drag changes the same Contour instead of nesting one, and a floating bar sets the distance and the Sharp, Round or Square corners. `object.contour` is the command behind it. A VectorCraft design built on Offset Path; no other application was inspected. Scores and estimates unchanged. | | 2026-11-05 | minor | Document tabs are reordered by dragging them along the tab strip (`document.move`, #5663). | | 2026-11-04 | minor | Path Precision Tools add-on (a VectorCraft addition): Set Corners… rounds only the corners in an angle range (#5545); scores and estimates unchanged | | 2026-11-04 | minor | Path Precision Tools add-on (a VectorCraft addition): Set Corners… rounds all, the odd-numbered or the even-numbered anchors (#5546); scores and estimates unchanged | From 8ce22e71eba827b1bd3c1ce42dda64b60fa11b96 Mon Sep 17 00:00:00 2001 From: Kindmark <39938776+Kindmark@users.noreply.github.com> Date: Wed, 4 Nov 2026 21:57:11 -0600 Subject: [PATCH 040/196] Contour: keep a Contour's corners when dragged again; ignore a no-distance drag Two fixes from review of #5694, each with a test that fails without it: - Dragging a selected Contour sent the tool's own corner options, so a Round or Square Contour came back Sharp and lost its miter limit, and the Contour bar (which reads the effect) disagreed with the shape. The press now reads the Contour's own corners and miter limit and every preview of that drag carries them; a new Contour still takes the tool's options. - A drag that never moved the distance (along the edge, or rounded to nothing by Shift) previewed offset 0 and committed an unchanged copy and an undo step. Nothing is previewed until the distance leaves where it started. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/tests/contour.rs | 34 ++++++++++++++++++++++++++++++ crates/tools/src/contour.rs | 34 +++++++++++++++++++++++++----- 2 files changed, 63 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/tests/contour.rs b/crates/engine/src/tests/contour.rs index 8ec0d7f454..164370c757 100644 --- a/crates/engine/src/tests/contour.rs +++ b/crates/engine/src/tests/contour.rs @@ -299,6 +299,40 @@ mod tool { assert_eq!(effects_of(&s, contour)[0].1["joins"], json!("round")); } + /// A Contour keeps its own corner style and miter limit when it is dragged again, whatever the + /// tool's options are by then (they said Sharp when the Contour was made Square). + #[test] + fn dragging_a_contour_again_keeps_its_corners_and_miter_limit() { + let (mut s, _) = ready(); + s.execute("object.contour", &json!({"offset": 5, "corners": "square", "miterLimit": 7})).unwrap(); + let contour = s.doc().unwrap().selection.objects[0]; + s.set_tool_option("corners", &json!("sharp")); + at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Drag, 158.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Up, 158.0, 120.0, Mods::default()); + let fx = effects_of(&s, contour); + assert_eq!(fx.len(), 1); + assert!((offset_of(&s, contour) - 13.0).abs() < 1e-6, "{}", offset_of(&s, contour)); + assert_eq!(fx[0].1["joins"], json!("bevel"), "{:?}", fx[0].1); + assert_eq!(fx[0].1["miterLimit"], json!(7.0), "{:?}", fx[0].1); + } + + /// A drag that never moves the distance (along the edge, or rounded back to nothing by Shift) + /// leaves no unchanged copy and no undo step. + #[test] + fn a_drag_along_the_edge_changes_nothing() { + let (mut s, _) = ready(); + let (before, nodes) = (undo_depth(&s), node_count(&s)); + let shift = Mods { shift: true, ..Mods::default() }; + for (mods, to) in [(Mods::default(), (150.0, 135.0)), (shift, (150.3, 120.0))] { + at(&mut s, PointerKind::Down, 150.0, 120.0, mods); + at(&mut s, PointerKind::Drag, to.0, to.1, mods); + at(&mut s, PointerKind::Up, to.0, to.1, mods); + assert_eq!((undo_depth(&s), node_count(&s)), (before, nodes), "{to:?}"); + assert!(!s.in_interaction()); + } + } + /// The outline a Contour was made from shows as a dashed guide over a solid halo (so it reads /// over any fill); a shape that is not a Contour yet has none. #[test] diff --git a/crates/tools/src/contour.rs b/crates/tools/src/contour.rs index a23329b7b8..cf450752c6 100644 --- a/crates/tools/src/contour.rs +++ b/crates/tools/src/contour.rs @@ -51,6 +51,22 @@ fn contour_offset(n: &Node) -> Option { Some(e.params.get("offset").and_then(Value::as_f64).unwrap_or(0.0)) } +/// The corner style and miter limit of a Contour's Offset Path effect, as `object.contour` takes +/// them. +fn contour_style(n: &Node) -> Option { + let e = n.appearance.effects.iter().rev().find(|e| e.id == EFFECT)?; + let corners = match e.params.get("joins").and_then(Value::as_str) { + Some("round") => "round", + Some("bevel") => "square", + _ => "sharp", + }; + let mut style = json!({ "corners": corners }); + if let Some(m) = e.params.get("miterLimit").and_then(Value::as_f64) { + style["miterLimit"] = json!(m); + } + Some(style) +} + /// How far `p` is from the nearest of `bases`' edges: positive outside, negative inside. fn signed_distance(bases: &[Base], p: Point) -> Option { let mut nearest = f64::INFINITY; @@ -69,6 +85,9 @@ struct Drag { pressed_at: f64, /// The Contour's distance at the press (0 for a shape that is not one yet). start: f64, + /// The corner style and miter limit every preview carries: the pressed Contour's own, else the + /// tool's options. + style: Value, /// The distance last previewed. last: Option, /// Where the pointer is, for the distance label. @@ -108,8 +127,9 @@ impl Corners { } impl ContourTool { - fn params(&self, offset: f64) -> Value { - let mut p = json!({"offset": offset, "corners": self.corners.id()}); + /// The corner style and miter limit of a new Contour: the tool's options. + fn style(&self) -> Value { + let mut p = json!({ "corners": self.corners.id() }); if let Some(m) = self.miter_limit { p["miterLimit"] = json!(m); } @@ -142,21 +162,25 @@ impl Tool for ContourTool { PointerKind::Down => { let shapes = selected_shapes(cx); let start = shapes.first().and_then(|n| contour_offset(n)).unwrap_or(0.0); + // A Contour keeps its own corners; a new one takes the tool's. + let style = shapes.first().and_then(|n| contour_style(n)).unwrap_or_else(|| self.style()); let bases: Vec = shapes.into_iter().filter_map(base_of).collect(); let Some(pressed_at) = signed_distance(&bases, ev.pos) else { return vec![] }; - self.drag = Some(Drag { bases, pressed_at, start, last: None, pos: ev.pos }); + self.drag = Some(Drag { bases, pressed_at, start, style, last: None, pos: ev.pos }); vec![Action::Begin("Contour".into())] } PointerKind::Drag => { - let mut params = self.params(0.0); let Some(drag) = self.drag.as_mut() else { return vec![] }; drag.pos = ev.pos; let Some(now) = signed_distance(&drag.bases, ev.pos) else { return vec![] }; let offset = round_distance(drag.start + now - drag.pressed_at, ev.mods); - if !offset.is_finite() || drag.last == Some(offset) { + // Nothing is previewed until the distance has left where it started: a drag along + // the edge (or one Shift rounds back) would otherwise leave an unchanged copy. + if !offset.is_finite() || drag.last == Some(offset) || (drag.last.is_none() && offset == drag.start) { return vec![]; } drag.last = Some(offset); + let mut params = drag.style.clone(); params["offset"] = json!(offset); vec![Action::Preview("object.contour".into(), params)] } From db1ef1bfed8ee401c1ef721d36dfb93529997f82 Mon Sep 17 00:00:00 2001 From: Kindmark <39938776+Kindmark@users.noreply.github.com> Date: Wed, 4 Nov 2026 22:41:32 -0600 Subject: [PATCH 041/196] Contour: make it a built-in add-on and translate its labels Review of #5694 asked for two changes. Add-on, not a core tool, as Enclosing Lasso is: - The command is addon.contour.set, in an add-on module of its own (crates/engine/src/cmd/addons/contour.rs) with its tests beside it. - The tool is listed under Object > Plug-ins > Contour and under its own "Contour" heading in All Tools. It has no Basic or Advanced toolbar slot and no default shortcut. The Contour bar is unchanged. - The add-on drawer test lists Contour with the other add-on tools. - Docs (mcp.md, the parity documents, ROADMAP) say add-on and use the new command name; mcp.md gains a Contour add-on section. Translations: rows for "Contour", "Contour Tool", "Sharp", "Bake" and "Turn the Contour into plain paths" in all 26 catalogs ("Round" and "Square" already had them). Drafted from each catalog's own vocabulary (for Bake, the verb it uses for Expand Appearance; a word other than the catalog's Stroke or Path word for the tool's name where they collide); they are not native-speaker reviewed. Co-Authored-By: Claude Sonnet 5.5 --- ROADMAP.md | 4 +-- crates/engine/src/cmd.rs | 2 -- crates/engine/src/cmd/addons.rs | 2 ++ crates/engine/src/cmd/{ => addons}/contour.rs | 15 ++++++---- .../addons/contour/tests.rs} | 28 +++++++++---------- crates/engine/src/tests.rs | 1 - crates/tools/src/addons.rs | 10 +++++-- crates/tools/src/{ => addons}/contour.rs | 20 ++++++------- crates/tools/src/catalog.rs | 1 - crates/tools/src/lib.rs | 2 -- crates/ui-egui/src/addons.rs | 2 ++ crates/ui-egui/src/addons/contour.rs | 12 ++++++++ crates/ui-egui/src/canvas/contour_bar.rs | 6 ++-- crates/ui-egui/src/canvas/tests.rs | 2 +- crates/ui-egui/src/edit_toolbar.rs | 2 +- crates/ui-egui/src/edit_toolbar/tests.rs | 17 +++++++++-- 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/toolbar.rs | 1 - docs/gaps.md | 3 +- docs/mcp.md | 21 ++++++++++++++ docs/target-app-parity.md | 5 ++-- docs/ui-parity.md | 3 +- 47 files changed, 288 insertions(+), 53 deletions(-) rename crates/engine/src/cmd/{ => addons}/contour.rs (89%) rename crates/engine/src/{tests/contour.rs => cmd/addons/contour/tests.rs} (92%) rename crates/tools/src/{ => addons}/contour.rs (94%) create mode 100644 crates/ui-egui/src/addons/contour.rs diff --git a/ROADMAP.md b/ROADMAP.md index e7000874f5..4115c31c2b 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,6 +1,6 @@ # VectorCraft Roadmap -- Contour tool (beyond Illustrator): drag a selected shape's edge outward or inward for a live, editable offset copy, with a floating bar for distance and Sharp, Round or Square corners; Bake turns it into paths. Scores and estimates unchanged. +- Contour add-on (beyond Illustrator): drag a selected shape's edge outward or inward for a live, editable offset copy, with a floating bar for distance and Sharp, Round or Square corners; Bake turns it into paths. Scores and estimates unchanged. - Paint: new gradients use the document's color model for default stops, including Gradient tool creation. Scores and estimates unchanged. @@ -13,7 +13,7 @@ **Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Contour tool, beyond Illustrator; scores and estimates unchanged; 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-05 · **Change:** minor (Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index e59331691f..b1b9efd60b 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -12,7 +12,6 @@ mod colorcmds; pub mod colormgmt; pub mod colortheme; mod compoundshape; -pub(crate) mod contour; pub(crate) mod create; mod css; mod cut; @@ -263,7 +262,6 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(xform::specs()); v.extend(effectcmd::specs()); v.extend(pathops::specs()); - v.extend(contour::specs()); v.extend(compoundshape::specs()); v.extend(typecmd::specs()); v.extend(menucmds::specs()); diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index ac9597cbd8..15ba1dad45 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -4,6 +4,7 @@ mod arrange; mod cleanup; mod color; +mod contour; mod document; mod pathtools; mod pen; @@ -17,6 +18,7 @@ pub fn specs() -> Vec { let mut v = arrange::specs(); v.extend(cleanup::specs()); v.extend(color::specs()); + v.extend(contour::specs()); v.extend(document::specs()); v.extend(pathtools::specs()); v.extend(pen::specs()); diff --git a/crates/engine/src/cmd/contour.rs b/crates/engine/src/cmd/addons/contour.rs similarity index 89% rename from crates/engine/src/cmd/contour.rs rename to crates/engine/src/cmd/addons/contour.rs index 5bbf5652bb..46df381edc 100644 --- a/crates/engine/src/cmd/contour.rs +++ b/crates/engine/src/cmd/addons/contour.rs @@ -1,18 +1,21 @@ -//! `object.contour`: the Contour tool's command. A Contour is a copy of a selected shape that +//! Contour (`addon.contour.*`), a built-in add-on: the Contour tool's command. A Contour is a copy of a selected shape that //! carries a live Offset Path effect, so it grows or shrinks the shape without baking anything: its //! fill, stroke and effect stay editable, and Expand Appearance bakes it into plain paths. The //! original stays where it is. Running the command on an object that already carries an Offset //! Path effect (a Contour made earlier) changes that effect instead of nesting another one. +#[cfg(test)] +mod tests; + use serde_json::{Value, json}; use vectorcraft_doc::NodeKind; use vectorcraft_render::effects; -use super::edit::{copy_above, selected_roots}; -use super::pathops::{len_param, num_param}; -use super::{CommandSpec, EngineError, NodeId, Result, Session, bad, cmd, has_selection, str_param}; +use super::super::edit::{copy_above, selected_roots}; +use super::super::pathops::{len_param, num_param}; +use super::super::{CommandSpec, EngineError, NodeId, Result, Session, bad, cmd, has_selection, str_param}; -const C: &str = "object.contour"; +const C: &str = "addon.contour.set"; /// The live effect that does the offsetting (the one Effect › Path › Offset Path applies). const EFFECT: &str = "path.offsetPath"; /// The largest offset, in points; Offset Path takes the same. @@ -20,7 +23,7 @@ const MAX_OFFSET: f64 = 1e5; pub fn specs() -> Vec { vec![cmd!( - "object.contour", + "addon.contour.set", "Contour", [], None, diff --git a/crates/engine/src/tests/contour.rs b/crates/engine/src/cmd/addons/contour/tests.rs similarity index 92% rename from crates/engine/src/tests/contour.rs rename to crates/engine/src/cmd/addons/contour/tests.rs index 164370c757..900d110d58 100644 --- a/crates/engine/src/tests/contour.rs +++ b/crates/engine/src/cmd/addons/contour/tests.rs @@ -1,4 +1,4 @@ -//! Tests for `object.contour`: a live Offset Path copy of a shape that stays editable until baked. +//! Tests for `addon.contour.set`: a live Offset Path copy of a shape that stays editable until baked. use serde_json::{Value, json}; use vectorcraft_doc::NodeKind; @@ -46,7 +46,7 @@ fn contour_is_a_live_copy_above_the_original() { let mut s = session(); let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0); let before = bounds(&s, a); - let r = s.execute("object.contour", &json!({"offset": 10})).unwrap(); + let r = s.execute("addon.contour.set", &json!({"offset": 10})).unwrap(); let (made, updated) = (ids_of(&r, "created"), ids_of(&r, "updated")); assert_eq!((made.len(), updated.len()), (1, 0)); // The original is untouched, the copy is above it and selected, and nothing is baked: the @@ -70,7 +70,7 @@ fn baking_a_contour_gives_the_grown_and_the_shrunk_shape() { let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0); for (offset, want) in [(10.0, Rect::new(90.0, 90.0, 160.0, 150.0)), (-5.0, Rect::new(105.0, 105.0, 145.0, 135.0))] { select(&mut s, &[a]); - s.execute("object.contour", &json!({"offset": offset})).unwrap(); + s.execute("addon.contour.set", &json!({"offset": offset})).unwrap(); let baked = ids_of(&s.execute("effect.expandAppearance", &json!({})).unwrap(), "ids"); let b = bounds(&s, baked[0]); // The default stroke widens the baked art by its weight; compare the fill's edges. @@ -92,10 +92,10 @@ fn baked_fill_bounds(s: &Session, id: NodeId) -> Rect { fn a_second_drag_changes_the_contour_instead_of_nesting_one() { let mut s = session(); let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0); - let made = ids_of(&s.execute("object.contour", &json!({"offset": 10})).unwrap(), "created"); + let made = ids_of(&s.execute("addon.contour.set", &json!({"offset": 10})).unwrap(), "created"); let count = node_count(&s); // The Contour is selected: the next call edits it. - let r = s.execute("object.contour", &json!({"offset": -4, "corners": "round"})).unwrap(); + let r = s.execute("addon.contour.set", &json!({"offset": -4, "corners": "round"})).unwrap(); assert_eq!(ids_of(&r, "updated"), made); assert!(ids_of(&r, "created").is_empty()); assert_eq!(node_count(&s), count, "no new object"); @@ -110,7 +110,7 @@ fn corner_styles_choose_the_join() { for (corners, joins) in [("sharp", "miter"), ("round", "round"), ("square", "bevel"), ("Round", "round")] { let mut s = session(); rect(&mut s, 0.0, 0.0, 30.0, 30.0); - let made = ids_of(&s.execute("object.contour", &json!({"offset": 3, "corners": corners})).unwrap(), "created"); + let made = ids_of(&s.execute("addon.contour.set", &json!({"offset": 3, "corners": corners})).unwrap(), "created"); assert_eq!(effects_of(&s, made[0])[0].1["joins"], json!(joins), "{corners}"); } } @@ -119,7 +119,7 @@ fn corner_styles_choose_the_join() { fn contour_keeps_the_color_and_stroke_editable_on_the_copy() { let mut s = session(); let a = rect(&mut s, 0.0, 0.0, 30.0, 30.0); - let made = ids_of(&s.execute("object.contour", &json!({"offset": 6})).unwrap(), "created"); + let made = ids_of(&s.execute("addon.contour.set", &json!({"offset": 6})).unwrap(), "created"); let original = node(&s, a).appearance.items.clone(); assert_eq!(node(&s, made[0]).appearance.items, original, "the copy starts with the shape's own paint"); // Recolouring the Contour (it is the selection) changes its fill only: the live effect stays @@ -135,7 +135,7 @@ fn contour_is_one_undo_step() { let mut s = session(); let a = rect(&mut s, 0.0, 0.0, 30.0, 30.0); let count = node_count(&s); - s.execute("object.contour", &json!({"offset": 6})).unwrap(); + s.execute("addon.contour.set", &json!({"offset": 6})).unwrap(); assert_eq!(node_count(&s), count + 1); s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(node_count(&s), count); @@ -148,13 +148,13 @@ fn contour_refuses_what_it_cannot_offset() { rect(&mut s, 0.0, 0.0, 30.0, 30.0); let count = node_count(&s); for params in [json!({}), json!({"offset": "abc"}), json!({"offset": 1e300}), json!({"offset": 5, "corners": "pointy"})] { - assert!(s.execute("object.contour", ¶ms).is_err(), "{params}"); + assert!(s.execute("addon.contour.set", ¶ms).is_err(), "{params}"); } // Nothing was added by the refused calls. assert_eq!(node_count(&s), count); // Type is not a path to offset. s.execute("text.create", &json!({"x": 10, "y": 10, "text": "Hi"})).unwrap(); - let err = s.execute("object.contour", &json!({"offset": 5})).unwrap_err().to_string(); + let err = s.execute("addon.contour.set", &json!({"offset": 5})).unwrap_err().to_string(); assert!(err.contains("select paths or shapes"), "{err}"); } @@ -169,9 +169,9 @@ fn border_with_a_gap_from_two_contours_and_minus_front() { // The gap first (+8), then the border (+20) from the same shape: both land directly above it, // the later one lower, so the gap ends up in front of the border. select(&mut s, &[a]); - let gap = ids_of(&s.execute("object.contour", &json!({"offset": 8})).unwrap(), "created")[0]; + let gap = ids_of(&s.execute("addon.contour.set", &json!({"offset": 8})).unwrap(), "created")[0]; select(&mut s, &[a]); - let border = ids_of(&s.execute("object.contour", &json!({"offset": 20})).unwrap(), "created")[0]; + let border = ids_of(&s.execute("addon.contour.set", &json!({"offset": 20})).unwrap(), "created")[0]; let d = &s.doc().unwrap().doc; assert!(d.index_path(gap).unwrap() > d.index_path(border).unwrap(), "the gap is in front of the border"); select(&mut s, &[border, gap]); @@ -239,7 +239,7 @@ mod tool { assert!(!s.in_interaction()); assert_eq!(undo_depth(&s), before + 1); assert_eq!(node_count(&s), nodes + 1); - assert_eq!(s.journal.last().map(|j| j.0.as_str()), Some("object.contour")); + assert_eq!(s.journal.last().map(|j| j.0.as_str()), Some("addon.contour.set")); let made = s.doc().unwrap().selection.objects.clone(); assert_eq!(made.len(), 1); assert_ne!(made[0], a); @@ -304,7 +304,7 @@ mod tool { #[test] fn dragging_a_contour_again_keeps_its_corners_and_miter_limit() { let (mut s, _) = ready(); - s.execute("object.contour", &json!({"offset": 5, "corners": "square", "miterLimit": 7})).unwrap(); + s.execute("addon.contour.set", &json!({"offset": 5, "corners": "square", "miterLimit": 7})).unwrap(); let contour = s.doc().unwrap().selection.objects[0]; s.set_tool_option("corners", &json!("sharp")); at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default()); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e78d828dc0..9ec3ccaf98 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -36,7 +36,6 @@ mod compoundpaint; mod constrain_new; mod constrain_tools; mod containers; -mod contour; mod css; mod cut; mod dashalign; diff --git a/crates/tools/src/addons.rs b/crates/tools/src/addons.rs index 42643538ed..69bb4858a4 100644 --- a/crates/tools/src/addons.rs +++ b/crates/tools/src/addons.rs @@ -3,6 +3,7 @@ //! submenu selects them. Tool gestures emit engine commands. pub mod anchor_eraser; +pub mod contour; pub mod corner_tool; pub mod enclosing_lasso; pub mod extend_path; @@ -28,14 +29,17 @@ pub const PATH_TOOLS: &[ToolInfo] = &[ /// Smart Pen's tool, a flyout group of its own. pub const SMART_PEN: &[ToolInfo] = &[ToolInfo { id: smart_pen::ID, label: "Smart Pen Tool", shortcut: None, icon: "spline-pointer" }]; +pub const CONTOUR: &[ToolInfo] = &[ToolInfo { id: contour::ID, label: "Contour Tool", shortcut: None, icon: "tool-contour" }]; + pub const ENCLOSING_LASSO: &[ToolInfo] = &[ToolInfo { id: enclosing_lasso::ID, label: "Enclosing Lasso Tool", shortcut: None, icon: "tool-lasso" }]; /// The add-ons' tool groups, after the toolbar's own ([`crate::TOOL_GROUPS`]), each with the /// heading the All Tools drawer lists it under (its add-on's name). -const HEADED: &[(&[ToolInfo], &str)] = &[(PATH_TOOLS, "Path Precision Tools"), (SMART_PEN, "Smart Pen"), (ENCLOSING_LASSO, "Enclosing Lasso")]; +const HEADED: &[(&[ToolInfo], &str)] = + &[(PATH_TOOLS, "Path Precision Tools"), (SMART_PEN, "Smart Pen"), (ENCLOSING_LASSO, "Enclosing Lasso"), (CONTOUR, "Contour")]; /// The add-ons' tool groups, after the toolbar's own ([`crate::TOOL_GROUPS`]). -pub const GROUPS: &[&[ToolInfo]] = &[PATH_TOOLS, SMART_PEN, ENCLOSING_LASSO]; +pub const GROUPS: &[&[ToolInfo]] = &[PATH_TOOLS, SMART_PEN, ENCLOSING_LASSO, CONTOUR]; /// The heading the All Tools drawer lists tool `id` under: its add-on's name. pub fn heading(id: &str) -> Option<&'static str> { @@ -54,6 +58,7 @@ pub fn create(id: &str) -> Option> { slide_anchor::ID => Box::new(slide_anchor::SlideAnchorTool::default()), smart_pen::ID => Box::new(smart_pen::SmartPenTool::default()), enclosing_lasso::ID => Box::new(enclosing_lasso::EnclosingLassoTool::default()), + contour::ID => Box::new(contour::ContourTool::default()), _ => return None, }) } @@ -74,6 +79,7 @@ mod tests { assert!(PATH_TOOLS.iter().all(|t| heading(t.id) == Some("Path Precision Tools"))); assert_eq!(heading(smart_pen::ID), Some("Smart Pen")); assert_eq!(heading(enclosing_lasso::ID), Some("Enclosing Lasso")); + assert_eq!(heading(contour::ID), Some("Contour")); assert_eq!(GROUPS.len(), HEADED.len()); assert!(crate::catalog::all_tools().any(|t| t.id == extend_path::ID)); assert!(create("pen").is_none() && heading("pen").is_none()); diff --git a/crates/tools/src/contour.rs b/crates/tools/src/addons/contour.rs similarity index 94% rename from crates/tools/src/contour.rs rename to crates/tools/src/addons/contour.rs index cf450752c6..e77bb29eed 100644 --- a/crates/tools/src/contour.rs +++ b/crates/tools/src/addons/contour.rs @@ -1,5 +1,5 @@ //! The Contour tool: drag away from a selected shape's edge to grow a live copy of it, or toward the -//! inside to shrink it (`object.contour`). The copy is the original's outline offset by the distance +//! inside to shrink it (`addon.contour.set`). The copy is the original's outline offset by the distance //! the pointer has moved from the edge, previewed while the button is down and kept as one undo step //! on release. Nothing is baked: the copy carries a live Offset Path effect, so it keeps being //! editable (a second drag on a selected Contour changes its distance instead of nesting another), @@ -16,9 +16,12 @@ use vectorcraft_geom::{BezPath, FillRule, Point, hit}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; -/// The live effect a Contour is made of (the one `object.contour` applies). +/// The tool's id. +pub const ID: &str = "contour"; + +/// The live effect a Contour is made of (the one `addon.contour.set` applies). const EFFECT: &str = "path.offsetPath"; -/// The largest distance, in points, `object.contour` accepts. +/// The largest distance, in points, `addon.contour.set` accepts. const MAX_OFFSET: f64 = 1e5; /// The guide showing the shape a Contour was made from. const GUIDE: [u8; 3] = [0x1e, 0x88, 0xe5]; @@ -51,7 +54,7 @@ fn contour_offset(n: &Node) -> Option { Some(e.params.get("offset").and_then(Value::as_f64).unwrap_or(0.0)) } -/// The corner style and miter limit of a Contour's Offset Path effect, as `object.contour` takes +/// The corner style and miter limit of a Contour's Offset Path effect, as `addon.contour.set` takes /// them. fn contour_style(n: &Node) -> Option { let e = n.appearance.effects.iter().rev().find(|e| e.id == EFFECT)?; @@ -154,7 +157,7 @@ fn round_distance(v: f64, mods: Mods) -> f64 { impl Tool for ContourTool { fn id(&self) -> &'static str { - "contour" + ID } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { @@ -182,7 +185,7 @@ impl Tool for ContourTool { drag.last = Some(offset); let mut params = drag.style.clone(); params["offset"] = json!(offset); - vec![Action::Preview("object.contour".into(), params)] + vec![Action::Preview("addon.contour.set".into(), params)] } PointerKind::Up => match self.drag.take() { Some(d) if d.last.is_some() => vec![Action::Commit], @@ -249,8 +252,3 @@ impl Tool for ContourTool { self.drag.is_some() } } - -/// The Contour tool, for [`crate::create`]. -pub fn create(id: &str) -> Option> { - (id == "contour").then(|| Box::new(ContourTool::default()) as Box) -} diff --git a/crates/tools/src/catalog.rs b/crates/tools/src/catalog.rs index 49fe557ea9..9bbd7cbdfb 100644 --- a/crates/tools/src/catalog.rs +++ b/crates/tools/src/catalog.rs @@ -94,7 +94,6 @@ pub const TOOL_GROUPS: &[&[ToolInfo]] = &[ t("livePaintBucket", "Live Paint Bucket", Some("K"), "tool-bucket"), t("livePaintSelection", "Live Paint Selection Tool", Some("Shift+L"), "tool-live-select"), ], - &[t("contour", "Contour Tool", None, "tool-contour")], &[ t("perspectiveGrid", "Perspective Grid Tool", Some("Shift+P"), "tool-perspective"), t("perspectiveSelection", "Perspective Selection Tool", Some("Shift+V"), "tool-perspective-select"), diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index d14e43c675..ee00fdbe97 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -11,7 +11,6 @@ pub mod addons; pub mod bbox; pub mod builder; pub mod catalog; -pub mod contour; pub mod corners; pub mod cropimage; pub mod cut; @@ -297,7 +296,6 @@ pub fn create(id: &str) -> Box { .or_else(|| printtiling::create(other)) .or_else(|| cropimage::create(other)) .or_else(|| cut::create(other)) - .or_else(|| contour::create(other)) .or_else(|| intertwine::create(other)) .or_else(|| objects_on_path::create(other)) .or_else(|| touchtype::create(other)) diff --git a/crates/ui-egui/src/addons.rs b/crates/ui-egui/src/addons.rs index d9c86240ad..f0238aee23 100644 --- a/crates/ui-egui/src/addons.rs +++ b/crates/ui-egui/src/addons.rs @@ -3,6 +3,7 @@ pub mod arrange; pub mod cleanup; pub mod color; +pub mod contour; pub mod document; pub mod enclosing_lasso; pub mod pathtools; @@ -18,6 +19,7 @@ pub fn plugin_menu() -> Vec { Item::Sub("Arrange Tools", arrange::menu()), Item::Sub("Artwork Cleanup", cleanup::menu()), Item::Sub("Color Effects", color::menu()), + Item::Sub("Contour", contour::menu()), Item::Sub("Document Tools", document::menu()), Item::Sub("Enclosing Lasso", enclosing_lasso::menu()), Item::Sub("Path Precision Tools", pathtools::menu()), diff --git a/crates/ui-egui/src/addons/contour.rs b/crates/ui-egui/src/addons/contour.rs new file mode 100644 index 0000000000..084a8b98c1 --- /dev/null +++ b/crates/ui-egui/src/addons/contour.rs @@ -0,0 +1,12 @@ +//! The Contour add-on in the interface: its submenu (Object › Plug-ins › Contour), which selects the +//! Contour tool. The Contour bar (`canvas/contour_bar.rs`) shows over the selection while the tool is +//! active. Everything acts through `addon.contour.set` and Expand Appearance. + +use serde_json::json; +use vectorcraft_tools::addons::contour; + +use crate::menus::Item; + +pub fn menu() -> Vec { + vec![Item::Cmd("Contour Tool", "tool.select", json!({"tool": contour::ID}))] +} diff --git a/crates/ui-egui/src/canvas/contour_bar.rs b/crates/ui-egui/src/canvas/contour_bar.rs index 443fdc2aa9..4b560eeba6 100644 --- a/crates/ui-egui/src/canvas/contour_bar.rs +++ b/crates/ui-egui/src/canvas/contour_bar.rs @@ -1,6 +1,6 @@ //! The Contour bar: a floating bar above the selection while the Contour tool is active. It has the //! Contour's distance in a number box, its corner style (Sharp, Round or Square) and Bake, which -//! turns the live Contour into plain paths. It acts through `object.contour` and +//! turns the live Contour into plain paths. It acts through `addon.contour.set` and //! `effect.expandAppearance`, so everything it does is a command with its own undo step. use serde_json::Value; @@ -98,7 +98,7 @@ pub(super) fn contour_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { if resp.drag_stopped() || resp.lost_focus() { ui.data_mut(|d| d.remove_temp::(key)); if (v - shown).abs() > 1e-9 { - run = Some(("object.contour", json!({"offset": v, "corners": corners}))); + run = Some(("addon.contour.set", json!({"offset": v, "corners": corners}))); } } for (label, id) in [(tl!("Sharp"), "sharp"), (tl!("Round"), "round"), (tl!("Square"), "square")] { @@ -119,7 +119,7 @@ pub(super) fn contour_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { if result.is_ok() && let Some(s) = &stand { - result = app.run("object.contour", json!({"offset": s.offset, "corners": id})); + result = app.run("addon.contour.set", json!({"offset": s.offset, "corners": id})); } if let Err(e) = result { app.ui.status = e; diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index da52ed353f..3f6f9f0ff6 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -9053,7 +9053,7 @@ fn the_contour_bar_sets_corners_and_bakes() { assert!(offsets(&app).is_empty()); // A Contour made now has round corners; Square changes the selected Contour in place. - app.session.execute("object.contour", &json!({"offset": 8, "corners": "round"})).unwrap(); + app.session.execute("addon.contour.set", &json!({"offset": 8, "corners": "round"})).unwrap(); assert_eq!(offsets(&app), ["round"]); click_contour_bar(&mut app, &ctx, "Square"); assert_eq!(offsets(&app), ["bevel"], "the selected Contour changed, none was added"); diff --git a/crates/ui-egui/src/edit_toolbar.rs b/crates/ui-egui/src/edit_toolbar.rs index dcec1ffc5b..eb79cf3570 100644 --- a/crates/ui-egui/src/edit_toolbar.rs +++ b/crates/ui-egui/src/edit_toolbar.rs @@ -410,7 +410,7 @@ fn heading(id: &str) -> &'static str { _ if id.starts_with("perspective") => "Perspective", "artboard" => "Artboards", "slice" | "sliceSelection" => "Slices", - "objectsOnPath" | "contour" => "Modify", + "objectsOnPath" => "Modify", _ => "More", } } diff --git a/crates/ui-egui/src/edit_toolbar/tests.rs b/crates/ui-egui/src/edit_toolbar/tests.rs index 85309507f8..c474cea581 100644 --- a/crates/ui-egui/src/edit_toolbar/tests.rs +++ b/crates/ui-egui/src/edit_toolbar/tests.rs @@ -529,10 +529,22 @@ fn drop_targets_follow_the_buttons_edges() { fn addon_tools_are_in_the_drawer_not_the_toolbars() { let mut app = app(); let enclosing = vectorcraft_tools::addons::enclosing_lasso::ID; + let contour = vectorcraft_tools::addons::contour::ID; let addon: Vec<&str> = vectorcraft_tools::addons::GROUPS.iter().flat_map(|g| g.iter().map(|t| t.id)).collect(); assert_eq!( addon, - ["anchorEraserBrush", "extendPath", "measureInspect", "parametricShape", "cornerTool", "slideAnchor", "sharedEdge", "smartPen", enclosing] + [ + "anchorEraserBrush", + "extendPath", + "measureInspect", + "parametricShape", + "cornerTool", + "slideAnchor", + "sharedEdge", + "smartPen", + enclosing, + contour + ] ); for advanced in [false, true] { if advanced { @@ -546,7 +558,8 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() { assert_eq!(listed("extendPath"), Some(("Path Precision Tools", addon[..7].to_vec()))); assert_eq!(listed("smartPen"), Some(("Smart Pen", vec!["smartPen"]))); assert_eq!(listed(enclosing), Some(("Enclosing Lasso", vec![enclosing]))); - for tool in ["extendPath", "smartPen", enclosing] { + assert_eq!(listed(contour), Some(("Contour", vec![contour]))); + for tool in ["extendPath", "smartPen", enclosing, contour] { app.run("toolbar.addTool", json!({"tool": tool})).unwrap(); assert!(slot_of(&app, tool).is_some(), "{tool}"); } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index ee25d5057e..96735ce205 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6201,6 +6201,13 @@ breakText Glyphs Глифи Fully Outside Изцяло извън No artboards match. Няма съвпадащи работни области. Chosen: {n} of {total} Избрани: {n} от {total} + +# Contour add-on + Contour Очертание + Contour Tool Инструмент „Очертание“ + Sharp Заостряне + Bake Разшири + Turn the Contour into plain paths Превръща очертанието в обикновени пътища Set Corners… Задаване на ъгли… All Anchors Всички опорни точки Odd-Numbered Anchors Нечетни опорни точки diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 1f4ea2422b..ad78ee84e0 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6236,6 +6236,13 @@ shape Open Otvoren Fully Outside Potpuno vani No artboards match. Nijedna radna ploča ne odgovara. Chosen: {n} of {total} Odabrano: {n} od {total} + +# Contour add-on + Contour Kontura + Contour Tool Alat kontura + Sharp Oštro + Bake Proširi + Turn the Contour into plain paths Pretvori konturu u obične putanje Set Corners… Postavi uglove… All Anchors Sva sidra Odd-Numbered Anchors Neparna sidra diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 70c893f326..8ad31d6d0a 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6337,6 +6337,13 @@ breakText Glyphs Glifs Fully Outside Totalment fora No artboards match. Cap tauler no coincideix. Chosen: {n} of {total} Triats: {n} de {total} + +# Contour add-on + Contour Contorn + Contour Tool Eina de contorn + Sharp Punxegut + Bake Expandeix + Turn the Contour into plain paths Converteix el contorn en traçats simples Set Corners… Defineix les cantonades… All Anchors Tots els ancoratges Odd-Numbered Anchors Ancoratges senars diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index cac60a6482..d801c39fdc 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6351,6 +6351,13 @@ breakText Glyphs Glyfy Fully Outside Zcela vně No artboards match. Žádná pracovní plocha neodpovídá. Chosen: {n} of {total} Zvoleno: {n} z {total} + +# Contour add-on + Contour Obrys + Contour Tool Nástroj Obrys + Sharp Ostrý + Bake Rozložit + Turn the Contour into plain paths Převést obrys na běžné cesty Set Corners… Nastavit rohy… All Anchors Všechny kotevní body Odd-Numbered Anchors Liché kotevní body diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 623e700387..e410c8e4ac 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6217,6 +6217,13 @@ breakText Glyphs Glyffer Fully Outside Helt udenfor No artboards match. Ingen tegneflader passer. Chosen: {n} of {total} Valgt: {n} af {total} + +# Contour add-on + Contour Kontur + Contour Tool Kontur-værktøj + Sharp Spids + Bake Udvid + Turn the Contour into plain paths Gør konturen til almindelige stier Set Corners… Angiv hjørner… All Anchors Alle ankre Odd-Numbered Anchors Ulige ankre diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index fea15fbe24..e11cf1bac8 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5937,6 +5937,13 @@ breakText Glyphs Glyphen Fully Outside Vollständig außen No artboards match. Keine Zeichenfläche passt. Chosen: {n} of {total} Gewählt: {n} von {total} + +# Contour add-on + Contour Umriss + Contour Tool Umriss-Werkzeug + Sharp Spitz + Bake Umwandeln + Turn the Contour into plain paths Wandelt den Umriss in einfache Pfade um Set Corners… Ecken festlegen… All Anchors Alle Ankerpunkte Odd-Numbered Anchors Ungerade Ankerpunkte diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 72684a9c6c..9f3d0c18e1 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6303,6 +6303,13 @@ breakText Glyphs Γλύφοι Fully Outside Πλήρως εκτός No artboards match. Κανένας πίνακας σχεδίασης δεν ταιριάζει. Chosen: {n} of {total} Επιλεγμένοι: {n} από {total} + +# Contour add-on + Contour Παράλληλο περίγραμμα + Contour Tool Εργαλείο παράλληλου περιγράμματος + Sharp Οξεία + Bake Επέκταση + Turn the Contour into plain paths Μετατρέπει το παράλληλο περίγραμμα σε απλές διαδρομές Set Corners… Ορισμός γωνιών… All Anchors Όλα τα σημεία αγκύρωσης Odd-Numbered Anchors Μονά σημεία αγκύρωσης diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index caf2b7b054..b02abb8f1e 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6293,6 +6293,13 @@ breakText Glyphs Glifos Fully Outside Totalmente fuera No artboards match. Ninguna mesa de trabajo coincide. Chosen: {n} of {total} Elegidas: {n} de {total} + +# Contour add-on + Contour Contorno + Contour Tool Herramienta Contorno + Sharp Puntiaguda + Bake Expandir + Turn the Contour into plain paths Convierte el contorno en trazados simples Set Corners… Definir esquinas… All Anchors Todas las anclas Odd-Numbered Anchors Anclas impares diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 73a7465a8c..eebd34d89e 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6386,6 +6386,13 @@ breakText Glyphs Merkit Fully Outside Kokonaan ulkona No artboards match. Mikään piirtoalusta ei vastaa hakua. Chosen: {n} of {total} Valittu: {n}/{total} + +# Contour add-on + Contour Ääriviiva + Contour Tool Ääriviivatyökalu + Sharp Terävä + Bake Laajenna + Turn the Contour into plain paths Muuntaa ääriviivan tavallisiksi poluiksi Set Corners… Aseta kulmat… All Anchors Kaikki ankkurit Odd-Numbered Anchors Parittomat ankkurit diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8aa5fa1e90..a5fbb1ab0a 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6346,6 +6346,13 @@ breakText Glyphs Glyphes Fully Outside Entièrement à l’extérieur No artboards match. Aucun plan de travail ne correspond. Chosen: {n} of {total} Choisis : {n} sur {total} + +# Contour add-on + Contour Pourtour + Contour Tool Outil Pourtour + Sharp Pointu + Bake Décomposer + Turn the Contour into plain paths Transforme le pourtour en tracés simples Set Corners… Définir les angles… All Anchors Tous les points d’ancrage Odd-Numbered Anchors Points d’ancrage impairs diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 2137addf13..3959b3fee5 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6335,6 +6335,13 @@ breakText Glyphs Glifák Fully Outside Teljesen kívül No artboards match. Nincs egyező rajztábla. Chosen: {n} of {total} Kiválasztva: {n} / {total} + +# Contour add-on + Contour Kontúr + Contour Tool Kontúr eszköz + Sharp Hegyes + Bake Kibontás + Turn the Contour into plain paths A kontúrt egyszerű útvonalakká alakítja Set Corners… Sarkok beállítása… All Anchors Összes horgonypont Odd-Numbered Anchors Páratlan horgonypontok diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c0c6489bf7..fd72bc7e62 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6217,6 +6217,13 @@ breakText Glyphs Glif Fully Outside Sepenuhnya di luar No artboards match. Tidak ada artboard yang cocok. Chosen: {n} of {total} Dipilih: {n} dari {total} + +# Contour add-on + Contour Kontur + Contour Tool Alat kontur + Sharp Tajam + Bake Perluas + Turn the Contour into plain paths Ubah kontur menjadi jalur biasa Set Corners… Atur sudut… All Anchors Semua jangkar Odd-Numbered Anchors Jangkar bernomor ganjil diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index d3add5036c..4f2035969e 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5971,6 +5971,13 @@ breakText Glyphs Glifi Fully Outside Completamente esterno No artboards match. Nessuna tavola da disegno corrisponde. Chosen: {n} of {total} Scelte: {n} di {total} + +# Contour add-on + Contour Contorno + Contour Tool Strumento Contorno + Sharp Appuntito + Bake Espandi + Turn the Contour into plain paths Trasforma il contorno in tracciati semplici Set Corners… Imposta angoli… All Anchors Tutti gli ancoraggi Odd-Numbered Anchors Ancoraggi dispari diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 3533338d7a..9f089ecf4b 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -6036,6 +6036,13 @@ breakText Glyphs 字形 Fully Outside 完全に外側 No artboards match. 一致するアートボードはありません。 Chosen: {n} of {total} 選択中: {n} / {total} + +# Contour add-on + Contour 輪郭 + Contour Tool 輪郭ツール + Sharp 鋭角 + Bake 分割 + Turn the Contour into plain paths 輪郭を通常のパスに変換します Set Corners… コーナーを設定… All Anchors すべてのアンカー Odd-Numbered Anchors 奇数番目のアンカー diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index cc96a111cb..78da64abc0 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6362,6 +6362,13 @@ font-script Japanese იაპონური Fully Outside მთლიანად გარეთ No artboards match. შესაბამისი სამუშაო დაფა არ არის. Chosen: {n} of {total} არჩეულია: {n} / {total} + +# Contour add-on + Contour მოხაზულობა + Contour Tool მოხაზულობის ხელსაწყო + Sharp მახვილი + Bake გაშლა + Turn the Contour into plain paths მოხაზულობას ჩვეულებრივ ტრაექტორიებად აქცევს Set Corners… კუთხეების დაყენება… All Anchors ყველა საყრდენი წერტილი Odd-Numbered Anchors კენტი საყრდენი წერტილები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 1ac6fdc758..3e99b509bc 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5932,6 +5932,13 @@ breakText Glyphs 글리프 Fully Outside 완전히 바깥쪽 No artboards match. 일치하는 아트보드가 없습니다. Chosen: {n} of {total} 선택됨: {n} / {total} + +# Contour add-on + Contour 윤곽 + Contour Tool 윤곽 도구 + Sharp 뾰족하게 + Bake 확장 + Turn the Contour into plain paths 윤곽을 일반 패스로 바꿉니다 Set Corners… 모퉁이 설정… All Anchors 모든 앵커 Odd-Numbered Anchors 홀수 번째 앵커 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 0a5943f822..7f7818c545 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6261,6 +6261,13 @@ breakText Glyphs Glyphs Fully Outside Volledig buiten No artboards match. Geen tekengebied komt overeen. Chosen: {n} of {total} Gekozen: {n} van {total} + +# Contour add-on + Contour Omtrek + Contour Tool Omtrek-gereedschap + Sharp Scherp + Bake Uitbreiden + Turn the Contour into plain paths Zet de omtrek om in gewone paden Set Corners… Hoeken instellen… All Anchors Alle ankerpunten Odd-Numbered Anchors Oneven ankerpunten diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index da7f069e60..56127f0525 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -6206,6 +6206,13 @@ breakText Glyphs Glify Fully Outside Całkowicie na zewnątrz No artboards match. Żaden obszar kompozycji nie pasuje. Chosen: {n} of {total} Wybrano: {n} z {total} + +# Contour add-on + Contour Kontur + Contour Tool Narzędzie Kontur + Sharp Ostry + Bake Rozszerz + Turn the Contour into plain paths Zamienia kontur w zwykłe ścieżki Set Corners… Ustaw narożniki… All Anchors Wszystkie punkty Odd-Numbered Anchors Punkty nieparzyste diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 4e05fc1eeb..7f68c5c7f6 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6424,6 +6424,13 @@ swatch Yellow Green Verde-amarelado Fully Outside Totalmente fora No artboards match. Nenhuma mesa de trabalho corresponde. Chosen: {n} of {total} Escolhidas: {n} de {total} + +# Contour add-on + Contour Contorno + Contour Tool Ferramenta Contorno + Sharp Pontiagudo + Bake Expandir + Turn the Contour into plain paths Transforma o contorno em caminhos simples Set Corners… Definir Cantos… All Anchors Todas as Âncoras Odd-Numbered Anchors Âncoras Ímpares diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 60dcc9e321..10426b2efd 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6440,6 +6440,13 @@ shape Open Открытый Fully Outside Полностью снаружи No artboards match. Нет подходящих монтажных областей. Chosen: {n} of {total} Выбрано: {n} из {total} + +# Contour add-on + Contour Эквидистанта + Contour Tool Инструмент «Эквидистанта» + Sharp Острый + Bake Разобрать + Turn the Contour into plain paths Преобразует эквидистанту в обычные контуры Set Corners… Задать углы… All Anchors Все опорные точки Odd-Numbered Anchors Нечётные опорные точки diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 7a26b4d02f..1d2d9b03e2 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6407,6 +6407,13 @@ digits Hindi Hindi Fully Outside Helt utanför No artboards match. Ingen rityta matchar. Chosen: {n} of {total} Valda: {n} av {total} + +# Contour add-on + Contour Kantlinje + Contour Tool Kantlinjeverktyg + Sharp Spetsig + Bake Expandera + Turn the Contour into plain paths Gör om kantlinjen till vanliga banor Set Corners… Ange hörn… All Anchors Alla ankare Odd-Numbered Anchors Udda ankare diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index f50913c3ed..133538fe9e 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6308,6 +6308,13 @@ breakText Glyphs Glifler Fully Outside Tamamen dışarıda No artboards match. Eşleşen çalışma yüzeyi yok. Chosen: {n} of {total} Seçilen: {n}/{total} + +# Contour add-on + Contour Dış Hat + Contour Tool Dış Hat Aracı + Sharp Keskin + Bake Genişlet + Turn the Contour into plain paths Dış hattı sade yollara dönüştürür Set Corners… Köşeleri Ayarla… All Anchors Tüm Çapalar Odd-Numbered Anchors Tek Numaralı Çapalar diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 35b806a1f4..95724a3d75 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5951,6 +5951,13 @@ breakText Glyphs Гліфи Fully Outside Повністю зовні No artboards match. Немає відповідних монтажних областей. Chosen: {n} of {total} Вибрано: {n} з {total} + +# Contour add-on + Contour Еквідистанта + Contour Tool Інструмент «Еквідистанта» + Sharp Гострий + Bake Розібрати + Turn the Contour into plain paths Перетворює еквідистанту на звичайні контури Set Corners… Задати кути… All Anchors Усі опорні точки Odd-Numbered Anchors Непарні опорні точки diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index bae63ccf83..93113bc392 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5952,6 +5952,13 @@ breakText Glyphs Glyph Fully Outside Hoàn toàn bên ngoài No artboards match. Không có bảng vẽ nào khớp. Chosen: {n} of {total} Đã chọn: {n} trên {total} + +# Contour add-on + Contour Đường viền + Contour Tool Công cụ Đường viền + Sharp Nhọn + Bake Mở rộng + Turn the Contour into plain paths Chuyển đường viền thành các đường dẫn thường Set Corners… Đặt góc… All Anchors Tất cả điểm neo Odd-Numbered Anchors Điểm neo số lẻ diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index c5004c3670..20ec647964 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -6192,6 +6192,13 @@ breakText Glyphs 字形 Fully Outside 完全在外 No artboards match. 没有匹配的画板。 Chosen: {n} of {total} 已选:{n} / {total} + +# Contour add-on + Contour 轮廓 + Contour Tool 轮廓工具 + Sharp 尖角 + Bake 扩展 + Turn the Contour into plain paths 将轮廓转为普通路径 Set Corners… 设置转角… All Anchors 所有锚点 Odd-Numbered Anchors 奇数锚点 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e42ab765b5..7dbb11507f 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5989,6 +5989,13 @@ breakText Glyphs 字符 Fully Outside 完全在外 No artboards match. 沒有符合的工作區域。 Chosen: {n} of {total} 已選:{n} / {total} + +# Contour add-on + Contour 輪廓 + Contour Tool 輪廓工具 + Sharp 尖角 + Bake 展開 + Turn the Contour into plain paths 將輪廓轉為一般路徑 Set Corners… 設定轉角… All Anchors 所有錨點 Odd-Numbered Anchors 奇數錨點 diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index fcb9a1cc9e..94054a0d46 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -59,7 +59,6 @@ pub const BASIC: &[(&str, &[&[&str]])] = &[ &["rotate", "reflect", "scale", "shear", "reshape", "freeTransform", "puppetWarp"], &["shapeBuilder", "livePaintBucket", "livePaintSelection", "blend"], &["dimension"], - &["contour"], ], ), ("Type", &[&["areaType", "typeOnPath", "verticalAreaType", "verticalTypeOnPath"], &["type", "verticalType", "touchType"]]), diff --git a/docs/gaps.md b/docs/gaps.md index 92ee96cb97..68d08df0b7 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Contour tool, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -28,6 +28,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | Contour add-on (beyond Illustrator): drag away from a selected shape's edge to grow a live copy of it, or toward the inside to shrink it; the copy carries a live Offset Path effect, so it stays editable until Bake (Expand Appearance), a second drag changes the same Contour instead of nesting one, and a floating bar sets the distance and the Sharp, Round or Square corners. `addon.contour.set` is the command behind it. It is a built-in add-on: Object › Plug-ins › Contour, and its own heading in All Tools, with no default shortcut or toolbar slot. A VectorCraft design built on Offset Path; no other application was inspected. Scores and estimates unchanged. | | 2026-11-04 | minor | Contour tool (beyond Illustrator): drag away from a selected shape's edge to grow a live copy of it, or toward the inside to shrink it; the copy carries a live Offset Path effect, so it stays editable until Bake (Expand Appearance), a second drag changes the same Contour instead of nesting one, and a floating bar sets the distance and the Sharp, Round or Square corners. `object.contour` is the command behind it. A VectorCraft design built on Offset Path; no other application was inspected. Scores and estimates unchanged. | | 2026-11-05 | minor | G12: Hyphenation › Default Language sets the language of new type unless Document Setup chose one, stored as a tag; each run hyphenates in its own language, English only so far, so 2 Preferences options stay unused (#394) | | 2026-11-03 | minor | New gradients use CMYK default stops in CMYK documents, including Gradient tool creation. Scores and estimates unchanged. | diff --git a/docs/mcp.md b/docs/mcp.md index 797ac023b5..8fd7a394aa 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6780,6 +6780,27 @@ The panel sets the next segment and runs Remove Points Keep Shape (`addon.pathto {"name":"run_command","arguments":{"command":"addon.pen.reshape","params":{"id":12,"segment":0,"t":0.3,"dx":0,"dy":-25}}} ``` +## Contour add-on + +Contour is a built-in add-on: it grows or shrinks a copy of a path or shape by a distance, live. Its command is +`addon.contour.set`; in the desktop app it lives in Object › Plug-ins › Contour and in the Contour Tool (`contour`), which +the toolbars don't show until it is added from the All Tools drawer (or chosen with `tool.select`); it has no shortcut. A +floating bar over the selection (the distance, Sharp / Round / Square and Bake) acts through the same commands. + +`addon.contour.set {offset, corners?, miterLimit?}` puts a copy of each selected path, shape or compound path directly above +it with a live Offset Path effect of `offset` points (negative insets), and selects the copies. `corners` is `"sharp"` +(default), `"round"` or `"square"` (corners cut off flat), `miterLimit` 1 to 500 (4; sharp corners). A selected object that +already has that effect (a Contour made earlier) has its effect changed instead of getting another, so the same call +adjusts a Contour. The original is kept, and nothing is baked: `effect.expandAppearance` turns a Contour into plain paths. +Type, images and groups are left alone; with nothing to offset it says "select paths or shapes". One undo step. Result: +`{ids, created, updated}`. + +The tool (`contour`) drags a distance from the selected shape's edge, outward to grow and inward to shrink: the press +changes nothing until the pointer moves, a Contour that already stands at a distance continues from it, Shift rounds to +whole points and Escape cancels. A drag keeps a Contour's own corners and miter limit; a new Contour takes the tool's +options `corners` and `miterLimit` (`tool.setOption`). A border with a gap is two Contours of one shape (the gap first, so +it ends up in front), baked with `effect.expandAppearance`, then `object.pathfinder.minusFront`. + ## Color Effects add-on Color Effects is a built-in add-on: its effects are colour adjustments in Effect › Color Effects, its command is diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 76c4c4ab2d..4b90d9967e 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-05 · **Change:** minor (Contour tool, beyond Illustrator; scores and estimates unchanged; Select by Artboards add-on selects by overlap, inside or outside several artboards; 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-05 · **Change:** minor (Contour add-on, beyond Illustrator; scores and estimates unchanged; Optical kerning spaces pairs by the font's own stem spacing instead of a fixed tight gap; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -482,7 +482,7 @@ since 2026-10-01. | **Agent automation** | beyond Illustrator | Every command, gesture and dialog is drivable over MCP, the CLI and the control channel; synthetic-input counts, pending events and per-frame control requests are bounded (#1709); what an agent reads and writes on disk can be confined to chosen folders (`--automation-read-root` / `--automation-write-root`, as in PhotoCraft, #832) | | **Scrubby numeric fields** | beyond Illustrator | As in Photoshop, dragging a numeric field's label (`W:`, `Opacity:`, the Character panel's icons) left or right steps its value live; one undo step per drag, Escape cancels (#400) | | **Align Stroke on live type** | beyond Illustrator | The Stroke panel's Align Stroke works on type's character stroke: inside or outside the glyphs without Create Outlines, the type staying editable (as InDesign does; users have asked Illustrator for it since 2010, e.g. [redd.it/1dwhos6](https://redd.it/1dwhos6)). Canvas, PDF and EPS clip it to its side of the glyphs; SVG keeps the text live and draws the stroke on the glyph outlines (#2294) | -| **Contour tool** | beyond Illustrator | Drag away from a selected shape's edge to grow a live copy of it, or toward the inside to shrink it (Shift: whole points); the copy carries a live Offset Path effect so it stays editable, with its own fill and stroke, until Bake (Expand Appearance). A second drag on a selected Contour changes it instead of nesting another; Escape cancels. A floating bar above the selection sets the distance and the corners (Sharp, Round, Square); `object.contour` makes or changes one over MCP and the control channel. Two Contours baked and combined with Minus Front give a border with a gap. Paths, shapes and compound paths only; type isn't offset. Tests: `crates/engine/src/tests/contour.rs`, `crates/ui-egui/src/canvas/tests.rs` | +| **Contour add-on** | beyond Illustrator | Drag away from a selected shape's edge to grow a live copy of it, or toward the inside to shrink it (Shift: whole points); the copy carries a live Offset Path effect so it stays editable, with its own fill and stroke, until Bake (Expand Appearance). A second drag on a selected Contour changes it instead of nesting another; Escape cancels. A floating bar above the selection sets the distance and the corners (Sharp, Round, Square); `addon.contour.set` makes or changes one over MCP and the control channel. The tool is in Object › Plug-ins › Contour and under its own heading in All Tools, with no default shortcut or toolbar slot. Two Contours baked and combined with Minus Front give a border with a gap. Paths, shapes and compound paths only; type isn't offset. Tests: `crates/engine/src/cmd/addons/contour/tests.rs`, `crates/ui-egui/src/canvas/tests.rs` | ## Evidence: what ships today, by area @@ -1650,6 +1650,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | Contour add-on (beyond Illustrator): drag away from a selected shape's edge to grow a live copy of it, or toward the inside to shrink it; the copy carries a live Offset Path effect, so it stays editable until Bake (Expand Appearance), a second drag changes the same Contour instead of nesting one, and a floating bar sets the distance and the Sharp, Round or Square corners. `addon.contour.set` is the command behind it. It is a built-in add-on: Object › Plug-ins › Contour, and its own heading in All Tools, with no default shortcut or toolbar slot. A VectorCraft design built on Offset Path; no other application was inspected. Scores and estimates unchanged. | | 2026-11-04 | minor | Contour tool (beyond Illustrator): drag away from a selected shape's edge to grow a live copy of it, or toward the inside to shrink it; the copy carries a live Offset Path effect, so it stays editable until Bake (Expand Appearance), a second drag changes the same Contour instead of nesting one, and a floating bar sets the distance and the Sharp, Round or Square corners. `object.contour` is the command behind it. A VectorCraft design built on Offset Path; no other application was inspected. Scores and estimates unchanged. | | 2026-11-05 | minor | View & navigation: document tabs are reordered by dragging them along the tab strip (`document.move`, #5663); evidence added; scores unchanged. | | 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. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 282eea9b6a..ac9cf181b4 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Contour tool, beyond Illustrator; scores and estimates unchanged; Select by Artboards add-on selects by overlap, inside or outside several artboards; Cmd+Space keeps the active drawing cursor during its drag; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Contour add-on, beyond Illustrator; scores and estimates unchanged; Select by Artboards add-on selects by overlap, inside or outside several artboards; Cmd+Space keeps the active drawing cursor during its drag; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) ## Feature submission evidence @@ -437,6 +437,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | Contour add-on (beyond Illustrator): drag away from a selected shape's edge to grow a live copy of it, or toward the inside to shrink it; the copy carries a live Offset Path effect, so it stays editable until Bake (Expand Appearance), a second drag changes the same Contour instead of nesting one, and a floating bar sets the distance and the Sharp, Round or Square corners. `addon.contour.set` is the command behind it. It is a built-in add-on: Object › Plug-ins › Contour, and its own heading in All Tools, with no default shortcut or toolbar slot. A VectorCraft design built on Offset Path; no other application was inspected. Scores and estimates unchanged. | | 2026-11-04 | minor | Contour tool (beyond Illustrator): drag away from a selected shape's edge to grow a live copy of it, or toward the inside to shrink it; the copy carries a live Offset Path effect, so it stays editable until Bake (Expand Appearance), a second drag changes the same Contour instead of nesting one, and a floating bar sets the distance and the Sharp, Round or Square corners. `object.contour` is the command behind it. A VectorCraft design built on Offset Path; no other application was inspected. Scores and estimates unchanged. | | 2026-11-05 | minor | Document tabs are reordered by dragging them along the tab strip (`document.move`, #5663). | | 2026-11-04 | minor | Path Precision Tools add-on (a VectorCraft addition): Set Corners… rounds only the corners in an angle range (#5545); scores and estimates unchanged | From 94424bfa0c2dfd87f92928c9c87d022d3ee93786 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 18:40:54 -0800 Subject: [PATCH 042/196] MCP: pointer_gesture waits for a key sent before it In remote mode, press_key queues its key for the next UI pass, while pointer_gesture drives the tool as soon as the app reads the request. A release sent right after a key could commit the drag before the key reached the tool, so C pressed while dragging out an arc left it open. A ui.pointer request now waits, ahead of the requests after it, until the synthetic input sent before it has been applied. --- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/app/control.rs | 10 +++++++- crates/ui-egui/src/control.rs | 3 ++- crates/ui-egui/src/lib.rs | 3 +++ crates/ui-egui/src/tests/synthetic.rs | 35 +++++++++++++++++++++++++++ docs/mcp.md | 2 +- 6 files changed, 51 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index c3869c5990..eb9c3526e1 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -104,6 +104,7 @@ impl VectorcraftApp { clipboard_publishing: Default::default(), pending_url: None, control_rx: None, + deferred_control: None, pending_screenshots: vec![], queued_screenshots: vec![], screenshot_token: 0, diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs index bbdf60befc..cde629466c 100644 --- a/crates/ui-egui/src/app/control.rs +++ b/crates/ui-egui/src/app/control.rs @@ -9,7 +9,15 @@ impl VectorcraftApp { let Some(rx) = self.control_rx.take() else { return }; let mut handled = 0; while handled < control::MAX_CONTROL_REQUESTS_PER_FRAME { - let Ok(req) = rx.try_recv() else { break }; + let Some(req) = self.deferred_control.take().or_else(|| rx.try_recv().ok()) else { break }; + // `ui.pointer` drives the tool at once, while `ui.key` and the other synthetic input + // reach it in a later UI pass: a pointer request waits until the input sent before it + // was applied, so a key pressed during a drag changes the drag before its release. + if req.method == "ui.pointer" && (!self.synthetic.is_empty() || self.synthetic_injected) { + self.deferred_control = Some(req); + ctx.request_repaint(); + break; + } // Its caller stopped waiting (the app was busy or its window not drawn for too long) // and was told it won't run: an edit applied now would come from nowhere (#1725). if !req.claim() { diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index d25a08f94d..045ad97328 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -10,7 +10,8 @@ //! - `ui.contextMenu.list`: the canvas context menu for the current selection, flattened //! - `ui.tool.select {tool}`, `ui.tool.list` //! - `ui.pointer {events:[{kind: down|drag|up|move|doubleclick, x, y, backquote?, space?: "doc"|"screen"}], mods?, backquote?}`: -//! drive the active tool through the same path as the mouse +//! drive the active tool through the same path as the mouse, after the synthetic input sent +//! before it was applied //! - `ui.key {key, shift?, alt?, cmd?}` / `ui.text {text}`: synthetic keyboard input //! - `ui.move {x, y}` / `ui.click {x, y, button?, count?, shift?…}` / `ui.drag {x, y, toX, toY, steps?}`: //! real egui pointer input in screen points (reaches every widget: panels, flyouts, dialogs) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 48b4e8dd3e..5b0aa93d84 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -151,6 +151,9 @@ pub struct VectorcraftApp { /// moves ([`native_menu::sync`]). run_count: u64, control_rx: Option>, + /// A `ui.pointer` request taken from the channel while synthetic input sent before it was not + /// yet applied: it runs, ahead of the channel, on the first frame after that input is applied. + deferred_control: Option, /// Window captures asked for and not answered yet. pending_screenshots: Vec, /// Admitted captures whose settled frame has not come yet (issued one at a time). diff --git a/crates/ui-egui/src/tests/synthetic.rs b/crates/ui-egui/src/tests/synthetic.rs index cb328e235f..c6e64a12fa 100644 --- a/crates/ui-egui/src/tests/synthetic.rs +++ b/crates/ui-egui/src/tests/synthetic.rs @@ -82,6 +82,41 @@ fn a_typed_key_holds_its_modifiers_for_its_text() { assert_eq!(app.session.tool_id(), "blobBrush", "Shift+B, not B"); } +/// A `ui.pointer` release sent right after a `ui.key` waits until the key reached the busy tool: +/// C pressed while an arc is dragged out closes the arc drawn on release. +#[test] +fn a_pointer_release_after_a_key_waits_for_the_key() { + let (tx, rx) = std::sync::mpsc::channel(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()).with_control(rx); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("tool.select", json!({"tool": "arc"})).unwrap(); + let ctx = egui::Context::default(); + control(&mut app, &ctx, "ui.pointer", json!({"events": [{"kind": "down", "x": 100, "y": 100}, {"kind": "drag", "x": 200, "y": 180}]})); + let (key, _key_reply) = ControlRequest::new("ui.key", json!({"key": "c"})); + let (up, up_reply) = ControlRequest::new("ui.pointer", json!({"events": [{"kind": "up", "x": 200, "y": 180}]})); + tx.send(key).unwrap(); + tx.send(up).unwrap(); + // Each frame as the host runs it: the input hook, the control requests, then the UI pass. + let mut released = None; + for _ in 0..8 { + let mut raw = egui::RawInput::default(); + app.raw_input_hook(&ctx, &mut raw); + app.drain_control(&ctx); + if let Ok(r) = up_reply.try_recv() { + released = Some(r); + break; + } + let mut out = ctx.run_ui(raw, |ui| crate::shortcuts::handle(&mut app, ui.ctx())); + out.textures_delta.clear(); + } + let r = released.expect("the release ran"); + assert_eq!(r["ok"], true, "{r}"); + let document = app.session.active().unwrap(); + let arc = *document.selection.objects.last().expect("the arc drawn on release"); + let closed = document.doc.node(arc).unwrap().path_data().unwrap().subpaths[0].closed; + assert!(closed, "C reached the Arc tool before the release"); +} + #[test] fn a_drag_holds_its_modifiers_from_the_press_to_the_release() { let (mut app, _) = one_square(); diff --git a/docs/mcp.md b/docs/mcp.md index 8fd7a394aa..624ab31234 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -426,7 +426,7 @@ opens the picker through `run_command` with the remote backend. | `inspect_document` | `{depth?, childLimit?, ids?, kind?, limit?, offset?}` | Artboards (with `color`, `#rrggbb`, for one with a background color), layer tree (ids, kinds, bounds, paint), selection, history, tool. A type node's `fill`, `stroke` and `strokeWidth` are the paint its characters show (its first run's); fills and strokes of the type object itself come as `objectFill`, `objectStroke` and `objectStrokeWidth`. Paint comes as a label (`"#ff0000"`, `"None"`, `"G1 40% (#ff9999)"` for a swatch at a tint); `paint.proxies` gives it as an object. | | `inspect_ui` | `{}` | UI state. Remote mode only. | | `select_tool` | `{tool}` | `selection`, `directSelection`, `pen`, `rectangle`, `ellipse`, `polygon`, `star`, `lineSegment`, … | -| `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`. `backquote` is the held state for each event; the top-level value supplies its default. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. | +| `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`. `backquote` is the held state for each event; the top-level value supplies its default. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. Remote, the events wait until the keys and other input sent before them (`press_key`, `type_text`) have reached the app, so a key pressed between two calls of one drag applies before the release. | | `draw_path` | `{points \| d, closed?, fill?, stroke?, strokeWidth?, dash?, cap?, join?, opacity?, name?, effects?}` | `points` is `[[x,y],…]` or `[{x,y,in?,out?,smooth?},…]`. `d` is SVG path data. The options are below. | | `draw_shape` | `{shape, …geometry, fill?, stroke?, strokeWidth?, dash?, cap?, join?, opacity?, name?, effects?}` | `rectangle`/`ellipse`: `x,y,width,height` (plus `radius` for corners). `polygon`: `cx,cy,radius,sides`. `star`: `cx,cy,radius1,radius2,points`. `line`: `x1,y1,x2,y2`. | | `set_paint` | `{fill?, stroke?, strokeWidth?, ids?}` | Applies to the selection (or `ids`) and becomes the default for new art. Returns `{applied, objects}`: `objects` is the number of objects painted, as the `objects` of the `paint.setFill`, `paint.setStroke` and `stroke.set` replies (the largest of them): a selected group counts the objects inside it. When it is 0, a `note` says that only the paint for new art changed. | From 624c82941e9cc50f3e2baf174b851c6d44d10fee Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 22:30:08 -0800 Subject: [PATCH 043/196] MCP: remote press_key does not run single-key shortcuts docs/mcp.md said that with nothing being dragged, remote press_key c chose the tool bound to C and f ran the shortcut bound to F. Remote press_key sends the key event without the letter it types, and the app runs single-key shortcuts only from the typed letter, so neither runs. The Arc tool, Selection marquee and grid paragraphs now say what headless press_key does with these letters and point remote callers to select_tool or invoke_menu. --- docs/mcp.md | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 624ab31234..1e6fbc2042 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -489,14 +489,17 @@ mode. To press the key during a drag, end one bounding-box scale or rotation, a marquee, a corner widget, pie widget or bracket drag) cancels it: the art goes back, no copy is left, no undo step is added, and the `up` event that follows does nothing. -With nothing being dragged, `e` chooses the tool bound to E. +With nothing being dragged, headless `press_key` `e` chooses the tool bound to E. Remote `press_key` does not run +single-key shortcuts (see the Arc tool below). While an arc is being dragged out with the Arc tool, `press_key {key: "c"}` switches it between an open and a closed path, `{key: "f"}` switches its base between the X and Y axes in the same box, and `{key: "up"}` and `{key: "down"}` raise and lower its slope by 10, within −100…100. Each press switches once. The arc drawn on release uses these values, and they stay as the Arc tool's `closed`, `baseAlong` and `slope` options for the next arc. With nothing being -dragged, `c` chooses the tool bound to C, and `f` runs the shortcut bound to F in remote mode (headless has no -binding for it). +dragged, headless `press_key` `c` chooses the tool bound to C (headless has no binding for F). In remote mode, +`press_key` sends the key event without the letter it types, and the app runs a single-key shortcut such as C or F only +from the typed letter, so with nothing being dragged `c` and `f` do not run their shortcuts there. Use `select_tool` or +`invoke_menu` instead. While a spiral is being dragged out with the Spiral tool, a `drag` event with `mods.alt` or `mods.cmd` keeps the spiral's inner end at the distance from the center it had on the first modified `drag` event, and the outer end follows @@ -515,7 +518,8 @@ While a grid is being dragged out with the Rectangular Grid or Polar Grid tool, 10, and `{key: "x"}` and `{key: "c"}` lower and raise that of the vertical dividers (`columnSkew`) or the concentric dividers (`concentricSkew`), within ±500. Plain and Shift presses change the skew; with Alt, Ctrl or Cmd held they do not. The grid drawn on release uses these skews, and they stay as the tool's options for the next grid. With nothing -being dragged, the four letters run their shortcuts as before. +being dragged, headless `press_key` runs the shortcuts bound to `v`, `x` and `c` (it has none for `f`), and remote +`press_key` does not run single-key shortcuts (see the Arc tool above). Appearance stacks: an object can carry several fills and strokes (`appearance.addFill`, `appearance.addStroke`), indexed in paint order (0 is painted first, the bottom row of the Appearance panel). Cmd+/ runs `appearance.addFill` and From 568bb9315dde7d0f041ed31f14a0bd0834703e54 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Thu, 5 Nov 2026 07:42:38 +0100 Subject: [PATCH 044/196] Line a moved selection's edges up with ruler guides Fixes #5746 Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/tests/prefs.rs | 46 +++++++++++++++++++++++++ crates/tools/src/guides/targets.rs | 54 +++++++++++++++++++++++++++++- crates/tools/src/select.rs | 24 +++++++++---- 3 files changed, 116 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index ae8609cd69..50a429d9e4 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -2001,6 +2001,52 @@ fn a_move_held_by_a_paths_stroke_lands_the_path_on_a_ruler_guide() { } } +/// #5746: a rectangle dragged until its left edge and its top edge are each 1 px from a ruler +/// guide lands on both guides, with "align", whichever guide was added last and wherever it was +/// grabbed; between two upright guides, its left edge lands on the one within reach; and an edge +/// Smart Guides line up with another object stays there, not on a ruler guide as near. +#[test] +fn a_moved_rectangle_lines_its_edges_up_with_two_ruler_guides() { + use vectorcraft_tools::Overlay; + use vectorcraft_tools::PointerKind::{Down, Drag, Up}; + let v = ViewInfo::default(); + // (guides as (vertical, pos), where it is grabbed, the top left it lands on) + type Case = (&'static [(bool, f64)], (f64, f64), (f64, f64)); + let cases: [Case; 3] = [ + (&[(true, 250.0), (false, 320.0)], (200.0, 100.0), (250.0, 320.0)), + (&[(false, 320.0), (true, 250.0)], (100.0, 175.0), (250.0, 320.0)), + (&[(true, 250.0), (true, 455.0)], (200.0, 175.0), (250.0, 100.0)), + ]; + for (guides, (x, y), want) in cases { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap(); + let id = NodeId(s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 200, "height": 150})).unwrap()["id"].as_u64().unwrap()); + for (vertical, pos) in guides { + s.execute("guide.add", &json!({"vertical": vertical, "pos": pos})).unwrap(); + } + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("selection", v).unwrap(); + // 1 px past the guides: the left edge at 251, the top edge at 321 (or where it was). + let (to_x, to_y) = (x + 151.0, if want.1 == 100.0 { y } else { y + 221.0 }); + gesture(&mut s, v, &[(Down, x, y), (Drag, (x + to_x) / 2.0, (y + to_y) / 2.0), (Drag, to_x, to_y)]); + let align = s.overlays(v).iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "align")); + gesture(&mut s, v, &[(Up, to_x, to_y)]); + assert_eq!(top_left(&s, id), want, "guides {guides:?}, grabbed at ({x}, {y})"); + assert!(align, "guides {guides:?}, grabbed at ({x}, {y}): no align"); + } + // Dragged by its centre until its left edge is at 401: 1 px from another rectangle's left + // edge (400) and 1 px from a ruler guide (402). + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + let id = NodeId(s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 200, "height": 150})).unwrap()["id"].as_u64().unwrap()); + s.execute("shape.rectangle", &json!({"x": 400, "y": 400, "width": 60, "height": 60})).unwrap(); + s.execute("guide.add", &json!({"vertical": true, "pos": 402.0})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("selection", v).unwrap(); + gesture(&mut s, v, &[(Down, 200.0, 175.0), (Drag, 350.0, 175.0), (Drag, 501.0, 175.0), (Up, 501.0, 175.0)]); + assert_eq!(top_left(&s, id), (400.0, 100.0), "a Smart Guides alignment gave way to a ruler guide"); +} + /// #3701: at 28,757%, Direct Selection pressed 1.5 px beside a rectangle's straight left side and /// dragged until the side is 1 px from a ruler guide lands both its anchors on the guide; so does /// the same press and drag on the rectangle selected whole, which moves it. diff --git a/crates/tools/src/guides/targets.rs b/crates/tools/src/guides/targets.rs index 36947c9314..6fed43337e 100644 --- a/crates/tools/src/guides/targets.rs +++ b/crates/tools/src/guides/targets.rs @@ -964,7 +964,14 @@ impl Targets { /// ([`Self::for_move`]) is spaced evenly along an axis that lines up with nothing /// ([`Self::even_spacing`]). Returns the shift and the guides. pub fn snap_rects(&self, rects: &[Rect], tol: f64) -> (Vec2, Vec) { + let (d, ov, _) = self.snap_rects_axes(rects, tol); + (d, ov) + } + + /// [`Self::snap_rects`], also saying which axes (x, y) lined up or were spaced evenly. + pub(crate) fn snap_rects_axes(&self, rects: &[Rect], tol: f64) -> (Vec2, Vec, [bool; 2]) { let (mut d, mut ov, aligned) = self.align_rects(rects, tol); + let mut taken = aligned; if let [r] = rects && !self.boxes.is_empty() { @@ -973,6 +980,7 @@ impl Targets { for (x, lined_up) in [true, false].into_iter().zip(aligned) { if let Some((shift, _)) = self.even_spacing(moved, x, tol).filter(|_| !lined_up) { *(if x { &mut d.x } else { &mut d.y }) += shift; + taken[usize::from(!x)] = true; spaced = true; } } @@ -985,7 +993,7 @@ impl Targets { } } } - (d, ov) + (d, ov, taken) } /// Spacing Guides along the x axis (`x`) or the y axis for the moved rectangle `r`, among the @@ -1088,6 +1096,50 @@ impl Targets { (d, ov, [best_x.is_some(), best_y.is_some()]) } + /// Snap a selection grabbed at `p` and moved as a whole, its bounds now `r`, to the ruler + /// guides: the grabbed point goes into line with a guide running within `tol` of it + /// ([`Self::snap_point`]), and on an axis where none does and that is not `taken` (x, y) + /// already, the edge or centre of `r` nearest a guide running past it within `tol` goes onto it + /// (#5746). Returns the shift, the guides (none when nothing lines up) and whether a guide held + /// the grabbed point. + pub(crate) fn snap_moved_to_rulers(&self, p: Point, r: Option, tol: f64, taken: [bool; 2]) -> (Vec2, Vec, bool) { + let near = |vertical: bool| { + let v = if vertical { p.x } else { p.y }; + self.rulers.iter().any(|g| g.vertical == vertical && (g.pos - v).abs() <= tol && g.line_at(p, tol).is_some()) + }; + let held = [near(true), near(false)]; + let (q, mut ov) = if held.contains(&true) { self.snap_point(p, tol) } else { (p, vec![]) }; + let mut d = q - p; + let Some(r) = r.map(|r| r + d) else { return (d, ov, held.contains(&true)) }; + // The guide upright (`vertical`) or level nearest one of `vs`, running past `r` across. + let nearest = |vertical: bool, vs: [f64; 3]| { + let (c, half) = + if vertical { (Point::new(0.0, r.center().y), r.height() / 2.0) } else { (Point::new(r.center().x, 0.0), r.width() / 2.0) }; + self.rulers + .iter() + .filter(|g| g.vertical == vertical) + .filter_map(|g| g.line_at(c, tol + half)) + .flat_map(|(t, from, _)| vs.into_iter().map(move |v| (t - v, t, from))) + .filter(|(s, ..)| s.abs() <= tol) + .min_by(|a, b| a.0.abs().total_cmp(&b.0.abs())) + }; + let hx = if held[0] || taken[0] { None } else { nearest(true, [r.x0, r.center().x, r.x1]) }; + let hy = if held[1] || taken[1] { None } else { nearest(false, [r.y0, r.center().y, r.y1]) }; + let shift = Vec2::new(hx.map_or(0.0, |h| h.0), hy.map_or(0.0, |h| h.0)); + let (r, lined) = (r + shift, hx.is_some() || hy.is_some()); + d += shift; + if let Some((_, x, from)) = hx { + ov.extend(self.line(Point::new(x, from.y.min(r.y0)), Point::new(x, from.y.max(r.y1)))); + } + if let Some((_, y, from)) = hy { + ov.extend(self.line(Point::new(from.x.min(r.x0), y), Point::new(from.x.max(r.x1), y))); + } + if lined && !held.contains(&true) { + ov.extend(self.label(p + d, "align")); + } + (d, ov, held.contains(&true)) + } + /// Snap a bounding-box resize. `a` is the scale [`crate::bbox::scale_for_drag`] gave for /// dragging `handle` of the box `bx` (about the centre when `from_center`), in the box's own /// frame, and so is the result. The handle lands on an anchor or centre within `tol` on the page diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 572c667e4b..e5474bbde7 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -206,7 +206,7 @@ pub(crate) struct MoveSnap { copy_targets: Option, copy_points: Option, /// With Smart Guides on, the ruler guides View › Snap to Point still pulls the grabbed point - /// onto (#1534); `points` holds them with Smart Guides off. + /// onto (#1534), and lines the bounds up with (#5746); `points` holds them with Smart Guides off. rulers: Option, } @@ -245,6 +245,8 @@ impl MoveSnap { d = q - start; guides = ov; } + // The axes (x, y) Smart Guides already put in line with other art. + let mut taken = [false; 2]; if let (Some(t), Some(b)) = (targets, self.bounds) { // The point the selection was grabbed by, near another object's anchor or centre, // lands on it, rather than the bounds lining up a little beside it (#955). @@ -252,18 +254,26 @@ impl MoveSnap { let (q, ov) = t.snap_point(start + d, cx.snap_tol()); d = q - start; guides = ov; + taken = [true; 2]; } else { - let (adj, ov) = t.snap_rect(b + d, cx.snap_tol()); + let (adj, ov, axes) = t.snap_rects_axes(&[b + d], cx.snap_tol()); d += adj; guides = ov; + taken = axes; } } - // A ruler guide within reach of the grabbed point wins over lining the bounds up. + // A ruler guide within reach of the grabbed point wins over lining the bounds up; on an + // axis without one that Smart Guides left free, the bounds line up with the ruler guides + // (#5746), alongside the Smart Guides. if let Some(t) = &self.rulers { - let (q, ov) = t.snap_point(start + d, cx.tol(cx.snap_tolerance)); - if q != start + d { - d = q - start; - guides = ov; + let (adj, ov, held) = t.snap_moved_to_rulers(start + d, self.bounds.map(|b| b + d), cx.tol(cx.snap_tolerance), taken); + if adj != Vec2::ZERO { + d += adj; + if held { + guides = ov; + } else { + guides.extend(ov); + } } } if cx.snap_to_pixel From d88f5eeed963dc7abc859915de2fe9ba7da009ad Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 22:26:36 -0800 Subject: [PATCH 045/196] Render: a moved path reuses its gradient stroke slices A path whose stroke has a gradient along or across it kept its slices under the node's address, so every nudge made the slices again for the whole path, although its stroke outline was already reused. The renderer now keeps the key of a stroke's latest slices under the object's id, the stroke's place and the tolerance level, and when the object has only moved (same stroke and gradient, same fill rule, anchors moved by one offset) it draws those slices moved by the offset, translating only the slices that reach the piece being clipped. Scale, rotate, an anchor edit or a change to the stroke or its gradient makes the slices again. The pixels are the same. --- crates/render/src/frame.rs | 19 +++- crates/render/src/lib.rs | 6 +- crates/render/src/renderer.rs | 5 +- crates/render/src/renderer/paint.rs | 99 ++++++++++++++++++-- crates/render/src/tests/movedstroke.rs | 125 ++++++++++++++++++++++++- docs/target-app-parity.md | 1 + 6 files changed, 236 insertions(+), 19 deletions(-) diff --git a/crates/render/src/frame.rs b/crates/render/src/frame.rs index 41a53201a2..df71c6da97 100644 --- a/crates/render/src/frame.rs +++ b/crates/render/src/frame.rs @@ -1,6 +1,6 @@ use super::options::{AntiAlias, RenderOptions}; use super::threads::single_threaded_context; -use super::{Affine, Arc, BezPath, Document, FillRule, HashMap, Ink, Node, Rect, RenderContext, StrokeLayer, SymbolBoxes, TextObject, live}; +use super::{Affine, Arc, BezPath, Document, FillRule, HashMap, Ink, Node, Rect, RenderContext, StrokeLayer, SymbolBoxes, TextObject, kurbo, live}; /// Hasher for pointer-keyed caches: a multiply-xorshift (SipHash showed up in frame profiles). #[derive(Default, Clone, Copy)] @@ -51,10 +51,25 @@ pub(crate) struct StrokeEntry { /// The slices of a stroke whose gradient runs along or across it, each with its paint and bounds. pub(crate) type Slices = Arc>; -/// [`Slices`] cached for a stroke: (owning node, slices, last frame used). +/// The key of cached [`Slices`]: ([`Renderer::stroke_owner`] of the stroke's object, stroke layer +/// address, tolerance level). +pub(crate) type SliceKey = (usize, usize, i32); + +/// What the [`SliceKey`] of the latest slices of an object's stroke is found under once the object +/// has changed: (the object's id, the stroke's place in its appearance items, tolerance level). +pub(crate) type MovedSliceKey = (u64, usize, i32); + +/// [`Slices`] cached for a stroke: (owning node, the node whose path and stroke the slices were +/// made from, either the owning node or an earlier copy of it that the owning node is moved from, +/// the slices, the offset they are drawn moved by, the fill rule they were made with, whether they +/// were made along the path [`Node::stroke_path`] makes from that node, last frame used). pub(crate) struct SliceEntry { pub(crate) node: Arc, + pub(crate) made: Arc, pub(crate) slices: Slices, + pub(crate) by: kurbo::Vec2, + pub(crate) rule: FillRule, + pub(crate) own: bool, pub(crate) stamp: u64, } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index b9852d0a19..cf9114846c 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -168,7 +168,11 @@ pub struct Renderer { clip_paints: FrameCache, /// Gradients along or across strokes (see [`Self::fill_path_gradient`]), keyed by /// ([`Self::stroke_owner`], stroke layer address, tolerance level). - stroke_slices: PtrMap<(usize, usize, i32), SliceEntry>, + stroke_slices: PtrMap, + /// The key in `stroke_slices` of the latest slices of each stroke of an object, under its + /// [`frame::MovedSliceKey`]: a moved copy of the object draws those slices moved + /// ([`Self::moved_slices`]). + moved_slices: PtrMap, /// What the image keys colour adjustments give their recoloured images name: the image /// recoloured and the adjustment, with its hash (see [`Self::adjusted_image`]). adjusts: HashMap, diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index e8aa40d3eb..2f69551c11 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -19,7 +19,7 @@ use super::{ }; #[cfg(test)] -pub(crate) use paint::{STROKES_OUTLINED, anchors_moved, offset_between}; +pub(crate) use paint::{SLICES_MADE, STROKES_OUTLINED, anchors_moved, offset_between}; mod images; mod nodes; @@ -76,6 +76,7 @@ impl Renderer { twice_drawn: 0, clip_paints: FrameCache::new(lru::CLIP_BUDGET, 256), stroke_slices: PtrMap::default(), + moved_slices: PtrMap::default(), adjusts: HashMap::new(), dim_images: None, inline_depth: 0, @@ -195,6 +196,8 @@ impl Renderer { } if self.stroke_slices.len() > 256 { self.stroke_slices.retain(|_, e| g - e.stamp <= 3); + let slices = &self.stroke_slices; + self.moved_slices.retain(|_, k| slices.contains_key(k)); } if self.shadows.len() > 256 { self.shadows.retain(|_, e| g - e.stamp <= 3); diff --git a/crates/render/src/renderer/paint.rs b/crates/render/src/renderer/paint.rs index 5228cc8817..6d9f0ea3e0 100644 --- a/crates/render/src/renderer/paint.rs +++ b/crates/render/src/renderer/paint.rs @@ -3,7 +3,7 @@ use super::{ Slices, StrokeAlign, StrokeEntry, StrokeLayer, TextGeom, blend_mode, drawable, effects, fill_rule, fx, kurbo, lru, owns_stroke, peniko, rects_overlap, }; -use crate::frame::{MovedKey, StrokeKey}; +use crate::frame::{MovedKey, MovedSliceKey, StrokeKey}; use crate::paint; impl Renderer { @@ -164,7 +164,9 @@ impl Renderer { /// Paint the line and arrowheads (`pieces`) of stroke `st` of `bp` (filled with `rule`) with /// its gradient `g` laid along or across the path ([`effects::stroke::gradient_slices`]). Each /// piece clips the slices, grown a pixel into each other and each replacing what it covers, so - /// neighbours meet without seams and translucent colours paint once. + /// neighbours meet without seams and translucent colours paint once. The slices of a stroke + /// of `self.cur` are kept in `stroke_slices`, and a moved copy of the object draws the slices + /// made before it moved, moved by the same offset ([`Self::moved_slices`]). #[allow(clippy::too_many_arguments)] fn fill_path_gradient( &mut self, @@ -180,6 +182,8 @@ impl Renderer { ) { let level = (f.px * 0.25).log2().floor() as i32; let make = || -> Slices { + #[cfg(test)] + SLICES_MADE.with(|n| n.set(n.get() + 1)); let tol = 2f64.powi(level); // Reach a pixel past the stroke, so its antialiased edge has colour under it. let slices = effects::stroke::gradient_slices(bp, rule, st, tol, f.px + tol, f.px); @@ -193,22 +197,37 @@ impl Renderer { .collect(), ) }; - let slices = match self.cur.clone().filter(|n| owns_stroke(n, st)) { + let (slices, by) = match self.cur.clone().filter(|n| owns_stroke(n, st)) { Some(node) => { let key = (self.stroke_owner(Arc::as_ptr(&node) as usize), st as *const StrokeLayer as usize, level); match self.stroke_slices.get_mut(&key) { Some(e) if Arc::ptr_eq(&e.node, &node) => { e.stamp = self.stamp; - e.slices.clone() + (e.slices.clone(), e.by) } _ => { - let slices = make(); - self.stroke_slices.insert(key, SliceEntry { node, slices: slices.clone(), stamp: self.stamp }); - slices + // Under its object's id, the stroke's place and the tolerance level, the key + // of the stroke's latest slices is kept, except for art made again in every + // frame. + let place = node.appearance.items.iter().position(|i| matches!(i, AppearanceItem::Stroke(s) if std::ptr::eq(s, st))); + let moved = place.filter(|_| !self.made_again).map(|place| (node.id.0, place, level)); + let kept = moved.and_then(|mk| self.moved_slices(mk, &node, st, rule, bp)); + let (made, slices, by, own) = match kept { + Some((made, slices, by)) => (made, slices, by, true), + None => { + let own = moved.is_some() && self.own_path(&node, bp); + (node.clone(), make(), kurbo::Vec2::ZERO, own) + } + }; + self.stroke_slices.insert(key, SliceEntry { node, made, slices: slices.clone(), by, rule, own, stamp: self.stamp }); + if let Some(mk) = moved { + self.moved_slices.insert(mk, key); + } + (slices, by) } } } - None => make(), + None => (make(), kurbo::Vec2::ZERO), }; let line = match self.cached_stroke(f, chars, bp, &pieces.line, st, width) { Some(o) => o, @@ -223,8 +242,18 @@ impl Renderer { ctx.push_clip_layer(clip); ctx.set_blend_mode(BlendMode::new(Mix::Normal, Compose::Copy)); for (shape, paint, b) in slices.iter() { - if rects_overlap(*b, cb) && paint::set_paint(ctx, paint, *b, f) { - ctx.fill_path(shape); + let b = *b + by; + if !rects_overlap(b, cb) { + continue; + } + if by == kurbo::Vec2::ZERO { + if paint::set_paint(ctx, paint, b, f) { + ctx.fill_path(shape); + } + } else if paint::set_paint(ctx, &moved_paint(paint, by), b, f) { + let mut shape = shape.clone(); + shape.apply_affine(Affine::translate(by)); + ctx.fill_path(&shape); } } ctx.set_blend_mode(BlendMode::default()); @@ -364,6 +393,38 @@ impl Renderer { Some((Arc::new(outline), crop)) } + /// The slices of stroke `st` of `node` along `bp` (filled with `rule`), made from the latest + /// slices kept under `mk` ([`MovedSliceKey`]) when those were made along their object's own + /// path, their object is `node` changed, its stroke there is `st` and its fill rule `rule`, and + /// `bp` is its path moved (to within rounding): the node they were made from, those slices, + /// and the offset from that node to `bp`, which the slices are drawn moved by. The anchors of + /// the two objects are compared first ([`anchors_moved`]), and the earlier path is made again + /// from its object only when they match. `None` when there are no such slices. + fn moved_slices( + &self, + mk: MovedSliceKey, + node: &Node, + st: &StrokeLayer, + rule: FillRule, + bp: &BezPath, + ) -> Option<(Arc, Slices, kurbo::Vec2)> { + let e = self.stroke_slices.get(self.moved_slices.get(&mk)?)?; + if !e.own || e.rule != rule || e.made.id != node.id { + return None; + } + let Some(AppearanceItem::Stroke(old)) = e.made.appearance.items.get(mk.1) else { + return None; + }; + if !std::ptr::eq(old, st) && old != st { + return None; + } + if !anchors_moved(&e.made, node) { + return None; + } + let by = offset_between(&e.made.stroke_path()?, bp)?; + Some((e.made.clone(), e.slices.clone(), by)) + } + /// What the `strokes`, `char_strokes` and `stroke_slices` keys hold for a stroke owner at /// `address` (`self.cur` or kept glyph geometry): the address, or 0 while art made again in /// every frame is drawn ([`Self::made_again`]). @@ -382,6 +443,24 @@ thread_local! { pub(crate) static CROP_STROKES: std::cell::Cell = const { std::cell::Cell::new(true) }; /// How many stroke outlines of nodes [`Renderer::cached_stroke`] has made on this thread. pub(crate) static STROKES_OUTLINED: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// How many sets of gradient stroke slices [`Renderer::fill_path_gradient`] has made on this + /// thread. + pub(crate) static SLICES_MADE: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Paint `p` of a slice ([`Slices`]) moved by `by`: a gradient's start, end and focal point moved. +fn moved_paint(p: &vectorcraft_color::Paint, by: kurbo::Vec2) -> vectorcraft_color::Paint { + let mut p = p.clone(); + if let vectorcraft_color::Paint::Gradient(g) = &mut p + && let Some(geom) = &mut g.geom + { + geom.start += by; + geom.end += by; + if let Some(focal) = &mut geom.focal { + *focal += by; + } + } + p } /// The offset that moves path `was` onto path `now`, when `now` is `was` moved (each point within diff --git a/crates/render/src/tests/movedstroke.rs b/crates/render/src/tests/movedstroke.rs index de35aa592a..81fa40da8d 100644 --- a/crates/render/src/tests/movedstroke.rs +++ b/crates/render/src/tests/movedstroke.rs @@ -1,14 +1,16 @@ -//! A moved object draws its stroke from the outline made for it before it moved, moved by the same +//! A moved object draws its stroke from the outline made for it before it moved, and a gradient +//! along or across its stroke from the slices made for it before it moved, moved by the same //! offset, with the pixels a new renderer draws. A change other than a move outlines the stroke -//! again. +//! and makes the slices again. -use vectorcraft_color::{Color, Gradient, GradientPaint, Paint}; +use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint}; use vectorcraft_doc::{ - Appearance, AppearanceItem, ArrowAlign, Arrowhead, Dash, FillLayer, LineCap, LineJoin, Node, NodeId, NodeKind, StrokeLayer, WidthProfile, + Appearance, AppearanceItem, ArrowAlign, Arrowhead, Dash, FillLayer, LineCap, LineJoin, Node, NodeId, NodeKind, StrokeGradientMode, StrokeLayer, + WidthProfile, }; use vectorcraft_geom::{PathData, Point, Vec2}; -use crate::renderer::{STROKES_OUTLINED, anchors_moved, offset_between}; +use crate::renderer::{SLICES_MADE, STROKES_OUTLINED, anchors_moved, offset_between}; use crate::*; const SIZE: u32 = 200; @@ -326,6 +328,119 @@ fn points_each_near_the_one_before_are_checked_against_one_offset() { assert!(!anchors_moved(&node(&was), &node(&edited))); } +/// How many sets of gradient stroke slices the renderers on this thread have made. +fn sliced() -> usize { + SLICES_MADE.with(std::cell::Cell::get) +} + +/// A stroke of `width` whose black to blue gradient runs `mode` (along or across the path). +fn gradient_stroke(width: f64, mode: StrokeGradientMode) -> StrokeLayer { + let g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]); + let mut st = stroke(width, LineJoin::Round, LineCap::Butt); + st.paint = Paint::Gradient(Box::new(GradientPaint::new(g))); + st.gradient_mode = mode; + st +} + +/// The documents of the gradient cases: open and closed paths, short and long (their line outlined +/// near the view), each with a gradient along and across the stroke, with the point the view is +/// centered on. +fn gradient_cases() -> Vec<(String, (Document, NodeId), Point)> { + let mut out = vec![]; + for mode in [StrokeGradientMode::Along, StrokeGradientMode::Across] { + let only = || vec![AppearanceItem::Stroke(gradient_stroke(12.0, mode))]; + out.push((format!("a short open path, {mode:?}"), doc(&zigzag(20), only()), Point::new(70.0, 15.0))); + out.push((format!("a short closed path, {mode:?}"), doc(&ring(40, 80.0), only()), Point::new(80.0, 0.0))); + out.push((format!("a long open path, {mode:?}"), doc(&zigzag(3000), only()), Point::new(12_000.0, 15.0))); + out.push((format!("a long closed path, {mode:?}"), doc(&ring(4000, 5000.0), only()), Point::new(0.0, 5000.0))); + } + out +} + +/// Draws `d` after `change` with `r` and with a new renderer, checks that the two draw the same +/// pixels, and returns how many sets of slices `r` made. +fn after_sliced(r: &mut Renderer, d: &mut Document, id: NodeId, at: Point, change: impl FnOnce(&mut Node)) -> usize { + change(d.node_mut(id).unwrap()); + let before = sliced(); + let img = render(r, d, at); + let made = sliced() - before; + assert!(img.pixels == render(&mut Renderer::new(), d, at).pixels, "the same pixels as a new renderer"); + assert!(img.pixels.chunks(4).any(|p| p[0] < 128), "the stroke shows"); + made +} + +/// Sets the color of the last stop of each stroke's gradient in `n`. +fn recolor(n: &mut Node, color: Color) { + restroke(n, |s| { + if let Paint::Gradient(g) = &mut s.paint + && let Some(stop) = g.gradient.stops.last_mut() + { + stop.color = color; + } + }) +} + +#[test] +fn a_moved_path_draws_its_gradient_stroke_from_the_slices_made_before() { + for (what, (mut d, id), at) in gradient_cases() { + let mut r = Renderer::new(); + render(&mut r, &d, at); + for by in [Vec2::new(1.0, 0.0), Vec2::new(0.25, -0.5), Vec2::new(-3.0, 2.0), Vec2::new(0.1, 0.0)] { + let made = after_sliced(&mut r, &mut d, id, at, |n| n.transform(Affine::translate(by), true)); + assert_eq!(made, 0, "{what}, moved by {by:?}: no new slices"); + } + assert_eq!(after_sliced(&mut r, &mut d, id, at, |_| {}), 0, "{what}: drawn again after the moves"); + } +} + +#[test] +fn a_path_changed_otherwise_makes_its_gradient_stroke_slices_again() { + let edit_anchor = |n: &mut Node| { + let NodeKind::Path { path, .. } = &mut n.kind else { + panic!("not a path"); + }; + let mut els = path.to_bezpath().elements().to_vec(); + if let Some(kurbo::PathEl::LineTo(p)) = els.get_mut(2) { + *p += Vec2::new(0.0, 3.0); + } + *path = PathData::from_bezpath(&BezPath::from_vec(els)); + }; + for (what, (mut d, id), at) in gradient_cases() { + let mut r = Renderer::new(); + render(&mut r, &d, at); + let nudge = |n: &mut Node| n.transform(Affine::translate((0.5, 0.0)), true); + assert_eq!(after_sliced(&mut r, &mut d, id, at, nudge), 0, "{what}: moved"); + assert_eq!(after_sliced(&mut r, &mut d, id, at, edit_anchor), 1, "{what}: an anchor moved"); + // A move after the edit uses the slices made for the edited path. + assert_eq!(after_sliced(&mut r, &mut d, id, at, nudge), 0, "{what}: moved after the edit"); + // Scaled and rotated about the view's center, stroke weights kept. + assert_eq!(after_sliced(&mut r, &mut d, id, at, |n| n.transform(Affine::scale_about(1.001, at), false)), 1, "{what}: scaled"); + assert_eq!(after_sliced(&mut r, &mut d, id, at, |n| n.transform(Affine::rotate_about(0.001, at), false)), 1, "{what}: rotated"); + assert_eq!(after_sliced(&mut r, &mut d, id, at, |n| recolor(n, Color::rgb(0.0, 0.5, 0.0))), 1, "{what}: another gradient"); + // Moved with the gradient changed back: the slices of that gradient made before are not used. + assert_eq!( + after_sliced(&mut r, &mut d, id, at, |n| { + recolor(n, Color::rgb(0.0, 0.0, 1.0)); + nudge(n); + }), + 1, + "{what}: the gradient changed back and moved" + ); + // Moved with the gradient laid the other way. + let turn = |s: &mut StrokeLayer| { + s.gradient_mode = if s.gradient_mode == StrokeGradientMode::Along { StrokeGradientMode::Across } else { StrokeGradientMode::Along } + }; + assert_eq!( + after_sliced(&mut r, &mut d, id, at, |n| { + restroke(n, turn); + nudge(n); + }), + 1, + "{what}: the gradient laid the other way and moved" + ); + } +} + #[test] fn a_path_moved_out_of_the_region_its_outline_was_cropped_to_is_outlined_again() { let (mut d, id) = doc(&zigzag(3000), vec![AppearanceItem::Stroke(stroke(6.0, LineJoin::Miter, LineCap::Square))]); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4b90d9967e..53c26cd357 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1280,6 +1280,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The renderer keeps the path of a path or compound path of 1,024 anchors or more by object, with the bounds of its segments and of its miter spikes in runs of 128 segments. When anchors move and the subpaths and anchor counts stay the same, the next frame changes only the segments that start or end at a moved anchor and measures again only the runs that hold them or the segments with length before them, instead of making the whole path again and measuring it whole for culling. The pixels and the cull bounds are the same. On Windows at 1600 × 1200, the frame after one anchor moves takes 8.2 ms instead of 30.1 ms with an open path of 200,000 anchors, 4.3 ms instead of 10.4 ms with a closed path of 50,000 anchors, and 6.6 ms instead of 11.9 ms with the filled closed path of 50,000 anchors and a dashed stroke (medians of five runs of `anchor_bench`). When a path object moves without changing shape, the renderer draws its stroke from the outline it made before the move, moved by the same offset. It outlines the stroke again when the path is scaled, rotated or edited, when the stroke changes, and when the move takes the view past the part of a long path it outlined. The pixels are the same. At 1600 × 1200, the frame after a 1 pt nudge takes 123 ms instead of 403 ms with an open path of 200,000 anchors in view (103 ms with nothing changed), and 13 ms instead of 26 ms with a closed path of 50,000 anchors whose stroke is dashed and has a width profile. When a path object moves without changing shape, the renderer draws its stroke from the outline it made before the move, moved by the same offset. It outlines the stroke again when the path is scaled, rotated or edited, when the stroke changes, and when the move takes the view past the part of a long path it outlined. The pixels are the same. At 1600 × 1200, the frame after a 1 pt nudge takes 128 ms instead of 405 ms with an open path of 200,000 anchors in view (104 ms with nothing changed), and 14 ms instead of 28 ms with a closed path of 50,000 anchors whose stroke is dashed and has a width profile. + When the stroke of a path moved this way has a gradient along or across it, the renderer also draws the gradient from the slices it made before the move, moved by the same offset. It makes the slices again when the path is scaled, rotated or edited, and when the stroke or its gradient changes. The pixels are the same. On Windows at 1600 × 1000, the frame after a 1 pt nudge of an open path of 200,000 anchors takes 75 ms instead of 1,237 ms with the gradient along the stroke and 69 ms instead of 1,420 ms with it across, and with an open path of 50,000 anchors 22 ms instead of 313 ms and 21 ms instead of 352 ms (medians of five interleaved runs). The renderer keeps the path of a path or compound path of 1,024 anchors or more by object, with the bounds of its segments and of its miter spikes in runs of 128 segments. When anchors move and the subpaths and anchor counts stay the same, the next frame changes only the segments that start or end at a moved anchor and measures again only the runs that hold them or the segments with length before them, instead of making the whole path again and measuring it whole for culling. The pixels and the cull bounds are the same. On Windows at 1600 × 1200, the frame after one anchor moves takes 8.2 ms instead of 30.1 ms with an open path of 200,000 anchors, 4.3 ms instead of 10.4 ms with a closed path of 50,000 anchors, and 6.6 ms instead of 11.9 ms with the filled closed path of 50,000 anchors and a dashed stroke (medians of five runs of `anchor_bench`). Type › Show Hidden Characters keeps the marks it places on each text object from one frame to the next. The canvas lays a text object out again when an edit changes it or its threaded story, or when the last frame that showed the marks did not draw it, and it lays out all type in view again when the fonts or the hyphenation exceptions change. With 1,000 two-line labels in view, drawing the marks takes 0.8 ms per frame in a release build instead of 19.7 ms. A selection with more than 100,000 points to outline shows its bounds instead of each object's outline and anchors. Paths count their anchors. Area type and type on a path count the anchors of their frame or path, and point type counts six: its box's corners and the ends of its baseline marker. Images, symbol instances, placed documents, and area type or type on a path in perspective count the four corners of their box, and gradient meshes and envelopes count their points and the ends of their mesh lines. The hover highlight leaves out an object past that count, and such an object shows its bounds as the key object. With 32,768 type objects, images, symbol instances, gradient meshes or envelopes selected, the selection's outlines and anchors add fewer than 100 vertices to the canvas's mesh (#2460). From 63c48588b5b8b1bbdb982a29faa04425617b2c5a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 22:36:47 -0800 Subject: [PATCH 046/196] Render: a moved path reuses the slices of a placed gradient stroke A move also moves where a stroke's gradient is placed, but the slices of a gradient along or across the stroke take only its stops and kind. The moved stroke is now compared with the stroke the slices were made for with the gradient's placement left out, so a placed gradient no longer makes its slices again after every move. --- crates/render/src/renderer/paint.rs | 23 +++++++++++++++++------ crates/render/src/tests/movedstroke.rs | 13 ++++++++++++- 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/crates/render/src/renderer/paint.rs b/crates/render/src/renderer/paint.rs index 6d9f0ea3e0..9e6080428a 100644 --- a/crates/render/src/renderer/paint.rs +++ b/crates/render/src/renderer/paint.rs @@ -395,11 +395,12 @@ impl Renderer { /// The slices of stroke `st` of `node` along `bp` (filled with `rule`), made from the latest /// slices kept under `mk` ([`MovedSliceKey`]) when those were made along their object's own - /// path, their object is `node` changed, its stroke there is `st` and its fill rule `rule`, and - /// `bp` is its path moved (to within rounding): the node they were made from, those slices, - /// and the offset from that node to `bp`, which the slices are drawn moved by. The anchors of - /// the two objects are compared first ([`anchors_moved`]), and the earlier path is made again - /// from its object only when they match. `None` when there are no such slices. + /// path, their object is `node` changed, its stroke there differs from `st` at most in where + /// its gradient is placed, its fill rule is `rule`, and `bp` is its path moved (to within + /// rounding): the node they were made from, those slices, and the offset from that node to + /// `bp`, which the slices are drawn moved by. The anchors of the two objects are compared first + /// ([`anchors_moved`]), and the earlier path is made again from its object only when they + /// match. `None` when there are no such slices. fn moved_slices( &self, mk: MovedSliceKey, @@ -415,7 +416,17 @@ impl Renderer { let Some(AppearanceItem::Stroke(old)) = e.made.appearance.items.get(mk.1) else { return None; }; - if !std::ptr::eq(old, st) && old != st { + // The slices take only the gradient's stops and kind, not where it is placed, which a move + // moves too. + let unplaced = |s: &StrokeLayer| { + let mut s = s.clone(); + if let vectorcraft_color::Paint::Gradient(g) = &mut s.paint { + g.geom = None; + g.angle = 0.0; + } + s + }; + if !std::ptr::eq(old, st) && unplaced(old) != unplaced(st) { return None; } if !anchors_moved(&e.made, node) { diff --git a/crates/render/src/tests/movedstroke.rs b/crates/render/src/tests/movedstroke.rs index 81fa40da8d..f08e341c25 100644 --- a/crates/render/src/tests/movedstroke.rs +++ b/crates/render/src/tests/movedstroke.rs @@ -3,7 +3,7 @@ //! offset, with the pixels a new renderer draws. A change other than a move outlines the stroke //! and makes the slices again. -use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint}; +use vectorcraft_color::{Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint}; use vectorcraft_doc::{ Appearance, AppearanceItem, ArrowAlign, Arrowhead, Dash, FillLayer, LineCap, LineJoin, Node, NodeId, NodeKind, StrokeGradientMode, StrokeLayer, WidthProfile, @@ -353,6 +353,17 @@ fn gradient_cases() -> Vec<(String, (Document, NodeId), Point)> { out.push((format!("a short closed path, {mode:?}"), doc(&ring(40, 80.0), only()), Point::new(80.0, 0.0))); out.push((format!("a long open path, {mode:?}"), doc(&zigzag(3000), only()), Point::new(12_000.0, 15.0))); out.push((format!("a long closed path, {mode:?}"), doc(&ring(4000, 5000.0), only()), Point::new(0.0, 5000.0))); + // A placed gradient, whose start and end a move moves too. + let mut st = gradient_stroke(12.0, mode); + if let Paint::Gradient(g) = &mut st.paint { + g.geom = Some(GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(140.0, 30.0), aspect: 1.0, focal: None }); + g.angle = 12.0; + } + out.push(( + format!("a short open path with a placed gradient, {mode:?}"), + doc(&zigzag(20), vec![AppearanceItem::Stroke(st)]), + Point::new(70.0, 15.0), + )); } out } From 1b8d96433e34c00ebdd00c72c12fc51c494c6aac Mon Sep 17 00:00:00 2001 From: Kindmark <39938776+Kindmark@users.noreply.github.com> Date: Thu, 5 Nov 2026 13:55:41 +0700 Subject: [PATCH 047/196] Compound shapes default Squashed from #5757 onto main. --- ROADMAP.md | 3 +- crates/ui-egui/src/addons.rs | 2 + crates/ui-egui/src/addons/compounds.rs | 19 ++++++ crates/ui-egui/src/i18n/bg.tsv | 4 ++ crates/ui-egui/src/i18n/bs.tsv | 4 ++ crates/ui-egui/src/i18n/ca.tsv | 4 ++ crates/ui-egui/src/i18n/cs.tsv | 4 ++ crates/ui-egui/src/i18n/da.tsv | 4 ++ crates/ui-egui/src/i18n/de.tsv | 4 ++ crates/ui-egui/src/i18n/el.tsv | 4 ++ crates/ui-egui/src/i18n/es.tsv | 4 ++ crates/ui-egui/src/i18n/fi.tsv | 4 ++ crates/ui-egui/src/i18n/fr.tsv | 4 ++ crates/ui-egui/src/i18n/hu.tsv | 4 ++ crates/ui-egui/src/i18n/id.tsv | 4 ++ crates/ui-egui/src/i18n/it.tsv | 4 ++ crates/ui-egui/src/i18n/ja.tsv | 4 ++ crates/ui-egui/src/i18n/ka.tsv | 4 ++ crates/ui-egui/src/i18n/ko.tsv | 4 ++ crates/ui-egui/src/i18n/nl.tsv | 4 ++ crates/ui-egui/src/i18n/pl.tsv | 4 ++ crates/ui-egui/src/i18n/pt-br.tsv | 4 ++ crates/ui-egui/src/i18n/ru.tsv | 4 ++ crates/ui-egui/src/i18n/sv.tsv | 4 ++ crates/ui-egui/src/i18n/tr.tsv | 4 ++ crates/ui-egui/src/i18n/uk.tsv | 4 ++ crates/ui-egui/src/i18n/vi.tsv | 4 ++ crates/ui-egui/src/i18n/zh-hans.tsv | 4 ++ crates/ui-egui/src/i18n/zh-hant.tsv | 4 ++ crates/ui-egui/src/menus/run.rs | 1 + crates/ui-egui/src/menus/state.rs | 1 + crates/ui-egui/src/menus/ui_commands.rs | 6 ++ crates/ui-egui/src/panels/pathfinder.rs | 79 +++++++++++++++++++++++-- crates/ui-egui/src/state.rs | 5 ++ docs/control-protocol.md | 6 ++ docs/gaps.md | 3 +- docs/target-app-parity.md | 4 +- docs/ui-parity.md | 3 +- 38 files changed, 228 insertions(+), 8 deletions(-) create mode 100644 crates/ui-egui/src/addons/compounds.rs diff --git a/ROADMAP.md b/ROADMAP.md index 4115c31c2b..0088ac5a03 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,6 +1,7 @@ # VectorCraft Roadmap - Contour add-on (beyond Illustrator): drag a selected shape's edge outward or inward for a live, editable offset copy, with a floating bar for distance and Sharp, Round or Square corners; Bake turns it into paths. Scores and estimates unchanged. +- Compound Shapes add-on (beyond Illustrator): a menu for Make, Release and Expand Compound Shape and a setting, off by default, that makes the Pathfinder panel's Shape Mode buttons create compound shapes on a click. Scores and estimates unchanged. - Paint: new gradients use the document's color model for default stops, including Gradient tool creation. Scores and estimates unchanged. @@ -13,7 +14,7 @@ **Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Contour add-on, beyond Illustrator; scores and estimates unchanged; 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-05 · **Change:** minor (Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON diff --git a/crates/ui-egui/src/addons.rs b/crates/ui-egui/src/addons.rs index f0238aee23..3f09098422 100644 --- a/crates/ui-egui/src/addons.rs +++ b/crates/ui-egui/src/addons.rs @@ -3,6 +3,7 @@ pub mod arrange; pub mod cleanup; pub mod color; +pub mod compounds; pub mod contour; pub mod document; pub mod enclosing_lasso; @@ -19,6 +20,7 @@ pub fn plugin_menu() -> Vec { Item::Sub("Arrange Tools", arrange::menu()), Item::Sub("Artwork Cleanup", cleanup::menu()), Item::Sub("Color Effects", color::menu()), + Item::Sub("Compound Shapes", compounds::menu()), Item::Sub("Contour", contour::menu()), Item::Sub("Document Tools", document::menu()), Item::Sub("Enclosing Lasso", enclosing_lasso::menu()), diff --git a/crates/ui-egui/src/addons/compounds.rs b/crates/ui-egui/src/addons/compounds.rs new file mode 100644 index 0000000000..00336013a8 --- /dev/null +++ b/crates/ui-egui/src/addons/compounds.rs @@ -0,0 +1,19 @@ +//! Compound Shapes in the interface: its submenu (Object › Plug-ins › Compound Shapes) puts Make, +//! Release and Expand Compound Shape (also in the Pathfinder panel's menu) in the menus, and holds the +//! setting that makes the Pathfinder panel's Shape Mode buttons make compound shapes on a click. It +//! acts through `object.compoundShape.*` and `window.pathfinder.compoundShapes`; nothing else +//! about the Pathfinder panel changes. + +use serde_json::{Value, json}; + +use crate::menus::Item; + +pub fn menu() -> Vec { + vec![ + Item::Cmd("Make Compound Shape", "object.compoundShape.make", json!({})), + Item::Cmd("Release Compound Shape", "object.compoundShape.release", json!({})), + Item::Cmd("Expand Compound Shape", "object.compoundShape.expand", json!({})), + Item::Sep, + Item::Cmd("Shape Mode Buttons Make Compound Shapes", "window.pathfinder.compoundShapes", Value::Null), + ] +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 96735ce205..07c4f90d9f 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6214,3 +6214,7 @@ breakText Glyphs Глифи Even-Numbered Anchors Четни опорни точки Minimum angle Минимален ъгъл Maximum angle Максимален ъгъл + +# Compound Shapes add-on + Compound Shapes Съставни фигури + Shape Mode Buttons Make Compound Shapes Бутоните за режими на фигури създават съставни фигури diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index ad78ee84e0..d007b68291 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6249,3 +6249,7 @@ shape Open Otvoren Even-Numbered Anchors Parna sidra Minimum angle Najmanji ugao Maximum angle Najveći ugao + +# Compound Shapes add-on + Compound Shapes Složeni oblici + Shape Mode Buttons Make Compound Shapes Tasteri načina oblika prave složene oblike diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 8ad31d6d0a..34988b565f 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6350,3 +6350,7 @@ breakText Glyphs Glifs Even-Numbered Anchors Ancoratges parells Minimum angle Angle mínim Maximum angle Angle màxim + +# Compound Shapes add-on + Compound Shapes Formes compostes + Shape Mode Buttons Make Compound Shapes Els botons de mode de forma creen formes compostes diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index d801c39fdc..57c3092b0d 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6364,3 +6364,7 @@ breakText Glyphs Glyfy Even-Numbered Anchors Sudé kotevní body Minimum angle Minimální úhel Maximum angle Maximální úhel + +# Compound Shapes add-on + Compound Shapes Složené tvary + Shape Mode Buttons Make Compound Shapes Tlačítka režimů tvarů vytvářejí složené tvary diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index e410c8e4ac..b5980d5727 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6230,3 +6230,7 @@ breakText Glyphs Glyffer Even-Numbered Anchors Lige ankre Minimum angle Mindste vinkel Maximum angle Største vinkel + +# Compound Shapes add-on + Compound Shapes Sammensatte figurer + Shape Mode Buttons Make Compound Shapes Knapper til formtilstande opretter sammensatte figurer diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index e11cf1bac8..5e38f90f52 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5950,3 +5950,7 @@ breakText Glyphs Glyphen Even-Numbered Anchors Gerade Ankerpunkte Minimum angle Minimaler Winkel Maximum angle Maximaler Winkel + +# Compound Shapes add-on + Compound Shapes Zusammengesetzte Formen + Shape Mode Buttons Make Compound Shapes Formmodus-Schaltflächen erstellen zusammengesetzte Formen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 9f3d0c18e1..84232bda24 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6316,3 +6316,7 @@ breakText Glyphs Γλύφοι Even-Numbered Anchors Ζυγά σημεία αγκύρωσης Minimum angle Ελάχιστη γωνία Maximum angle Μέγιστη γωνία + +# Compound Shapes add-on + Compound Shapes Σύνθετα σχήματα + Shape Mode Buttons Make Compound Shapes Τα κουμπιά λειτουργιών σχημάτων δημιουργούν σύνθετα σχήματα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index b02abb8f1e..c09b51167c 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6306,3 +6306,7 @@ breakText Glyphs Glifos Even-Numbered Anchors Anclas pares Minimum angle Ángulo mínimo Maximum angle Ángulo máximo + +# Compound Shapes add-on + Compound Shapes Formas compuestas + Shape Mode Buttons Make Compound Shapes Los botones de modo de forma crean formas compuestas diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index eebd34d89e..909240b3d2 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6399,3 +6399,7 @@ breakText Glyphs Merkit Even-Numbered Anchors Parilliset ankkurit Minimum angle Pienin kulma Maximum angle Suurin kulma + +# Compound Shapes add-on + Compound Shapes Yhdistelmämuodot + Shape Mode Buttons Make Compound Shapes Muototilapainikkeet luovat yhdistelmämuotoja diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index a5fbb1ab0a..6738ec8df3 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6359,3 +6359,7 @@ breakText Glyphs Glyphes Even-Numbered Anchors Points d’ancrage pairs Minimum angle Angle minimal Maximum angle Angle maximal + +# Compound Shapes add-on + Compound Shapes Formes composées + Shape Mode Buttons Make Compound Shapes Les boutons de mode de forme créent des formes composées diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 3959b3fee5..491c89fae0 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6348,3 +6348,7 @@ breakText Glyphs Glifák Even-Numbered Anchors Páros horgonypontok Minimum angle Legkisebb szög Maximum angle Legnagyobb szög + +# Compound Shapes add-on + Compound Shapes Összetett alakzatok + Shape Mode Buttons Make Compound Shapes Az alakzatmód-gombok összetett alakzatokat hoznak létre diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index fd72bc7e62..ffb0cbf56f 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6230,3 +6230,7 @@ breakText Glyphs Glif Even-Numbered Anchors Jangkar bernomor genap Minimum angle Sudut minimum Maximum angle Sudut maksimum + +# Compound Shapes add-on + Compound Shapes Bentuk majemuk + Shape Mode Buttons Make Compound Shapes Tombol mode bentuk membuat bentuk majemuk diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 4f2035969e..cfd99e62b3 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5984,3 +5984,7 @@ breakText Glyphs Glifi Even-Numbered Anchors Ancoraggi pari Minimum angle Angolo minimo Maximum angle Angolo massimo + +# Compound Shapes add-on + Compound Shapes Forme composte + Shape Mode Buttons Make Compound Shapes I pulsanti dei metodi forma creano forme composte diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9f089ecf4b..5da2097f26 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -6049,3 +6049,7 @@ breakText Glyphs 字形 Even-Numbered Anchors 偶数番目のアンカー Minimum angle 最小角度 Maximum angle 最大角度 + +# Compound Shapes add-on + Compound Shapes 複合シェイプ + Shape Mode Buttons Make Compound Shapes シェイプモードボタンで複合シェイプを作成 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 78da64abc0..b9f4a70a09 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6375,3 +6375,7 @@ font-script Japanese იაპონური Even-Numbered Anchors ლუწი საყრდენი წერტილები Minimum angle მინიმალური კუთხე Maximum angle მაქსიმალური კუთხე + +# Compound Shapes add-on + Compound Shapes შედგენილი ფიგურები + Shape Mode Buttons Make Compound Shapes ფიგურის რეჟიმის ღილაკები ქმნის შედგენილ ფიგურებს diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 3e99b509bc..ac5d1193a7 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5945,3 +5945,7 @@ breakText Glyphs 글리프 Even-Numbered Anchors 짝수 번째 앵커 Minimum angle 최소 각도 Maximum angle 최대 각도 + +# Compound Shapes add-on + Compound Shapes 컴파운드 모양 + Shape Mode Buttons Make Compound Shapes 모양 모드 버튼으로 컴파운드 모양 만들기 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 7f7818c545..62385d6c98 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6274,3 +6274,7 @@ breakText Glyphs Glyphs Even-Numbered Anchors Even ankerpunten Minimum angle Minimale hoek Maximum angle Maximale hoek + +# Compound Shapes add-on + Compound Shapes Samengestelde vormen + Shape Mode Buttons Make Compound Shapes Vormmodus-knoppen maken samengestelde vormen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 56127f0525..908f36c948 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -6219,3 +6219,7 @@ breakText Glyphs Glify Even-Numbered Anchors Punkty parzyste Minimum angle Kąt minimalny Maximum angle Kąt maksymalny + +# Compound Shapes add-on + Compound Shapes Kształty złożone + Shape Mode Buttons Make Compound Shapes Przyciski trybów kształtu tworzą kształty złożone diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 7f68c5c7f6..eb376906ca 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6437,3 +6437,7 @@ swatch Yellow Green Verde-amarelado Even-Numbered Anchors Âncoras Pares Minimum angle Ângulo Mínimo Maximum angle Ângulo Máximo + +# Compound Shapes add-on + Compound Shapes Formas Compostas + Shape Mode Buttons Make Compound Shapes Os Botões de Modo de Forma Criam Formas Compostas diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 10426b2efd..d700736c6c 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6453,3 +6453,7 @@ shape Open Открытый Even-Numbered Anchors Чётные опорные точки Minimum angle Минимальный угол Maximum angle Максимальный угол + +# Compound Shapes add-on + Compound Shapes Составные фигуры + Shape Mode Buttons Make Compound Shapes Кнопки режимов фигур создают составные фигуры diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1d2d9b03e2..85f4812d15 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6420,3 +6420,7 @@ digits Hindi Hindi Even-Numbered Anchors Jämna ankare Minimum angle Minsta vinkel Maximum angle Största vinkel + +# Compound Shapes add-on + Compound Shapes Sammansatta former + Shape Mode Buttons Make Compound Shapes Formlägesknapparna skapar sammansatta former diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 133538fe9e..5c6446de73 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6321,3 +6321,7 @@ breakText Glyphs Glifler Even-Numbered Anchors Çift Numaralı Çapalar Minimum angle En Küçük Açı Maximum angle En Büyük Açı + +# Compound Shapes add-on + Compound Shapes Bileşik Şekiller + Shape Mode Buttons Make Compound Shapes Şekil Modu Düğmeleri Bileşik Şekiller Yapar diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 95724a3d75..4bb7083401 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5964,3 +5964,7 @@ breakText Glyphs Гліфи Even-Numbered Anchors Парні опорні точки Minimum angle Мінімальний кут Maximum angle Максимальний кут + +# Compound Shapes add-on + Compound Shapes Складені фігури + Shape Mode Buttons Make Compound Shapes Кнопки режимів фігур створюють складені фігури diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 93113bc392..330792405e 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5965,3 +5965,7 @@ breakText Glyphs Glyph Even-Numbered Anchors Điểm neo số chẵn Minimum angle Góc tối thiểu Maximum angle Góc tối đa + +# Compound Shapes add-on + Compound Shapes Hình phức hợp + Shape Mode Buttons Make Compound Shapes Nút chế độ hình dạng tạo hình phức hợp diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 20ec647964..48f040a9cb 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -6205,3 +6205,7 @@ breakText Glyphs 字形 Even-Numbered Anchors 偶数锚点 Minimum angle 最小角度 Maximum angle 最大角度 + +# Compound Shapes add-on + Compound Shapes 复合形状 + Shape Mode Buttons Make Compound Shapes 形状模式按钮创建复合形状 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 7dbb11507f..f0c659b50a 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -6002,3 +6002,7 @@ breakText Glyphs 字符 Even-Numbered Anchors 偶數錨點 Minimum angle 最小角度 Maximum angle 最大角度 + +# Compound Shapes add-on + Compound Shapes 複合形狀 + Shape Mode Buttons Make Compound Shapes 形狀模式按鈕製作複合形狀 diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 2d134f76f8..e9776e78f4 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -494,6 +494,7 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option flag(&mut app.ui.task_bar), + "window.pathfinder.compoundShapes" => flag(&mut app.ui.shape_modes_compound), "window.taskBar.pin" => { let place = &mut app.ui.task_bar_place; opt_bool(p, "pinned").map(|pinned| { diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 2dd1051b12..673ceb81fd 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -79,6 +79,7 @@ pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { crate::toolbar::strips(&app.ui, toolbar).iter().any(|f| f.tools.iter().any(|id| id == tool)) } "window.taskBar" => app.ui.task_bar, + "window.pathfinder.compoundShapes" => app.ui.shape_modes_compound, "window.taskBar.pin" => app.ui.task_bar_place.pinned, "window.panel" => { let panel = p.get("panel").and_then(Value::as_str).unwrap_or(""); diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 02fd4ba5f5..44627725df 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -523,6 +523,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ), ("window.toolbar.list", "List Toolbars", "", "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots}]"), ("window.taskBar", "Contextual Task Bar", "", "{}"), + ( + "window.pathfinder.compoundShapes", + "Shape Mode Buttons Make Compound Shapes", + "", + "{} toggles the Compound Shapes add-on's setting: on, the Pathfinder panel's Shape Mode buttons make a compound shape and Alt-click gives the permanent Pathfinder result; off (the default), the other way round. Members of a compound shape selected always take the mode", + ), ( "window.taskBar.pin", "Pin Bar Position", diff --git a/crates/ui-egui/src/panels/pathfinder.rs b/crates/ui-egui/src/panels/pathfinder.rs index 4d08938c53..97959ed4a8 100644 --- a/crates/ui-egui/src/panels/pathfinder.rs +++ b/crates/ui-egui/src/panels/pathfinder.rs @@ -77,12 +77,19 @@ fn button(ui: &mut Ui, icon: &str, tip: &str, selected: bool, n: usize, min: usi } /// A Shape Mode button clicked: Alt makes a compound shape of the selection in `mode`; with -/// members of compound shapes selected they take `mode`; otherwise operation `op` runs. +/// members of compound shapes selected they take `mode`; otherwise operation `op` runs. With the +/// Compound Shapes add-on's setting on, a click on the selection (not on members) makes the +/// compound shape and Alt gives the permanent result. fn shape_mode(app: &mut VectorcraftApp, ui: &Ui, op: &str, mode: ShapeMode, members: bool) { - if ui.input(|i| i.modifiers.alt) { + let alt = ui.input(|i| i.modifiers.alt); + if members { + if alt { + crate::menus::invoke(app, "object.compoundShape.make", json!({"mode": mode.name()})); + } else { + crate::menus::invoke(app, "object.compoundShape.setMode", json!({"mode": mode.name()})); + } + } else if alt != app.ui.shape_modes_compound { crate::menus::invoke(app, "object.compoundShape.make", json!({"mode": mode.name()})); - } else if members { - crate::menus::invoke(app, "object.compoundShape.setMode", json!({"mode": mode.name()})); } else { run(app, op); } @@ -588,4 +595,68 @@ mod tests { assert_eq!(app.last_pathfinder, None); assert!(!crate::menus::enabled(&app, "pathfinder.repeat")); } + + /// How many compound shapes the active document holds. + fn compound_shapes(app: &VectorcraftApp) -> usize { + let mut n = 0; + app.session.active().unwrap().doc.walk(|node| n += usize::from(node.is_compound_shape())); + n + } + + /// Off (the default) a Shape Mode click is the permanent Pathfinder result and Alt-click makes a + /// compound shape; with the Compound Shapes add-on's setting on it is the other way round. + #[test] + fn the_compound_shapes_setting_swaps_click_and_alt_on_the_shape_modes() { + // Off: unchanged. + let mut app = two_squares(); + assert!(!app.ui.shape_modes_compound); + click_button(&mut app, "Unite"); + assert_eq!((objects(&app).len(), compound_shapes(&app)), (1, 0), "a click is permanent"); + let mut app = two_squares(); + click_button_with_modifiers(&mut app, "Unite", egui::Modifiers::ALT); + assert_eq!(compound_shapes(&app), 1, "Alt makes a compound shape"); + + // On: a click makes the compound shape, Alt the permanent result. + let mut app = two_squares(); + app.run("window.pathfinder.compoundShapes", json!({})).unwrap(); + assert!(app.ui.shape_modes_compound); + assert_eq!(crate::menus::checked(&app, "window.pathfinder.compoundShapes", &serde_json::Value::Null), Some(true)); + click_button(&mut app, "Unite"); + assert_eq!(compound_shapes(&app), 1, "a click makes a compound shape"); + let mut app = two_squares(); + app.run("window.pathfinder.compoundShapes", json!({})).unwrap(); + click_button_with_modifiers(&mut app, "Unite", egui::Modifiers::ALT); + assert_eq!((objects(&app).len(), compound_shapes(&app)), (1, 0), "Alt is permanent"); + + // Toggled off again, and the check mark follows. + app.run("window.pathfinder.compoundShapes", json!({})).unwrap(); + assert!(!app.ui.shape_modes_compound); + assert_eq!(crate::menus::checked(&app, "window.pathfinder.compoundShapes", &serde_json::Value::Null), Some(false)); + } + + /// Members of a compound shape that are selected take the clicked mode whatever the setting says. + #[test] + fn selected_members_take_the_mode_with_the_setting_on() { + let mut app = two_squares(); + app.run("window.pathfinder.compoundShapes", json!({})).unwrap(); + click_button(&mut app, "Unite"); + let shape = app.session.active().unwrap().selection.objects[0]; + let front = app.session.active().unwrap().doc.node(shape).unwrap().children().unwrap().last().unwrap().id; + app.run("select.set", json!({"ids": [front.0]})).unwrap(); + click_button(&mut app, "Minus Front"); + assert_eq!(compound_shapes(&app), 1, "no second compound shape"); + assert_eq!(vectorcraft_engine::cmd::selected_member_modes(&app.session), [ShapeMode::Subtract]); + } + + /// The setting is kept with the preferences; preferences saved before it read as off. + #[test] + fn the_compound_shapes_setting_is_saved_and_older_preferences_read_as_off() { + let mut app = two_squares(); + app.run("window.pathfinder.compoundShapes", json!({})).unwrap(); + let mut saved = serde_json::to_value(&app.ui).unwrap(); + assert_eq!(saved["shape_modes_compound"], json!(true)); + assert!(serde_json::from_value::(saved.clone()).unwrap().shape_modes_compound); + saved.as_object_mut().unwrap().remove("shape_modes_compound"); + assert!(!serde_json::from_value::(saved).unwrap().shape_modes_compound); + } } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 77c19753fc..2baf6f6ee7 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -366,6 +366,10 @@ pub struct UiState { /// starts under the selection at every launch. #[serde(skip)] pub task_bar_place: TaskBarPlace, + /// The Pathfinder panel's Shape Mode buttons make a compound shape on a click, and give the + /// permanent Pathfinder result on Alt-click (off, the default: the other way round). + #[serde(default)] + pub shape_modes_compound: bool, /// The locked objects under the pointer at the last right-click on the canvas, with the /// document's `uid`: the context menu's Unlock submenu lists them while the menu is open. Not /// saved. @@ -935,6 +939,7 @@ impl Default for UiState { toolbar_advanced: false, task_bar: true, task_bar_place: TaskBarPlace::default(), + shape_modes_compound: false, context_locked: None, context_intertwine: None, slot_tool: Default::default(), diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 191be79756..a0e392cd6c 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -402,6 +402,12 @@ Bar Position (`window.taskBar.reset`), which unpins it and puts it back under th Panel. As in Illustrator, neither the position nor the pin is saved: each launch starts with the bar under the selection. +The Compound Shapes add-on's setting, `window.pathfinder.compoundShapes` (omitted params toggle; checked while on; kept with the +preferences; off by default), swaps what a click and an Alt-click do on the Pathfinder panel's Shape Mode buttons: on, a click makes a +compound shape (`object.compoundShape.make`) and Alt-click gives the permanent Pathfinder result. Selected members of a compound +shape always take the clicked mode (`object.compoundShape.setMode`). Its submenu, Object › Plug-ins › Compound Shapes, also lists +Make, Release and Expand Compound Shape. + The Free Transform widget: while the Free Transform tool (E) is active, a small box at the canvas's top left holds Constrain over the tool's three modes, Free Transform, Perspective Distort and Free Distort. The buttons set the tool's options, as `tool.setOption {key: "mode", value: "free"|"perspective"|"distort"}` and `{key: "constrain", value}` do: diff --git a/docs/gaps.md b/docs/gaps.md index 68d08df0b7..7b458a347e 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -31,6 +31,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | 2026-11-04 | minor | Contour add-on (beyond Illustrator): drag away from a selected shape's edge to grow a live copy of it, or toward the inside to shrink it; the copy carries a live Offset Path effect, so it stays editable until Bake (Expand Appearance), a second drag changes the same Contour instead of nesting one, and a floating bar sets the distance and the Sharp, Round or Square corners. `addon.contour.set` is the command behind it. It is a built-in add-on: Object › Plug-ins › Contour, and its own heading in All Tools, with no default shortcut or toolbar slot. A VectorCraft design built on Offset Path; no other application was inspected. Scores and estimates unchanged. | | 2026-11-04 | minor | Contour tool (beyond Illustrator): drag away from a selected shape's edge to grow a live copy of it, or toward the inside to shrink it; the copy carries a live Offset Path effect, so it stays editable until Bake (Expand Appearance), a second drag changes the same Contour instead of nesting one, and a floating bar sets the distance and the Sharp, Round or Square corners. `object.contour` is the command behind it. A VectorCraft design built on Offset Path; no other application was inspected. Scores and estimates unchanged. | | 2026-11-05 | minor | G12: Hyphenation › Default Language sets the language of new type unless Document Setup chose one, stored as a tag; each run hyphenates in its own language, English only so far, so 2 Preferences options stay unused (#394) | +| 2026-11-05 | minor | Compound Shapes add-on (beyond Illustrator): Object › Plug-ins › Compound Shapes lists Make, Release and Expand Compound Shape, and holds a setting, off by default, that makes the Pathfinder panel's Shape Mode buttons make a compound shape on a click and give the permanent result on Alt-click (the default is the reverse). Selected members of a compound shape always take the clicked mode. The setting is `window.pathfinder.compoundShapes`; no existing behavior changes while it is off. Scores and estimates unchanged. | | 2026-11-03 | minor | New gradients use CMYK default stops in CMYK documents, including Gradient tool creation. Scores and estimates unchanged. | | 2026-11-02 | minor | Font-family fields step selected text with the mouse wheel (#5253); no scored gap or estimate reassessed. | | 2026-10-24 | minor | G12: General › Corner Radius is the Rounded Rectangle tool's radius, a change while the tool is active reaches it, and the radius ↑/↓ set while drawing (or a Tool Options value) becomes the preference, within 0–1296 pt (#394, `crates/engine/src/tests/constrain_tools.rs`); no entry closed, estimate unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 53c26cd357..50e1b0cf23 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-05 · **Change:** minor (Contour add-on, beyond Illustrator; scores and estimates unchanged; Optical kerning spaces pairs by the font's own stem spacing instead of a fixed tight gap; 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-05 · **Change:** minor (Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; Optical kerning spaces pairs by the font's own stem spacing instead of a fixed tight gap; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -483,6 +483,7 @@ since 2026-10-01. | **Scrubby numeric fields** | beyond Illustrator | As in Photoshop, dragging a numeric field's label (`W:`, `Opacity:`, the Character panel's icons) left or right steps its value live; one undo step per drag, Escape cancels (#400) | | **Align Stroke on live type** | beyond Illustrator | The Stroke panel's Align Stroke works on type's character stroke: inside or outside the glyphs without Create Outlines, the type staying editable (as InDesign does; users have asked Illustrator for it since 2010, e.g. [redd.it/1dwhos6](https://redd.it/1dwhos6)). Canvas, PDF and EPS clip it to its side of the glyphs; SVG keeps the text live and draws the stroke on the glyph outlines (#2294) | | **Contour add-on** | beyond Illustrator | Drag away from a selected shape's edge to grow a live copy of it, or toward the inside to shrink it (Shift: whole points); the copy carries a live Offset Path effect so it stays editable, with its own fill and stroke, until Bake (Expand Appearance). A second drag on a selected Contour changes it instead of nesting another; Escape cancels. A floating bar above the selection sets the distance and the corners (Sharp, Round, Square); `addon.contour.set` makes or changes one over MCP and the control channel. The tool is in Object › Plug-ins › Contour and under its own heading in All Tools, with no default shortcut or toolbar slot. Two Contours baked and combined with Minus Front give a border with a gap. Paths, shapes and compound paths only; type isn't offset. Tests: `crates/engine/src/cmd/addons/contour/tests.rs`, `crates/ui-egui/src/canvas/tests.rs` | +| **Compound Shapes add-on** | beyond Illustrator | Object › Plug-ins › Compound Shapes puts Make, Release and Expand Compound Shape in the menus, and holds a setting (off by default) that swaps the Pathfinder panel's Shape Mode buttons: a click makes a compound shape and Alt-click gives the permanent result. Selected members of a compound shape always take the clicked mode; the setting is kept with the preferences. Tests: `panels::pathfinder::tests` in `crates/ui-egui/src/panels/pathfinder.rs` | ## Evidence: what ships today, by area @@ -1655,6 +1656,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | 2026-11-04 | minor | Contour tool (beyond Illustrator): drag away from a selected shape's edge to grow a live copy of it, or toward the inside to shrink it; the copy carries a live Offset Path effect, so it stays editable until Bake (Expand Appearance), a second drag changes the same Contour instead of nesting one, and a floating bar sets the distance and the Sharp, Round or Square corners. `object.contour` is the command behind it. A VectorCraft design built on Offset Path; no other application was inspected. Scores and estimates unchanged. | | 2026-11-05 | minor | View & navigation: document tabs are reordered by dragging them along the tab strip (`document.move`, #5663); evidence added; scores unchanged. | | 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-11-05 | minor | Compound Shapes add-on (beyond Illustrator): Object › Plug-ins › Compound Shapes lists Make, Release and Expand Compound Shape, and holds a setting, off by default, that makes the Pathfinder panel's Shape Mode buttons make a compound shape on a click and give the permanent result on Alt-click (the default is the reverse). Selected members of a compound shape always take the clicked mode. The setting is `window.pathfinder.compoundShapes`; no existing behavior changes while it is off. Scores and estimates unchanged. | | 2026-11-01 | minor | Batch Trace Folder (`imageTrace.batchFolder`, #4921); evidence added; scores unchanged. | | 2026-11-01 | minor | Copy and paste ruler guides (#3226); evidence added; scores unchanged. | | 2026-11-04 | minor | Area type vertical alignment buttons in the Properties panel's Paragraph section and the Control panel, off for columns, rows and threaded frames (#3759); evidence added; scores unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index ac9cf181b4..fca5458f04 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Contour add-on, beyond Illustrator; scores and estimates unchanged; Select by Artboards add-on selects by overlap, inside or outside several artboards; Cmd+Space keeps the active drawing cursor during its drag; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; Select by Artboards add-on selects by overlap, inside or outside several artboards; Cmd+Space keeps the active drawing cursor during its drag; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) ## Feature submission evidence @@ -442,6 +442,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | 2026-11-05 | minor | Document tabs are reordered by dragging them along the tab strip (`document.move`, #5663). | | 2026-11-04 | minor | Path Precision Tools add-on (a VectorCraft addition): Set Corners… rounds only the corners in an angle range (#5545); scores and estimates unchanged | | 2026-11-04 | minor | Path Precision Tools add-on (a VectorCraft addition): Set Corners… rounds all, the odd-numbered or the even-numbered anchors (#5546); scores and estimates unchanged | +| 2026-11-05 | minor | Compound Shapes add-on (beyond Illustrator): Object › Plug-ins › Compound Shapes lists Make, Release and Expand Compound Shape, and holds a setting, off by default, that makes the Pathfinder panel's Shape Mode buttons make a compound shape on a click and give the permanent result on Alt-click (the default is the reverse). Selected members of a compound shape always take the clicked mode. The setting is `window.pathfinder.compoundShapes`; no existing behavior changes while it is off. Scores and estimates unchanged. | | 2026-11-04 | minor | New Document: the units chosen in Preset Details belong to the chosen document, as the pane's options are listed "for the selected preset" ([public source](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/create-and-save-custom-document-presets.html)); the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units (#2078); scores and estimates unchanged | | 2026-11-01 | minor | Object › Image Trace › Batch Trace Folder asks for a source and a destination folder and traces each image into it (#4921); scores and estimates unchanged | | 2026-11-01 | minor | Edit › Copy and Cut take the selected ruler guides, with the objects or alone; pasting puts them on the layer new art goes to, moved as the objects are (alone: where they were), Paste in Place onto the active artboard and Paste on All Artboards onto each (#3226); scores and estimates unchanged | From ec13f54f3c82d1f115e487482ee3fd52208d18cd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 22:39:53 -0800 Subject: [PATCH 048/196] Layers: the shown document's thumbnails are not held up by another document's queue The Layers and Links panels share one thumbnail thread across documents, and it ran its jobs in the order they came. Rows of a document left with a long queue held up the thumbnails of the next document shown. The thumbnail thread can now drop the jobs it has not started for some slots. Each frame the Layers and Links panels name the document they show; when it changes, the queued jobs of every other document are dropped, and when no document is open, all of them are. Those rows ask for their thumbnails again when their document shows again, and the thumbnails already made are kept. The Navigator and the arrange panes do not use the new call. With 150 rows of 20,000-anchor paths queued for one document, the 8 rows of such paths of the next document shown get their thumbnails in 153 ms instead of 3,265 ms (debug test build, median of three runs). --- crates/ui-egui/src/panels/layers.rs | 3 +- crates/ui-egui/src/panels/layers/tests.rs | 36 +++++ crates/ui-egui/src/panels/layers/thumbs.rs | 146 +++++++++++++++++++++ crates/ui-egui/src/panels/links.rs | 1 + crates/ui-egui/src/thumb_worker.rs | 57 +++++++- docs/target-app-parity.md | 1 + 6 files changed, 237 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index 8f87786892..2a737d2fb8 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -69,7 +69,7 @@ use model::{push_rows, rows_of_doc}; use rows::{drag_ghost, key, rename_id, resolve_click, row}; #[cfg(test)] use thumbs::THUMBS; -pub(crate) use thumbs::{ThumbSource, node_arc, real_thumb, thumb_options}; +pub(crate) use thumbs::{ThumbSource, node_arc, real_thumb, show_thumbs_of, thumb_options}; /// Width of the eye and the lock columns. const COLUMN: f32 = 25.0; @@ -184,6 +184,7 @@ pub(crate) const ROW_KEYS: &str = "ly-keys"; /// The Layers panel: the layer tree with its click, drag and rename rules and the bottom buttons; Delete/Backspace after a row click delete the highlighted rows. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); + show_thumbs_of(app.session.active().map(|st| st.uid)); let Some(st) = app.session.active() else { return }; // A rename belongs to the document it started in (node ids are per document): drop it when // another document shows, so it can't rename that document's node with the same id. diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index 297afd6936..6f65e5d8c7 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -239,6 +239,42 @@ fn row_thumbnails_wait_for_the_end_of_a_drag() { assert_eq!(renders(), after, "once"); } +#[test] +fn the_row_thumbnails_follow_the_document_shown_and_none_once_it_closes() { + let (mut app, _, _) = two_rects(); + let ctx = egui::Context::default(); + let showing = || THUMBS.with(|c| c.borrow().showing); + frame(&mut app, &ctx, vec![], false); + let first = app.session.active().map(|st| st.uid); + assert_eq!(showing(), first); + // With no thumbnails drawn, the panel still tells which document it shows. + let p = &mut app.ui.layers_panel; + (p.thumb_layers, p.thumb_groups, p.thumb_objects) = (false, false, false); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap(); + frame(&mut app, &ctx, vec![], false); + let second = app.session.active().map(|st| st.uid); + assert_ne!(second, first); + assert_eq!(showing(), second, "the new document's rows are drawn"); + for _ in 0..2 { + app.session.execute("file.close", &json!({"index": 0})).unwrap(); + } + frame(&mut app, &ctx, vec![], false); + assert_eq!(showing(), None, "no document is shown once both close"); + + // The Links panel alone does the same. + let links = |app: &mut VectorcraftApp| { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::super::links::show(app, ui)); + out.textures_delta.clear(); + }; + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + links(&mut app); + assert_eq!(showing(), app.session.active().map(|st| st.uid)); + app.session.execute("file.close", &json!({"index": 0})).unwrap(); + links(&mut app); + assert_eq!(showing(), None, "the Links panel shows no document"); +} + #[test] fn clicking_a_target_circle_targets_the_layer() { let (mut app, layer, [a, b]) = two_rects(); diff --git a/crates/ui-egui/src/panels/layers/thumbs.rs b/crates/ui-egui/src/panels/layers/thumbs.rs index db303a11c8..78e1217c2d 100644 --- a/crates/ui-egui/src/panels/layers/thumbs.rs +++ b/crates/ui-egui/src/panels/layers/thumbs.rs @@ -55,6 +55,8 @@ pub(super) struct Thumbs { pending: HashMap<(u64, NodeId), (Weak, u32)>, worker: Option>, worker_started: bool, + /// The uid of the document whose rows were last drawn: the worker holds jobs for it alone. + pub(super) showing: Option, settle: Settle, /// (pass, ms, count) rendered on the UI thread in that pass. spent: (u64, f64, u32), @@ -275,6 +277,24 @@ impl Thumbs { } } + /// The panels draw the rows of document `uid` (None: no document). When that is another + /// document than before, the worker drops the jobs it has not started for every other + /// document, so they don't hold up this one's thumbnails, and those rows are asked for again + /// when their document shows again. The thumbnails made already stay. + pub(super) fn show(&mut self, uid: Option) { + if self.showing == uid { + return; + } + self.showing = uid; + self.pending.retain(|key, _| Some(key.0) == uid); + if let Some(w) = &self.worker + && !w.discard(move |key| Some(key.0) != uid) + { + self.worker = None; + self.pending.clear(); + } + } + /// Keep the thumbnail `d` the worker finished. fn receive(&mut self, ctx: &egui::Context, d: Done) { let (key, node, px) = d.key; @@ -305,6 +325,7 @@ impl Thumbs { for d in done { self.receive(ctx, d); } + self.show(Some(src.uid)); let key = (src.uid, n.id); let pass = ctx.cumulative_pass_nr(); let (fresh, light) = match self.entries.get_mut(&key) { @@ -356,6 +377,12 @@ impl Thumbs { } } +/// The Layers or Links panel shows the rows of document `uid` in this frame (None: no document +/// is open), whether or not a thumbnail is drawn; see [`Thumbs::show`]. +pub(crate) fn show_thumbs_of(uid: Option) { + THUMBS.with(|c| c.borrow_mut().show(uid)); +} + /// A real rendered thumbnail of row `n`, cached by node identity (unchanged nodes keep their `Arc` /// allocation, so the address is a free change detector). Only rendered for visible rows; see /// [`Thumbs::texture`] for when. @@ -729,6 +756,125 @@ mod tests { assert!(thumbs.pending.is_empty()); } + /// A document of `rows` paths of 5,000 anchors on its layer, and the paths as the layer holds + /// them. + fn long_paths(rows: usize) -> (Arc, Vec>) { + let mut doc = Document::new(200.0, 200.0); + let layer = doc.layers.first().map(|l| l.id); + let ids: Vec = (0..rows) + .map(|_| { + let id = doc.alloc_id(); + doc.insert(layer, usize::MAX, path(id.0, 5_000)).unwrap(); + id + }) + .collect(); + let doc = Arc::new(doc); + let nodes = ids.iter().filter_map(|id| node_arc(&doc, *id)).collect(); + (doc, nodes) + } + + /// Keep the worker of `thumbs` busy with a job of row (0, 0) until the sender returned sends, + /// so the jobs submitted meanwhile wait in its queue. + fn hold(thumbs: &Thumbs) -> std::sync::mpsc::Sender<()> { + let (started, running) = std::sync::mpsc::channel::<()>(); + let (release, held) = std::sync::mpsc::channel::<()>(); + let key = (0, NodeId(0)); + let job: crate::thumb_worker::JobFn = Box::new(move |_| { + started.send(()).ok(); + held.recv().ok(); + None + }); + assert!(thumbs.worker.as_ref().is_some_and(|w| w.submit(key, (key, Weak::new(), 1), job))); + running.recv().expect("the job starts"); + release + } + + /// The next job `thumbs`'s worker finishes, checked against the thumbnail of the same node in + /// `rows` of `doc` made on this thread, then kept. + fn receive_checked(ctx: &egui::Context, thumbs: &mut Thumbs, uid: u64, doc: &Document, rows: &[Arc]) { + let done = thumbs.worker.as_ref().and_then(ThumbWorker::wait).expect("the worker finishes a job"); + assert_eq!(done.key.0.0, uid, "a job of document {uid} is done next"); + let n = rows.iter().find(|n| n.id == done.key.0.1).expect("one of its rows"); + let there = done.img.as_ref().expect("the worker draws the path"); + let here = render_thumb(&mut vectorcraft_render::Renderer::new(), doc, n, 24).expect("this thread draws the path"); + assert!(here.pixels.chunks(4).any(|p| p[3] > 0), "the thumbnail shows the path"); + assert_eq!((there.width, there.height, &there.pixels), (here.width, here.height, &here.pixels), "the same pixels"); + thumbs.receive(ctx, done); + } + + #[test] + fn the_shown_documents_thumbnails_are_made_before_the_queued_ones_of_another() { + let ctx = egui::Context::default(); + let Some(worker) = ThumbWorker::start(&ctx, "test") else { return }; + let mut thumbs = Thumbs { worker: Some(worker), worker_started: true, ..Default::default() }; + let (a, a_rows) = long_paths(3); + let (b, b_rows) = long_paths(2); + let release = hold(&thumbs); + let src_a = ThumbSource { uid: 1, revision: 1, doc: &a, busy: false }; + for n in &a_rows { + assert!(thumbs.texture(&ctx, &src_a, n, 24).is_none()); + } + assert_eq!(thumbs.pending.len(), 3, "document 1's rows wait on the worker"); + // Document 2 shows before the worker gets to them. + let src_b = ThumbSource { uid: 2, revision: 1, doc: &b, busy: false }; + for n in &b_rows { + assert!(thumbs.texture(&ctx, &src_b, n, 24).is_none()); + } + assert_eq!(thumbs.pending.keys().map(|k| k.0).collect::>(), [2, 2], "only the shown document's rows are pending"); + release.send(()).expect("the held job is waiting"); + let held = thumbs.worker.as_ref().and_then(ThumbWorker::wait).expect("the held job finishes"); + assert_eq!(held.key.0, (0, NodeId(0))); + for _ in &b_rows { + receive_checked(&ctx, &mut thumbs, 2, &b, &b_rows); + } + for n in &b_rows { + assert!(thumbs.texture(&ctx, &src_b, n, 24).is_some(), "the shown document's thumbnails are shown"); + } + // Shown again, document 1's rows are asked for again and come back. + for n in &a_rows { + assert!(thumbs.texture(&ctx, &src_a, n, 24).is_none()); + } + assert_eq!(thumbs.pending.keys().filter(|k| k.0 == 1).count(), 3); + for _ in &a_rows { + receive_checked(&ctx, &mut thumbs, 1, &a, &a_rows); + } + for n in &a_rows { + assert!(thumbs.texture(&ctx, &src_a, n, 24).is_some()); + } + // Document 2's thumbnails were kept: showing it again asks for nothing. + for n in &b_rows { + assert!(thumbs.texture(&ctx, &src_b, n, 24).is_some()); + } + assert!(thumbs.pending.is_empty()); + assert_eq!(thumbs.renders, 0, "none was made on this thread"); + } + + #[test] + fn the_queued_thumbnails_of_a_closed_document_are_dropped() { + let ctx = egui::Context::default(); + let Some(worker) = ThumbWorker::start(&ctx, "test") else { return }; + let mut thumbs = Thumbs { worker: Some(worker), worker_started: true, ..Default::default() }; + let (a, a_rows) = long_paths(3); + let release = hold(&thumbs); + let src_a = ThumbSource { uid: 1, revision: 1, doc: &a, busy: false }; + for n in &a_rows { + thumbs.texture(&ctx, &src_a, n, 24); + } + // The document closes and no other shows. + thumbs.show(None); + assert!(thumbs.pending.is_empty()); + // A job queued after it, straight on the worker, comes back next. + let (b, b_rows) = long_paths(1); + let (doc, node) = (b.clone(), b_rows[0].clone()); + let key = (2, node.id); + let job: crate::thumb_worker::JobFn = Box::new(move |r| render_thumb(r, &doc, &node, 24)); + assert!(thumbs.worker.as_ref().is_some_and(|w| w.submit(key, (key, Arc::downgrade(&b_rows[0]), 24), job))); + release.send(()).expect("the held job is waiting"); + let held = thumbs.worker.as_ref().and_then(ThumbWorker::wait).expect("the held job finishes"); + assert_eq!(held.key.0, (0, NodeId(0))); + receive_checked(&ctx, &mut thumbs, 2, &b, &b_rows); + } + #[test] fn an_instance_of_a_long_symbols_thumbnail_is_made_on_the_worker_and_matches_one_made_here() { let ctx = egui::Context::default(); diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index 9fc91f5068..d924d06f3f 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -316,6 +316,7 @@ fn click(app: &mut VectorcraftApp, ctx: &egui::Context, rows: &[Value], id: u64, pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); let o = options(ui.ctx()); + super::layers::show_thumbs_of(app.session.active().map(|st| st.uid)); let Some(cache) = cached(app, ui.ctx(), &o) else { widgets::dim_label(ui, tl!("No document")); return; diff --git a/crates/ui-egui/src/thumb_worker.rs b/crates/ui-egui/src/thumb_worker.rs index ceea0b3cef..c754cd786d 100644 --- a/crates/ui-egui/src/thumb_worker.rs +++ b/crates/ui-egui/src/thumb_worker.rs @@ -32,11 +32,20 @@ struct Job { run: JobFn, } +/// Which slots' jobs [`ThumbWorker::discard`] drops. +type SlotTest = Box bool + Send>; + +/// What a panel sends its worker: a job, or the slots whose jobs not started yet are dropped. +enum Msg { + Job(Job), + Discard(SlotTest), +} + /// A render thread for one panel's thumbnails. Jobs go in by slot (the Navigator has one, the /// Layers panel one per row): a job not started yet is replaced by a newer one for its slot, so /// only the latest image of anything is drawn. pub struct ThumbWorker { - tx: Sender>, + tx: Sender>, rx: Receiver>, } @@ -53,7 +62,7 @@ impl ThumbWorker { /// Spawn the thread. pub(crate) fn start(ctx: &egui::Context, name: &str) -> Option { - let (tx, jobs) = channel::>(); + let (tx, jobs) = channel::>(); let (done_tx, rx) = channel::>(); let ctx = ctx.clone(); std::thread::Builder::new() @@ -61,9 +70,12 @@ impl ThumbWorker { .spawn(move || { let mut r = Renderer::new(); let mut queue: VecDeque> = VecDeque::new(); - let add = |queue: &mut VecDeque>, job: Job| match queue.iter_mut().find(|j| j.slot == job.slot) { - Some(old) => *old = job, - None => queue.push_back(job), + let add = |queue: &mut VecDeque>, msg: Msg| match msg { + Msg::Job(job) => match queue.iter_mut().find(|j| j.slot == job.slot) { + Some(old) => *old = job, + None => queue.push_back(job), + }, + Msg::Discard(which) => queue.retain(|j| !which(&j.slot)), }; loop { if queue.is_empty() { @@ -91,7 +103,15 @@ impl ThumbWorker { /// thread is gone: the caller renders on the UI thread from now on. #[must_use] pub fn submit(&self, slot: S, key: K, run: JobFn) -> bool { - self.tx.send(Job { slot, key, run }).is_ok() + self.tx.send(Msg::Job(Job { slot, key, run })).is_ok() + } + + /// Drop the jobs not started yet whose slot `which` picks, so they don't hold up the jobs + /// submitted after them; they never come back from [`ThumbWorker::poll`]. A job already + /// running still finishes. False when the thread is gone, as for [`ThumbWorker::submit`]. + #[must_use] + pub fn discard(&self, which: impl Fn(&S) -> bool + Send + 'static) -> bool { + self.tx.send(Msg::Discard(Box::new(which))).is_ok() } /// The jobs finished since the last call, oldest first; None when the thread is gone (the @@ -169,6 +189,31 @@ mod tests { drop(w); } + #[test] + fn discarded_jobs_do_not_run_and_the_running_one_finishes() { + let Some(w) = ThumbWorker::::start(&egui::Context::default(), "test") else { return }; + let job = |n: u32| -> JobFn { Box::new(move |_| Some(Rendered { width: n, height: 1, pixels: vec![0; 4] })) }; + // A job that holds the thread until it is let go, so the others queue behind it. + let (started, running) = channel::<()>(); + let (release, held) = channel::<()>(); + let blocker: JobFn = Box::new(move |_| { + started.send(()).ok(); + held.recv().ok(); + None + }); + assert!(w.submit(0, 0, blocker)); + running.recv().expect("the first job starts"); + assert!(w.submit(1, 1, job(1))); + assert!(w.submit(2, 2, job(2))); + assert!(w.submit(1, 3, job(3))); + assert!(w.discard(|slot| *slot == 0 || *slot == 1)); + assert!(w.submit(3, 4, job(4))); + release.send(()).expect("the first job is waiting"); + assert_eq!(w.wait().map(|d| d.key), Some(0), "the running job finishes"); + assert_eq!(w.wait().map(|d| d.key), Some(2), "slot 1's jobs were dropped"); + assert_eq!(w.wait().map(|d| d.key), Some(4), "a job submitted after the discard runs"); + } + #[test] fn settles_after_the_document_stays_unchanged() { let ctx = egui::Context::default(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 50e1b0cf23..004188166e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1289,6 +1289,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In the web build the status bar's render and UI times are measured with the browser's `performance.now()`, and the Layers panel stops rendering row thumbnails in a frame once they have taken 8 ms. On the desktop, the Layers panel renders a row's thumbnail on its thumbnail thread when the row's paths, and the paths of its opacity masks that are not disabled, hold more than 2,000 anchors in all. It already did this for the first thumbnail of a row of more than 200 objects. Until its first thumbnail is ready, the row shows boxes at the bounds of up to 41 of its paths, each in its path's solid fill or stroke color or in gray, when its own paths, without its opacity masks, hold at most 2,000 anchors in all, and an empty white box otherwise. With one path of 200,000 anchors, the first frame after the panel opens takes 2.4 ms instead of 393 ms (release build, median of three runs). The same 2,000-anchor limit counts each glyph of type as 4 anchors, each point of a gradient mesh as 1 and every 100 pixels of an image as 1, and a symbol instance or a placed document counts the objects and anchors of the art it shows. A placed document whose file has not been read yet, or a symbol nested more than 8 deep (one that holds an instance of itself, for example), gets its first thumbnail on the thumbnail thread, and so does a row whose art takes more than 20,000 steps to count (each object, subpath, text run and symbol looked at is one step). The first frame after the panel opens takes 2.4 ms instead of 19.8 ms with 5,000 glyphs of point type, 1.8 ms instead of 343 ms with one instance of a symbol of a 200,000-anchor path, 2.0 ms instead of 11.0 ms with a 100 × 100 mesh, and 2.1 ms instead of 274 ms with a placed document of a 200,000-anchor path (release build, median of three runs). + When the Layers or Links panel shows another document's rows, the thumbnail thread drops the row thumbnails it has not started for the documents not shown, and it drops all of them when the Layers or Links panel is open after the last document closes. Those rows ask for their thumbnails again when their document shows again, and the thumbnails already made are kept. With 150 rows of 20,000-anchor paths waiting for another document, the 8 rows of such paths of the document shown get their thumbnails in 153 ms instead of 3,265 ms (debug test build, median of three runs). In the web build, while a pan, zoom or rotation changes the view of a document whose last canvas render took more than 8 ms, the canvas draws the last frame moved with the view, and it renders the art again once the view has been still for 0.2 s. An Alt-drag with the Selection, Direct Selection, Group Selection, Rotate, Scale, Reflect or Shear tool copies the selection on its first move, and the moves after it transform those copies; the previews of the Move, Rotate, Scale, Reflect and Shear dialogs with Copy and Preview on copy the selection once in the same way (#1429). An Alt-drag of objects in perspective with the Perspective Selection tool, and an Alt-drag of a plane widget with that tool or the Perspective Grid tool, copy the objects on the first move, and the moves after it move those copies (#1429). From 7dc66d660a369afe94bce3d3862a88863bc0d1a3 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Thu, 5 Nov 2026 12:24:08 +0530 Subject: [PATCH 049/196] Fix #5526: select images by link status Selection Tools add-on: addon.select.byLinkStatus selects the image objects and placed documents whose link is linked, embedded, missing or modified (one status or several), as links.list reports it. Optional ids limit the search, add adds to the selection, and zoom runs the existing Zoom to Selection in the desktop app. Objects that are hidden, locked, on a template layer or outside the isolated group are left out and returned with the reason. Only the selection changes. Select Linked / Embedded / Missing / Modified are in Object > Plug-ins > Selection Tools and the Links panel menu. Each is off when no image has that status, and Shift adds to the selection. Select by Link Status... lists the images with name, status and format, with a name search, a status filter, checkboxes with All / None and Zoom to Selection. The status bar says what was selected and how many were left out, with plural rows in every catalog. Tests: engine (statuses, ids, add, zoom, skip reasons, bad params), command sweep, and UI (message, list filtering, menu items, Links panel menu, headless dialog frame). Docs: mcp, target-app-parity, ui-parity, roadmap. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/addons/select.rs | 156 +++++++++- crates/engine/src/cmd/addons/select/tests.rs | 176 +++++++++++ crates/engine/src/cmd/links.rs | 2 +- crates/engine/tests/command_sweep.rs | 4 + crates/ui-egui/src/addons/select.rs | 9 +- .../ui-egui/src/addons/select/link_status.rs | 286 ++++++++++++++++++ .../src/addons/select/link_status/tests.rs | 199 ++++++++++++ crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/dialogs.rs | 1 + crates/ui-egui/src/i18n/bg.tsv | 19 ++ crates/ui-egui/src/i18n/bs.tsv | 19 ++ crates/ui-egui/src/i18n/ca.tsv | 19 ++ crates/ui-egui/src/i18n/cs.tsv | 19 ++ crates/ui-egui/src/i18n/da.tsv | 19 ++ crates/ui-egui/src/i18n/de.tsv | 19 ++ crates/ui-egui/src/i18n/el.tsv | 19 ++ crates/ui-egui/src/i18n/es.tsv | 19 ++ crates/ui-egui/src/i18n/fi.tsv | 19 ++ crates/ui-egui/src/i18n/fr.tsv | 19 ++ crates/ui-egui/src/i18n/hu.tsv | 19 ++ crates/ui-egui/src/i18n/id.tsv | 19 ++ crates/ui-egui/src/i18n/it.tsv | 19 ++ crates/ui-egui/src/i18n/ja.tsv | 19 ++ crates/ui-egui/src/i18n/ka.tsv | 19 ++ crates/ui-egui/src/i18n/ko.tsv | 19 ++ crates/ui-egui/src/i18n/nl.tsv | 19 ++ crates/ui-egui/src/i18n/pl.tsv | 19 ++ crates/ui-egui/src/i18n/pt-br.tsv | 19 ++ crates/ui-egui/src/i18n/ru.tsv | 19 ++ crates/ui-egui/src/i18n/sv.tsv | 19 ++ crates/ui-egui/src/i18n/tr.tsv | 19 ++ crates/ui-egui/src/i18n/uk.tsv | 19 ++ crates/ui-egui/src/i18n/vi.tsv | 19 ++ crates/ui-egui/src/i18n/zh-hans.tsv | 19 ++ crates/ui-egui/src/i18n/zh-hant.tsv | 19 ++ crates/ui-egui/src/menus.rs | 2 + crates/ui-egui/src/menus/invoke.rs | 7 +- crates/ui-egui/src/menus/run.rs | 1 + crates/ui-egui/src/menus/state.rs | 2 +- crates/ui-egui/src/panels/links.rs | 14 +- crates/ui-egui/src/state.rs | 6 + docs/mcp.md | 24 ++ docs/roadmap.md | 3 +- docs/target-app-parity.md | 4 +- docs/ui-parity.md | 4 +- 45 files changed, 1370 insertions(+), 25 deletions(-) create mode 100644 crates/ui-egui/src/addons/select/link_status.rs create mode 100644 crates/ui-egui/src/addons/select/link_status/tests.rs diff --git a/crates/engine/src/cmd/addons/select.rs b/crates/engine/src/cmd/addons/select.rs index ce2869abca..4d71895c01 100644 --- a/crates/engine/src/cmd/addons/select.rs +++ b/crates/engine/src/cmd/addons/select.rs @@ -1,31 +1,51 @@ //! Selection Tools (`addon.select.*`), a built-in add-on: Select by Artboards selects the objects -//! overlapping, fully inside or fully outside one or more chosen artboards (#5525). Its submenu -//! (Object › Plug-ins › Selection Tools) and dialog are the UI's. +//! overlapping, fully inside or fully outside one or more chosen artboards (#5525), and Select by +//! Link Status selects the images and placed documents whose file is linked, embedded, missing or +//! modified (#5526), saying which ones it had to leave out and why. Its submenu (Object › Plug-ins +//! › Selection Tools), the Links panel's menu items and the dialogs are the UI's. #[cfg(test)] mod tests; +use std::collections::BTreeSet; + use serde_json::{Value, json}; -use vectorcraft_doc::NodeId; +use vectorcraft_doc::{LockedArtboards, Node, NodeId, NodeKind}; use vectorcraft_geom::Point; -use super::super::select::{on_artboard, selectable}; -use super::super::{CommandSpec, bad, cmd, has_doc, point_indices, text_param}; -use crate::{Result, Session}; +use super::super::links::{Status, statuses}; +use super::super::select::{is_selectable, on_artboard, selectable}; +use super::super::{CommandSpec, bad, checked_ids_param, cmd, has_doc, point_indices, switch_or, text_param}; +use crate::{DocState, Result, Session}; /// How Select by Artboards relates an object to the chosen artboards (`relation`). pub const RELATIONS: [&str; 3] = ["overlap", "inside", "outside"]; +/// The link statuses Select by Link Status takes (`status`): a file found unchanged, pixels kept +/// in the document, a file not found, a file changed since it was read. +pub const LINK_STATUSES: [&str; 4] = ["linked", "embedded", "missing", "modified"]; + pub fn specs() -> Vec { - vec![cmd!( - "addon.select.byArtboards", - "Select by Artboards", - ["Object", "Plug-ins", "Selection Tools"], - None, - "{artboards: [index…] (0-based, at least one), relation?: \"overlap\" (default: on at least one of them, as select.allOnArtboard takes it: the bounds overlap the artboard or the centre is on it) | \"inside\" (the bounds lie wholly within one of them, edges included) | \"outside\" (on none of them)} select those objects among the ones Select All takes (in isolation mode, the isolated container's); hidden and locked objects, objects on hidden, locked or template layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art → {count}", - has_doc, - by_artboards - )] + vec![ + cmd!( + "addon.select.byArtboards", + "Select by Artboards", + ["Object", "Plug-ins", "Selection Tools"], + None, + "{artboards: [index…] (0-based, at least one), relation?: \"overlap\" (default: on at least one of them, as select.allOnArtboard takes it: the bounds overlap the artboard or the centre is on it) | \"inside\" (the bounds lie wholly within one of them, edges included) | \"outside\" (on none of them)} select those objects among the ones Select All takes (in isolation mode, the isolated container's); hidden and locked objects, objects on hidden, locked or template layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art → {count}", + has_doc, + by_artboards + ), + cmd!( + "addon.select.byLinkStatus", + "Select by Link Status", + ["Object", "Plug-ins", "Selection Tools"], + None, + "{status: \"linked\" (its file found unchanged) | \"embedded\" | \"missing\" | \"modified\" (its file changed since it was read) | [several of them] (at least one), ids?: [object ids] (pick only among these; default: every image and placed document in the layers), add?: false (add to the selection instead of replacing it), zoom?: false (then zoom to the selection: the desktop app runs addon.arrange.zoomSelection when something was selected; elsewhere the result's zoom flag asks the caller to)} select the image objects and placed documents whose link has that status, as links.list reports it. Those 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 left out and listed with the reason. Only the selection changes, not the document → {count (how many it selected), selected: [ids] (in stacking order, bottom first), skipped: [{id, reason: hidden|locked|template|isolation}], zoom?: true}", + has_doc, + by_link_status + ), + ] } fn by_artboards(s: &mut Session, p: &Value) -> Result { @@ -61,3 +81,109 @@ fn by_artboards(s: &mut Session, p: &Value) -> Result { s.select(|_, sel| sel.set(ids))?; Ok(json!({ "count": s.doc()?.selection.objects.len() })) } + +/// The link statuses `p` asks for (`status`: one, or a list of them), each once. +fn link_statuses(p: &Value, cmd: &str) -> Result> { + let given: Vec<&Value> = match p.get("status") { + None | Some(Value::Null) => return Err(bad(cmd, "missing `status`: linked, embedded, missing or modified")), + Some(Value::Array(v)) => v.iter().collect(), + Some(v) => vec![v], + }; + let mut out = vec![]; + for v in given { + let s = v.as_str().ok_or_else(|| bad(cmd, "`status` must be linked, embedded, missing or modified, or a list of them"))?; + let known = + LINK_STATUSES.iter().find(|k| **k == s).ok_or_else(|| bad(cmd, format!("status `{s}`: linked, embedded, missing or modified")))?; + if !out.contains(known) { + out.push(*known); + } + } + if out.is_empty() { + return Err(bad(cmd, "choose at least one status")); + } + Ok(out) +} + +/// The link status of every image object and placed document in the layers of `st`, as +/// `links.list` reports it (`ok` named `linked`), in stacking order (bottom first). Each file is +/// looked at once. +pub(crate) fn link_status_of_objects(st: &DocState) -> Vec<(NodeId, &'static str)> { + let linked = statuses(st); + let mut out = vec![]; + st.doc.walk(|n| { + if matches!(n.kind, NodeKind::Image(_) | NodeKind::PlacedDocument(_)) { + let status = match linked.get(&n.id).map(|(s, ..)| *s) { + Some(Status::Ok) => "linked", + Some(Status::Modified) => "modified", + Some(Status::Missing) => "missing", + None => "embedded", + }; + out.push((n.id, status)); + } + }); + out +} + +/// Why object `id` of `st` can't be selected now ([`is_selectable`]): it is outside the isolated +/// group or layer, on a template layer, hidden (or inside something hidden), or locked (or inside +/// something locked, or on a locked artboard); `None` when it can be. `locks` is the document's +/// [`vectorcraft_doc::Document::locked_artboards`]. +fn skip_reason(st: &DocState, locks: &LockedArtboards, id: NodeId) -> Option<&'static str> { + let d = &st.doc; + if is_selectable(d, st.isolation, locks, id) { + return None; + } + let ancestry = d.ancestry(id).unwrap_or_default(); + // Outside the isolated container, or the isolated container itself (its art is what's taken). + if let Some(c) = st.isolation.and_then(|i| d.node(i)) + && ancestry.iter().position(|i| *i == c.id).is_none_or(|at| at + 1 == ancestry.len() && c.is_container()) + { + return Some("isolation"); + } + let held: Vec<&Node> = ancestry.iter().filter_map(|i| d.node(*i)).collect(); + Some(if held.iter().any(|n| n.is_template()) { + "template" + } else if held.iter().any(|n| !n.visible) { + "hidden" + } else { + // A locked object, group or layer, or the locked artboard that holds it. + "locked" + }) +} + +fn by_link_status(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.select.byLinkStatus"; + let wanted = link_statuses(p, C)?; + let add = switch_or(p, "add", false, C)?; + let zoom = switch_or(p, "zoom", false, C)?; + let only: Option> = match p.get("ids") { + None | Some(Value::Null) => None, + Some(_) => Some(checked_ids_param(s, p, "ids", C)?.into_iter().collect()), + }; + let st = s.doc()?; + let locks = st.doc.locked_artboards(); + let (mut picked, mut skipped) = (vec![], vec![]); + for (id, status) in link_status_of_objects(st) { + if !wanted.contains(&status) || only.as_ref().is_some_and(|o| !o.contains(&id)) { + continue; + } + match skip_reason(st, &locks, id) { + None => picked.push(id), + Some(reason) => skipped.push(json!({ "id": id.0, "reason": reason })), + } + } + s.select(|_, sel| { + if add { + for id in &picked { + sel.add(*id); + } + } else { + sel.set(picked.iter().copied()); + } + })?; + let mut out = json!({ "count": picked.len(), "selected": picked.iter().map(|id| id.0).collect::>(), "skipped": skipped }); + if zoom { + out["zoom"] = json!(true); + } + Ok(out) +} diff --git a/crates/engine/src/cmd/addons/select/tests.rs b/crates/engine/src/cmd/addons/select/tests.rs index bea05ff9e2..ca59565261 100644 --- a/crates/engine/src/cmd/addons/select/tests.rs +++ b/crates/engine/src/cmd/addons/select/tests.rs @@ -126,3 +126,179 @@ fn a_symbol_instance_is_measured_by_its_art() { assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "inside"})), vec![instance]); assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "outside"})), vec![]); } + +/// Select by Link Status. +mod by_link_status { + use serde_json::{Value, json}; + use vectorcraft_doc::{Document, NodeId}; + + use crate::Session; + use crate::tests_links::{BLUE, Folder, RED, place, png, session, write}; + + const C: &str = "addon.select.byLinkStatus"; + + /// One linked image whose file stays as it is (`ok`), one whose file changes (`modified`), + /// one whose file goes (`missing`), an embedded one, and a placed document whose file goes + /// (missing too), bottom to top. + struct Links { + s: Session, + ok: NodeId, + modified: NodeId, + missing: NodeId, + embedded: NodeId, + document: NodeId, + _dir: Folder, + } + + fn links(name: &str) -> Links { + let dir = Folder::new(name); + let (a, b, c, e, d) = (dir.file("ok.png"), dir.file("changes.png"), dir.file("goes.png"), dir.file("kept.png"), dir.file("page.vectorcraft")); + write(&a, &png(10, 10, RED)); + write(&b, &png(12, 10, RED)); + write(&c, &png(14, 10, BLUE)); + write(&e, &png(16, 10, BLUE)); + write(&d, &vectorcraft_format::save_file(&Document::new(80.0, 50.0))); + let mut s = session(); + let (ok, modified, missing) = (place(&mut s, &a), place(&mut s, &b), place(&mut s, &c)); + let embedded = NodeId(s.execute("file.place", &json!({"path": e, "at": [100, 100], "link": false})).unwrap()["ids"][0].as_u64().unwrap()); + let document = place(&mut s, &d); + write(&b, &png(13, 10, BLUE)); + std::fs::remove_file(&c).unwrap(); + std::fs::remove_file(&d).unwrap(); + Links { s, ok, modified, missing, embedded, document, _dir: dir } + } + + fn run(s: &mut Session, p: Value) -> Value { + s.execute(C, &p).unwrap_or_else(|e| panic!("{p}: {e}")) + } + + fn sorted(mut v: Vec) -> Vec { + v.sort(); + v + } + + fn selection(s: &Session) -> Vec { + sorted(s.doc().unwrap().selection.objects.clone()) + } + + fn ids(v: &Value) -> Vec { + sorted(v.as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()) + } + + #[test] + fn each_status_selects_its_images_and_placed_documents() { + let Links { mut s, ok, modified, missing, embedded, document, _dir } = links("select-status"); + // As the Links panel lists them. + let listed = s.execute("links.list", &json!({})).unwrap(); + let status = |id: NodeId| listed["links"].as_array().unwrap().iter().find(|r| r["id"] == id.0).unwrap()["status"].clone(); + assert_eq!([ok, modified, missing, embedded, document].map(status), ["ok", "modified", "missing", "embedded", "missing"].map(|s| json!(s))); + let undo = s.doc().unwrap().history.undo.len(); + for (status, want) in [("linked", vec![ok]), ("modified", vec![modified]), ("missing", vec![missing, document]), ("embedded", vec![embedded])] + { + s.execute("select.none", &json!({})).unwrap(); + let r = run(&mut s, json!({"status": status})); + assert_eq!((ids(&r["selected"]), r["count"].as_u64()), (sorted(want.clone()), Some(want.len() as u64)), "{status}: {r}"); + assert_eq!(selection(&s), sorted(want), "{status}"); + assert_eq!(r["skipped"], json!([])); + assert!(r.get("zoom").is_none()); + } + // Several at once, in stacking order (bottom first); a status listed twice counts once. + let r = run(&mut s, json!({"status": ["missing", "linked", "missing"]})); + assert_eq!(r["selected"], json!([ok.0, missing.0, document.0])); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "only the selection changes"); + } + + #[test] + fn ids_add_and_zoom() { + let Links { mut s, ok, modified, embedded, document, _dir, .. } = links("select-options"); + // Only among the ids given; other objects among them (a rectangle) are passed over. + let rect = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap()["id"].as_u64().unwrap(); + let r = run(&mut s, json!({"status": "missing", "ids": [document.0, ok.0, rect]})); + assert_eq!(r["selected"], json!([document.0])); + assert_eq!(selection(&s), vec![document]); + // Added to the selection. + let r = run(&mut s, json!({"status": "embedded", "add": true})); + assert_eq!((r["count"].as_u64(), r["selected"].clone()), (Some(1), json!([embedded.0]))); + assert_eq!(selection(&s), sorted(vec![document, embedded])); + // Replacing it by default. + run(&mut s, json!({"status": "modified"})); + assert_eq!(selection(&s), vec![modified]); + // Nothing to select: added, the selection stays; replacing, it empties. + let r = run(&mut s, json!({"status": "linked", "ids": [embedded.0], "add": true})); + assert_eq!((r["count"].as_u64(), r["selected"].clone(), r["skipped"].clone()), (Some(0), json!([]), json!([]))); + assert_eq!(selection(&s), vec![modified]); + run(&mut s, json!({"status": "linked", "ids": [embedded.0]})); + assert_eq!(selection(&s), vec![]); + // Zoom is reported for the caller (the desktop app zooms). + assert_eq!(run(&mut s, json!({"status": "linked", "zoom": true}))["zoom"], true); + assert!(run(&mut s, json!({"status": "linked", "zoom": false})).get("zoom").is_none()); + } + + #[test] + fn hidden_locked_template_and_isolated_ones_are_skipped_with_the_reason() { + let dir = Folder::new("select-skipped"); + let files: Vec = (0..6).map(|i| dir.file(&format!("img{i}.png"))).collect(); + for (i, f) in files.iter().enumerate() { + write(f, &png(10 + i as u32, 10, RED)); + } + let mut s = session(); + let [free, hidden, locked, in_group, mate] = [0, 1, 2, 3, 4].map(|i| place(&mut s, &files[i])); + s.execute("object.setProps", &json!({"ids": [hidden.0], "visible": false})).unwrap(); + s.execute("object.setProps", &json!({"ids": [locked.0], "locked": true})).unwrap(); + // Inside a locked group. + s.execute("select.set", &json!({"ids": [in_group.0]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setProps", &json!({"ids": [g], "locked": true})).unwrap(); + // On a template layer. + let layer = s.execute("layer.new", &json!({"name": "Trace"})).unwrap()["id"].as_u64().unwrap(); + let on_template = place(&mut s, &files[5]); + s.execute("layer.setProps", &json!({"id": layer, "template": true})).unwrap(); + let r = run(&mut s, json!({"status": "linked"})); + assert_eq!(ids(&r["selected"]), sorted(vec![free, mate]), "{r}"); + let mut reasons: Vec<(u64, String)> = + r["skipped"].as_array().unwrap().iter().map(|k| (k["id"].as_u64().unwrap(), k["reason"].as_str().unwrap().to_string())).collect(); + reasons.sort(); + let mut want: Vec<(u64, String)> = [(hidden, "hidden"), (locked, "locked"), (in_group, "locked"), (on_template, "template")] + .into_iter() + .map(|(id, why)| (id.0, why.to_string())) + .collect(); + want.sort(); + assert_eq!(reasons, want, "{r}"); + assert!(reasons.iter().all(|(_, why)| ["hidden", "locked", "template", "isolation"].contains(&why.as_str()))); + // In isolation mode, those outside the isolated group are left out. + s.execute("select.set", &json!({"ids": [mate.0]})).unwrap(); + let iso = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.isolate", &json!({"id": iso})).unwrap(); + let r = run(&mut s, json!({"status": "linked"})); + assert_eq!(r["selected"], json!([mate.0]), "{r}"); + let why = |id: NodeId| r["skipped"].as_array().unwrap().iter().find(|k| k["id"] == id.0).map(|k| k["reason"].clone()); + assert_eq!(why(free), Some(json!("isolation"))); + assert_eq!(why(hidden), Some(json!("isolation"))); + } + + #[test] + fn bad_params_are_errors_and_leave_the_selection() { + let Links { mut s, ok, _dir, .. } = links("select-bad"); + for p in [ + json!({}), + json!({"status": null}), + json!({"status": []}), + json!({"status": "lost"}), + json!({"status": ["linked", "lost"]}), + json!({"status": 3}), + json!({"status": [true]}), + json!({"status": "linked", "add": "yes"}), + json!({"status": "linked", "zoom": 1}), + json!({"status": "linked", "ids": "1"}), + json!({"status": "linked", "ids": [999_999]}), + json!({"status": "linked", "ids": [-1]}), + json!({"status": "linked", "stauts": "missing"}), + ] { + s.execute("select.set", &json!({"ids": [ok.0]})).unwrap(); + assert!(s.execute(C, &p).is_err(), "{p}"); + assert_eq!(s.doc().unwrap().selection.objects, vec![ok], "{p}"); + } + // Without a document it is off, not a crash. + assert!(Session::new().execute(C, &json!({"status": "linked"})).is_err()); + } +} diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 441249b05b..842d78b56c 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -1110,7 +1110,7 @@ fn linked_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result { /// Per linked image in the layers of `st`: its file's status, where it was found when away from /// its path, and whether the image shows its preview (each file probed once). -fn statuses(st: &crate::DocState) -> BTreeMap, bool)> { +pub(crate) fn statuses(st: &crate::DocState) -> BTreeMap, bool)> { let mut out = BTreeMap::new(); for g in groups(&st.doc, None).iter().filter(|g| !g.ids.is_empty()) { let (status, found) = probe(g, st.path.as_deref()); diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index b8b360b804..42970aa160 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -239,6 +239,10 @@ fn structured_junk() { ("addon.select.byArtboards", json!({"artboards": [0, u64::MAX, -1, "x", null, 1.5], "relation": "inside"})), ("addon.select.byArtboards", json!({"artboards": [1e308], "relation": [1]})), ("addon.select.byArtboards", json!({"artboards": {"a": 1}, "relation": "outside"})), + ("addon.select.byLinkStatus", json!({"status": ["linked", "missing", null, 7, {"a": 1}], "ids": [2, u64::MAX, -1, "x", 1.5]})), + ("addon.select.byLinkStatus", json!({"status": "embedded", "ids": {"a": 1}, "add": [1], "zoom": "yes"})), + ("addon.select.byLinkStatus", json!({"status": ["modified", "embedded"], "ids": [], "add": true, "zoom": true})), + ("addon.select.byLinkStatus", json!({"status": [[["linked"]]], "ids": null})), ("object.transform", json!({"matrix": [0, 0, 0, 0, 0, 0]})), ("object.transform", json!({"matrix": [1e308, 1e308, 1e308, 1e308, 1e308, 1e308]})), ("object.transform", json!({"matrix": [1, 2, 3]})), diff --git a/crates/ui-egui/src/addons/select.rs b/crates/ui-egui/src/addons/select.rs index 8f6b258269..c61eb0537d 100644 --- a/crates/ui-egui/src/addons/select.rs +++ b/crates/ui-egui/src/addons/select.rs @@ -1,7 +1,8 @@ //! Selection Tools in the interface: its submenu (Object › Plug-ins › Selection Tools) and the //! Select by Artboards dialog (#5548), which lists the artboards with their number, name and size, //! filters them by name, picks several, fits one in the window on double-click (#5549), and on OK -//! runs `addon.select.byArtboards` with the relation chosen. +//! runs `addon.select.byArtboards` with the relation chosen; and Select by Link Status +//! ([`link_status`], #5526). use egui::{Sense, Ui, vec2}; use serde_json::{Value, json}; @@ -13,6 +14,8 @@ use crate::state::Dialog; use crate::theme::Tokens; use crate::widgets; +pub mod link_status; + /// Select by Artboards, and its dialog's kind. pub const COMMAND: &str = "addon.select.byArtboards"; pub const KIND: &str = "selectByArtboards"; @@ -25,7 +28,9 @@ const LIST_H: f32 = 220.0; /// Object › Plug-ins › Selection Tools. pub fn menu() -> Vec { - vec![Item::Cmd("Select by Artboards…", COMMAND, Value::Null)] + let mut v = vec![Item::Cmd("Select by Artboards…", COMMAND, Value::Null), Item::Sep]; + v.extend(link_status::menu()); + v } /// The dialog's fields to start with: the active artboard chosen, Overlapping. diff --git a/crates/ui-egui/src/addons/select/link_status.rs b/crates/ui-egui/src/addons/select/link_status.rs new file mode 100644 index 0000000000..7b7203276c --- /dev/null +++ b/crates/ui-egui/src/addons/select/link_status.rs @@ -0,0 +1,286 @@ +//! Select by Link Status in the interface (#5526): Select Linked, Embedded, Missing and Modified +//! (in Object › Plug-ins › Selection Tools and the Links panel's menu; Shift adds to the +//! selection), the Select by Link Status dialog, and the status bar's line saying what was +//! selected and what was left out. Everything goes through `addon.select.byLinkStatus`; the dialog +//! lists what `links.list` reports. + +use egui::{Ui, vec2}; +use serde_json::{Value, json}; + +use crate::VectorcraftApp; +use crate::dialogs::{DialogSpec, form}; +use crate::menus::Item; +use crate::state::Dialog; +use crate::theme::Tokens; +use crate::widgets; + +/// Select by Link Status, and its dialog's kind. +pub const COMMAND: &str = "addon.select.byLinkStatus"; +pub const KIND: &str = "selectByLinkStatus"; +/// The statuses, as the command names them, with their menu items' and the dialog's labels. +pub const STATUSES: [(&str, &str, &str); 4] = [ + ("linked", "Select Linked", "Linked"), + ("embedded", "Select Embedded", "Embedded"), + ("missing", "Select Missing", "Missing"), + ("modified", "Select Modified", "Modified"), +]; +/// The dialog's Show choices: (value, label). +const SHOW: [(&str, &str); 5] = [("all", "All"), ("linked", "Linked"), ("embedded", "Embedded"), ("missing", "Missing"), ("modified", "Modified")]; +/// How often the statuses are looked at again while the document stays as it is (s): files +/// change on disk without the document knowing. +const RECHECK: f64 = 2.0; +/// The least time between two looks while the document keeps changing (s). +const SETTLE: f64 = 0.5; +const ROW_H: f32 = 22.0; +const LIST_H: f32 = 240.0; +const STATUS_W: f32 = 80.0; +const FORMAT_W: f32 = 70.0; + +/// The menu items: one per status, then the dialog. +pub fn menu() -> Vec { + let mut v: Vec = STATUSES.iter().map(|&(status, label, _)| Item::Cmd(label, COMMAND, json!({ "status": status }))).collect(); + v.push(Item::Cmd("Select by Link Status…", COMMAND, Value::Null)); + v +} + +/// Which statuses ([`STATUSES`] order) the active document's images and placed documents have, +/// for the document and revision it was read for and when. +#[derive(Clone, Debug, Default)] +pub struct Present { + key: Option<(u64, u64)>, + at: f64, + pub has: [bool; 4], +} + +/// The statuses the `links.list` result `list` holds, in [`STATUSES`] order. +pub(crate) fn statuses_in(list: &Value) -> [bool; 4] { + let rows = list["links"].as_array().map_or(&[][..], Vec::as_slice); + STATUSES.map(|(status, ..)| rows.iter().any(|r| command_status(r) == status)) +} + +/// The status of a `links.list` row as the command names it (`ok` is `linked`). +fn command_status(row: &Value) -> &str { + match row["status"].as_str().unwrap_or_default() { + "ok" => "linked", + s => s, + } +} + +/// Keep [`Present`] up to date: at once when another document comes to the front, at most every +/// [`SETTLE`] seconds while its revision changes (a drag changes it every frame, and each look +/// asks the file system about every linked file), and every [`RECHECK`] seconds while it has +/// linked files. +pub fn refresh(app: &mut VectorcraftApp, now: f64) { + let key = app.session.active().map(|st| (st.uid, st.revision)); + let p = &app.ui.link_statuses; + let linked = p.has.iter().zip(STATUSES).any(|(on, (status, ..))| *on && status != "embedded"); + let other_document = p.key.map(|k| k.0) != key.map(|k| k.0); + let due = if p.key == key { linked && now - p.at >= RECHECK } else { other_document || now - p.at >= SETTLE }; + if !due { + return; + } + let has = if key.is_some() { app.session.execute("links.list", &json!({})).map(|l| statuses_in(&l)).unwrap_or_default() } else { [false; 4] }; + app.ui.link_statuses = Present { key, at: now, has }; +} + +/// Is menu item `status` (a [`STATUSES`] value) on: does an image or placed document have it? +pub(crate) fn enabled(app: &VectorcraftApp, p: &Value) -> bool { + let Some(status) = p.get("status").and_then(Value::as_str) else { return true }; + STATUSES.iter().position(|(s, ..)| *s == status).and_then(|i| app.ui.link_statuses.has.get(i).copied()).unwrap_or(false) +} + +/// A menu item's params with Shift held: add to the selection. +pub(crate) fn with_shift(mut p: Value) -> Value { + if let Some(o) = p.as_object_mut() + && o.contains_key("status") + { + o.insert("add".into(), json!(true)); + } + p +} + +/// Run the command; with `zoom` and something selected, Zoom to Selection; the status bar says +/// what was selected and what was left out. Without params (the menu's "Select by Link Status…") +/// it opens the dialog instead. +pub(crate) fn run(app: &mut VectorcraftApp, p: &Value) -> Result { + if p.as_object().is_none_or(serde_json::Map::is_empty) { + if app.session.active().is_none() { + return Err("no document".into()); + } + let fields = fields(app); + app.ui.dialog = Some(Dialog::new(KIND, fields)); + return Ok(json!({ "dialog": KIND })); + } + let r = app.session.execute(COMMAND, p).map_err(|e| e.to_string())?; + let count = r["count"].as_u64().unwrap_or(0); + if r["zoom"] == true && count > 0 { + crate::addons::arrange::zoom(app)?; + } + let statuses: Vec<&str> = match &p["status"] { + Value::Array(v) => v.iter().filter_map(Value::as_str).collect(), + v => v.as_str().into_iter().collect(), + }; + let reasons: Vec<&str> = r["skipped"].as_array().map_or(vec![], |v| v.iter().filter_map(|k| k["reason"].as_str()).collect()); + app.status(message(&statuses, count, &reasons)); + Ok(r) +} + +/// The status bar's line: `count` objects of `statuses` selected, and the `reasons` the others +/// were left out for (e.g. "Selected 9 missing images; 3 more are hidden or locked"). +pub(crate) fn message(statuses: &[&str], count: u64, reasons: &[&str]) -> String { + let n = count; + let selected = match statuses { + ["linked"] => crate::i18n::msg_n(n, "Selected {n} linked image", "Selected {n} linked images", &[]), + ["embedded"] => crate::i18n::msg_n(n, "Selected {n} embedded image", "Selected {n} embedded images", &[]), + ["missing"] => crate::i18n::msg_n(n, "Selected {n} missing image", "Selected {n} missing images", &[]), + ["modified"] => crate::i18n::msg_n(n, "Selected {n} modified image", "Selected {n} modified images", &[]), + _ => crate::i18n::msg_n(n, "Selected {n} image", "Selected {n} images", &[]), + }; + let Some(first) = reasons.first() else { return selected }; + // Hidden and locked go together; a template layer, or the isolated group, alone. + fn kind(r: &str) -> &str { + match r { + "hidden" | "locked" => "locked", + r => r, + } + } + let (one, other) = match kind(first) { + k if reasons.iter().any(|r| kind(r) != k) => ("{selected}; {n} more can't be selected now", "{selected}; {n} more can't be selected now"), + "template" => ("{selected}; {n} more is on a template layer", "{selected}; {n} more are on template layers"), + "isolation" => ("{selected}; {n} more is outside the isolated group", "{selected}; {n} more are outside the isolated group"), + _ => ("{selected}; {n} more is hidden or locked", "{selected}; {n} more are hidden or locked"), + }; + crate::i18n::msg_n(reasons.len() as u64, one, other, &[("selected", &selected)]) +} + +/// The dialog's fields to start with: every image and placed document (`__rows`, as `links.list` +/// lists them, read once), those selected chosen, All shown, Zoom to Selection on. +pub(crate) fn fields(app: &mut VectorcraftApp) -> Value { + let list = app.session.execute("links.list", &json!({})).unwrap_or_default(); + let rows: Vec = list["links"].as_array().cloned().unwrap_or_default(); + let selected: Vec = app.session.active().map(|st| st.selection.objects.iter().map(|id| id.0).collect()).unwrap_or_default(); + let chosen: Vec = rows.iter().filter_map(|r| r["id"].as_u64()).filter(|id| selected.contains(id)).collect(); + json!({ "__rows": rows, "ids": chosen, "show": "all", "zoom": true }) +} + +pub(crate) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Select by Link Status").to_string(), + body, + confirm, + ok: Some("Select"), + min_width: 420.0, + max_width: Some(480.0), + ok_enabled: Some(|_, d| !chosen(d).is_empty()), + ..DialogSpec::FORM +}; + +/// The ids chosen in dialog `d`. +pub(crate) fn chosen(d: &Dialog) -> Vec { + d.fields.get("ids").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_u64).collect() +} + +/// The rows of `rows` the name search `query` (ignoring case) and the Show choice `show` let through. +pub(crate) fn shown<'a>(rows: &'a [Value], query: &str, show: &str) -> Vec<&'a Value> { + let q = query.trim().to_lowercase(); + rows.iter() + .filter(|r| show == "all" || command_status(r) == show) + .filter(|r| q.is_empty() || r["name"].as_str().unwrap_or_default().to_lowercase().contains(&q)) + .collect() +} + +/// All (`on`) or None: choose every row `shown`, or none of them; rows the search or Show hides +/// keep their state. +pub(crate) fn choose_shown(chosen: &mut Vec, shown: &[u64], on: bool) { + if on { + for id in shown { + if !chosen.contains(id) { + chosen.push(*id); + } + } + } else { + chosen.retain(|id| !shown.contains(id)); + } +} + +/// Tick or untick row `id`. +pub(crate) fn toggle(chosen: &mut Vec, id: u64) { + match chosen.iter().position(|c| *c == id) { + Some(i) => { + chosen.remove(i); + } + None => chosen.push(id), + } +} + +/// A status's label in the list. +fn status_label(status: &str) -> &'static str { + STATUSES.iter().find(|(s, ..)| *s == status).map_or("", |&(.., label)| tl!(label)) +} + +fn body(_app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { + let t = Tokens::get(ui.ctx()); + let rows: Vec = d.fields.get("__rows").and_then(Value::as_array).cloned().unwrap_or_default(); + let query = widgets::search_field(ui, ui.scope_id().with("select-by-link-status-search"), tl!("Search images")); + d.fields.insert("__search".into(), json!(query)); + ui.add_space(4.0); + form::choice(ui, d, "show", tl!("Show:"), (60.0, 140.0), &SHOW); + let show = d.str("show"); + let visible = shown(&rows, &query, &show); + let mut picked = chosen(d); + ui.add_space(4.0); + egui::ScrollArea::vertical().max_height(LIST_H).auto_shrink([false, true]).show(ui, |ui| { + if visible.is_empty() { + ui.label(egui::RichText::new(tl!("No images match.")).color(t.text_dim)); + } + for r in &visible { + let Some(id) = r["id"].as_u64() else { continue }; + let name = r["name"].as_str().unwrap_or_default(); + let status = status_label(command_status(r)); + let format = r["format"].as_str().unwrap_or_default(); + ui.horizontal(|ui| { + ui.set_min_height(ROW_H); + let on = picked.contains(&id); + let name_w = (ui.available_width() - STATUS_W - FORMAT_W - 40.0).max(60.0); + let check = ui.scope(|ui| { + ui.set_width(name_w + 24.0); + widgets::check_name(ui, name, on) + }); + if check.inner { + toggle(&mut picked, id); + } + ui.add_sized(vec2(STATUS_W, ROW_H), egui::Label::new(egui::RichText::new(status).color(t.text_dim)).truncate()); + ui.add_sized(vec2(FORMAT_W, ROW_H), egui::Label::new(egui::RichText::new(format).color(t.text_dim)).truncate()); + }); + } + }); + ui.add_space(4.0); + let ids: Vec = visible.iter().filter_map(|r| r["id"].as_u64()).collect(); + ui.horizontal(|ui| { + if widgets::flat_button_fit(ui, "All", 50.0).clicked() { + choose_shown(&mut picked, &ids, true); + } + if widgets::flat_button_fit(ui, "None", 50.0).clicked() { + choose_shown(&mut picked, &ids, false); + } + let count = crate::i18n::fmt(tl!("Chosen: {n} of {total}"), &[("n", &picked.len().to_string()), ("total", &rows.len().to_string())]); + ui.label(egui::RichText::new(count).color(t.text_dim)); + }); + d.fields.insert("ids".into(), json!(picked)); + ui.add_space(6.0); + form::check(ui, d, "zoom", tl!("Zoom to Selection")); + false +} + +/// The command's params for dialog `d`: the rows chosen, whatever their status. +pub(crate) fn params(d: &Dialog) -> Value { + json!({ "status": STATUSES.map(|(s, ..)| s), "ids": chosen(d), "zoom": d.bool("zoom") }) +} + +/// Select: select the rows chosen (and zoom to them) and close. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + app.ui.dialog = None; + app.run(COMMAND, params(d)) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/select/link_status/tests.rs b/crates/ui-egui/src/addons/select/link_status/tests.rs new file mode 100644 index 0000000000..22b07ccace --- /dev/null +++ b/crates/ui-egui/src/addons/select/link_status/tests.rs @@ -0,0 +1,199 @@ +use serde_json::{Value, json}; +use vectorcraft_engine::Session; + +use super::{COMMAND, KIND, choose_shown, message, refresh, shown, toggle}; +use crate::tests_labels::painted_text; +use crate::{VectorcraftApp, menus}; + +/// A fresh folder for one test (removed when dropped). +struct Folder(std::path::PathBuf); + +impl Folder { + fn new(name: &str) -> Self { + let dir = std::env::temp_dir().join(format!("vectorcraft-ui-select-links-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir) + } + fn file(&self, name: &str, bytes: &[u8]) -> String { + let p = self.0.join(name); + std::fs::write(&p, bytes).unwrap(); + p.to_string_lossy().into_owned() + } +} + +impl Drop for Folder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn png(w: u32, h: u32) -> Vec { + let mut out = vec![]; + image::RgbaImage::from_pixel(w, h, image::Rgba([200, 40, 40, 255])) + .write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png) + .unwrap(); + out +} + +/// A document with `river.png` linked, `harbour.png` linked and then deleted (missing), and +/// `stamp.png` embedded → (app, river, harbour, stamp). +fn app(dir: &Folder) -> (VectorcraftApp, u64, u64, u64) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let place = |app: &mut VectorcraftApp, path: &str, at: [u32; 2], link: bool| { + app.run("file.place", json!({"path": path, "at": at, "link": link})).unwrap()["ids"][0].as_u64().unwrap() + }; + let (a, b, c) = (dir.file("river.png", &png(40, 30)), dir.file("harbour.png", &png(30, 20)), dir.file("stamp.png", &png(20, 20))); + let river = place(&mut app, &a, [100, 100], true); + let harbour = place(&mut app, &b, [300, 100], true); + let stamp = place(&mut app, &c, [200, 220], false); + std::fs::remove_file(&b).unwrap(); + app.run("select.none", json!({})).unwrap(); + (app, river, harbour, stamp) +} + +fn selected(app: &VectorcraftApp) -> Vec { + let mut ids: Vec = app.session.active().unwrap().selection.objects.iter().map(|id| id.0).collect(); + ids.sort_unstable(); + ids +} + +#[test] +fn the_message_says_what_was_selected_and_what_was_left_out() { + assert_eq!(message(&["missing"], 9, &[]), "Selected 9 missing images"); + assert_eq!(message(&["linked"], 1, &[]), "Selected 1 linked image"); + assert_eq!(message(&["embedded", "modified"], 2, &[]), "Selected 2 images"); + assert_eq!(message(&["missing"], 9, &["hidden", "locked", "hidden"]), "Selected 9 missing images; 3 more are hidden or locked"); + assert_eq!(message(&["modified"], 0, &["template"]), "Selected 0 modified images; 1 more is on a template layer"); + assert_eq!(message(&["embedded"], 2, &["isolation", "isolation"]), "Selected 2 embedded images; 2 more are outside the isolated group"); + assert_eq!(message(&["linked"], 1, &["isolation", "locked"]), "Selected 1 linked image; 2 more can't be selected now"); +} + +#[test] +fn the_list_filters_by_name_and_status_and_all_and_none_act_on_the_rows_shown() { + let rows = vec![ + json!({"id": 1, "name": "River.png", "status": "ok"}), + json!({"id": 2, "name": "harbour.png", "status": "missing"}), + json!({"id": 3, "name": "Stamp.png", "status": "embedded"}), + json!({"id": 4, "name": "river-2.tif", "status": "modified"}), + ]; + let ids = |v: Vec<&Value>| v.iter().map(|r| r["id"].as_u64().unwrap()).collect::>(); + assert_eq!(ids(shown(&rows, "", "all")), vec![1, 2, 3, 4]); + assert_eq!(ids(shown(&rows, " RIVER ", "all")), vec![1, 4]); + assert_eq!(ids(shown(&rows, "river", "linked")), vec![1], "ok is Linked"); + assert_eq!(ids(shown(&rows, "", "missing")), vec![2]); + assert_eq!(ids(shown(&rows, "zzz", "all")), Vec::::new()); + // Row 3 is chosen but hidden: neither All nor None touches it. + let mut c = vec![3]; + choose_shown(&mut c, &[1, 4], true); + assert_eq!(c, vec![3, 1, 4]); + choose_shown(&mut c, &[1, 4], false); + assert_eq!(c, vec![3]); + toggle(&mut c, 2); + toggle(&mut c, 3); + assert_eq!(c, vec![2]); +} + +#[test] +fn menu_items_are_on_for_the_statuses_present_and_shift_adds() { + let dir = Folder::new("menu"); + let (mut app, river, harbour, stamp) = app(&dir); + refresh(&mut app, 0.0); + let entries = menus::menu_entries(&app); + let item = |label: &str| entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Selection Tools"] && e.label == label).unwrap(); + for (label, on) in + [("Select Linked", true), ("Select Embedded", true), ("Select Missing", true), ("Select Modified", false), ("Select by Link Status…", true)] + { + assert_eq!(item(label).enabled, on, "{label}"); + } + let run = |app: &mut VectorcraftApp, label: &str, shift: bool| { + let e = item(label); + let target = menus::click_target(&e.label, e.command.as_deref().unwrap(), &e.params); + let held = if shift { egui::Modifiers::SHIFT } else { egui::Modifiers::NONE }; + let (cmd, p) = menus::with_held_keys(target, held); + menus::invoke(app, &cmd, p); + }; + run(&mut app, "Select Missing", false); + assert_eq!(selected(&app), vec![harbour]); + assert_eq!(app.ui.status, "Selected 1 missing image"); + run(&mut app, "Select Embedded", true); + assert_eq!(selected(&app), vec![harbour, stamp], "Shift adds"); + run(&mut app, "Select Linked", false); + assert_eq!(selected(&app), vec![river], "without Shift it replaces"); + // A hidden image is left out, and the status bar says so. + app.run("object.setProps", json!({"ids": [river], "visible": false})).unwrap(); + run(&mut app, "Select Linked", false); + assert_eq!(selected(&app), Vec::::new()); + assert_eq!(app.ui.status, "Selected 0 linked images; 1 more is hidden or locked"); + // The document changes: the items follow on the next refresh. + app.run("select.set", json!({"ids": [harbour]})).unwrap(); + app.run("edit.clear", json!({})).unwrap(); + refresh(&mut app, 1.0); + let entries = menus::menu_entries(&app); + let on = |label: &str| entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Selection Tools"] && e.label == label).unwrap().enabled; + assert!(!on("Select Missing")); + assert!(on("Select Embedded")); +} + +#[test] +fn the_links_panel_menu_lists_the_select_items() { + let dir = Folder::new("flyout"); + let (mut app, ..) = app(&dir); + refresh(&mut app, 0.0); + let shown = painted_text(&mut app, crate::panels::links::menu); + for s in ["Select Linked", "Select Embedded", "Select Missing", "Select Modified"] { + assert!(shown.contains(s), "{s} in {shown}"); + } +} + +#[test] +fn the_dialog_lists_filters_and_selects_with_zoom() { + let dir = Folder::new("dialog"); + let (mut app, river, harbour, stamp) = app(&dir); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(560.0, 460.0))); + let zoom_before = app.view().unwrap().zoom; + menus::invoke(&mut app, COMMAND, Value::Null); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), &d.fields["zoom"], &d.fields["show"]), (KIND, &json!(true), &json!("all"))); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in [ + "Select by Link Status", + "river.png", + "harbour.png", + "stamp.png", + "Linked", + "Missing", + "Embedded", + "PNG", + "Zoom to Selection", + "Chosen: 0 of 3", + "All", + "None", + "Select", + ] { + assert!(shown.contains(s), "{s} in {shown}"); + } + assert!(!(super::SPEC.ok_enabled.unwrap())(&app, app.ui.dialog.as_ref().unwrap()), "Select is off with nothing chosen"); + // Show: Missing lists only the missing image. + app.ui.dialog.as_mut().unwrap().fields.insert("show".into(), json!("missing")); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert!(shown.contains("harbour.png") && !shown.contains("river.png") && !shown.contains("stamp.png"), "{shown}"); + // Choose two and Select: they are selected and the view zooms to them. + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("ids".into(), json!([river, stamp])); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(selected(&app), vec![river, stamp]); + assert_eq!(app.ui.status, "Selected 2 images"); + assert_ne!(app.view().unwrap().zoom, zoom_before, "zoomed to the selection"); + // Without Zoom to Selection the view stays. + menus::invoke(&mut app, COMMAND, Value::Null); + let zoom = app.view().unwrap().zoom; + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("ids".into(), json!([harbour])); + d.fields.insert("zoom".into(), json!(false)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(selected(&app), vec![harbour]); + assert_eq!(app.view().unwrap().zoom, zoom); +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index eb9c3526e1..7a8e99409f 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -314,6 +314,7 @@ impl VectorcraftApp { placing::poll(self); #[cfg(not(target_arch = "wasm32"))] self.tick_link_updates(ctx, now); + crate::addons::select::link_status::refresh(self, now); if !self.background.jobs.is_empty() || !self.opening.pending.is_empty() || !self.plugin_runs.running.is_empty() diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 2a90425c1f..c0f900f67c 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -422,6 +422,7 @@ registry! { SwatchLegend: [crate::addons::color::legend::KIND] => crate::addons::color::legend::SPEC, TextTweaker: [crate::addons::typetools::KIND] => crate::addons::typetools::SPEC, SelectByArtboards: [crate::addons::select::KIND] => crate::addons::select::SPEC, + SelectByLinkStatus: [crate::addons::select::link_status::KIND] => crate::addons::select::link_status::SPEC, ArrangeTools: [crate::addons::arrange::GRID, crate::addons::arrange::REPLACE, crate::addons::arrange::SIZE, crate::addons::arrange::OPACITY, crate::addons::arrange::SORT] => crate::addons::arrange::SPEC, ShortcutImport: [shortcut_import::KIND] => DialogSpec::window(shortcut_import::show, shortcut_import::confirm), } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 07c4f90d9f..5c297aeb28 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6215,6 +6215,25 @@ breakText Glyphs Глифи Minimum angle Минимален ъгъл Maximum angle Максимален ъгъл +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Избиране на свързаните + Select Embedded Избиране на вградените + Select Missing Избиране на липсващите + Select Modified Избиране на модифицираните + Select by Link Status Избиране по състояние на връзката + Select by Link Status… Избиране по състояние на връзката… + Search images Търсене на изображения + No images match. Няма съвпадащи изображения. +@msgplural Selected {n} linked image|Selected {n} linked images Избрано е {n} свързано изображение|Избрани са {n} свързани изображения +@msgplural Selected {n} embedded image|Selected {n} embedded images Избрано е {n} вградено изображение|Избрани са {n} вградени изображения +@msgplural Selected {n} missing image|Selected {n} missing images Избрано е {n} липсващо изображение|Избрани са {n} липсващи изображения +@msgplural Selected {n} modified image|Selected {n} modified images Избрано е {n} модифицирано изображение|Избрани са {n} модифицирани изображения +@msgplural Selected {n} image|Selected {n} images Избрано е {n} изображение|Избрани са {n} изображения +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; още {n} е скрито или заключено|{selected}; още {n} са скрити или заключени +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; още {n} е в шаблонен слой|{selected}; още {n} са в шаблонни слоеве +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; още {n} е извън изолираната група|{selected}; още {n} са извън изолираната група +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; още {n} не може да бъде избрано сега|{selected}; още {n} не могат да бъдат избрани сега + # Compound Shapes add-on Compound Shapes Съставни фигури Shape Mode Buttons Make Compound Shapes Бутоните за режими на фигури създават съставни фигури diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index d007b68291..12b748971d 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6250,6 +6250,25 @@ shape Open Otvoren Minimum angle Najmanji ugao Maximum angle Najveći ugao +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Odaberi povezane + Select Embedded Odaberi ugrađene + Select Missing Odaberi nedostajuće + Select Modified Odaberi izmijenjene + Select by Link Status Odabir po statusu veze + Select by Link Status… Odabir po statusu veze… + Search images Pretraži slike + No images match. Nijedna slika ne odgovara. +@msgplural Selected {n} linked image|Selected {n} linked images Odabrana je {n} povezana slika|Odabrane su {n} povezane slike|Odabrano je {n} povezanih slika +@msgplural Selected {n} embedded image|Selected {n} embedded images Odabrana je {n} ugrađena slika|Odabrane su {n} ugrađene slike|Odabrano je {n} ugrađenih slika +@msgplural Selected {n} missing image|Selected {n} missing images Odabrana je {n} nedostajuća slika|Odabrane su {n} nedostajuće slike|Odabrano je {n} nedostajućih slika +@msgplural Selected {n} modified image|Selected {n} modified images Odabrana je {n} izmijenjena slika|Odabrane su {n} izmijenjene slike|Odabrano je {n} izmijenjenih slika +@msgplural Selected {n} image|Selected {n} images Odabrana je {n} slika|Odabrane su {n} slike|Odabrano je {n} slika +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; još {n} je skrivena ili zaključana|{selected}; još {n} su skrivene ili zaključane|{selected}; još {n} je skriveno ili zaključano +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; još {n} je na sloju predloška|{selected}; još {n} su na slojevima predloška|{selected}; još {n} je na slojevima predloška +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; još {n} je izvan izolirane grupe|{selected}; još {n} su izvan izolirane grupe|{selected}; još {n} je izvan izolirane grupe +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; još {n} se sada ne može odabrati|{selected}; još {n} se sada ne mogu odabrati|{selected}; još {n} se sada ne može odabrati + # Compound Shapes add-on Compound Shapes Složeni oblici Shape Mode Buttons Make Compound Shapes Tasteri načina oblika prave složene oblike diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 34988b565f..d68f2a5bce 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6351,6 +6351,25 @@ breakText Glyphs Glifs Minimum angle Angle mínim Maximum angle Angle màxim +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Selecciona les enllaçades + Select Embedded Selecciona les incrustades + Select Missing Selecciona les que falten + Select Modified Selecciona les modificades + Select by Link Status Selecciona per estat de l’enllaç + Select by Link Status… Selecciona per estat de l’enllaç… + Search images Cerca imatges + No images match. Cap imatge no coincideix. +@msgplural Selected {n} linked image|Selected {n} linked images S’ha seleccionat {n} imatge enllaçada|S’han seleccionat {n} imatges enllaçades +@msgplural Selected {n} embedded image|Selected {n} embedded images S’ha seleccionat {n} imatge incrustada|S’han seleccionat {n} imatges incrustades +@msgplural Selected {n} missing image|Selected {n} missing images S’ha seleccionat {n} imatge que falta|S’han seleccionat {n} imatges que falten +@msgplural Selected {n} modified image|Selected {n} modified images S’ha seleccionat {n} imatge modificada|S’han seleccionat {n} imatges modificades +@msgplural Selected {n} image|Selected {n} images S’ha seleccionat {n} imatge|S’han seleccionat {n} imatges +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} més està oculta o bloquejada|{selected}; {n} més estan ocultes o bloquejades +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} més és en una capa de plantilla|{selected}; {n} més són en capes de plantilla +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} més és fora del grup aïllat|{selected}; {n} més són fora del grup aïllat +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} més no es pot seleccionar ara|{selected}; {n} més no es poden seleccionar ara + # Compound Shapes add-on Compound Shapes Formes compostes Shape Mode Buttons Make Compound Shapes Els botons de mode de forma creen formes compostes diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 57c3092b0d..10a96a0e8e 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6365,6 +6365,25 @@ breakText Glyphs Glyfy Minimum angle Minimální úhel Maximum angle Maximální úhel +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Vybrat propojené + Select Embedded Vybrat vložené + Select Missing Vybrat chybějící + Select Modified Vybrat upravené + Select by Link Status Vybrat podle stavu propojení + Select by Link Status… Vybrat podle stavu propojení… + Search images Hledat obrazy + No images match. Žádný obraz neodpovídá. +@msgplural Selected {n} linked image|Selected {n} linked images Vybrán {n} propojený obraz|Vybrány {n} propojené obrazy|Vybráno {n} propojených obrazů +@msgplural Selected {n} embedded image|Selected {n} embedded images Vybrán {n} vložený obraz|Vybrány {n} vložené obrazy|Vybráno {n} vložených obrazů +@msgplural Selected {n} missing image|Selected {n} missing images Vybrán {n} chybějící obraz|Vybrány {n} chybějící obrazy|Vybráno {n} chybějících obrazů +@msgplural Selected {n} modified image|Selected {n} modified images Vybrán {n} upravený obraz|Vybrány {n} upravené obrazy|Vybráno {n} upravených obrazů +@msgplural Selected {n} image|Selected {n} images Vybrán {n} obraz|Vybrány {n} obrazy|Vybráno {n} obrazů +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; další {n} je skrytý nebo zamčený|{selected}; další {n} jsou skryté nebo zamčené|{selected}; dalších {n} je skrytých nebo zamčených +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; další {n} je na vrstvě šablony|{selected}; další {n} jsou na vrstvách šablony|{selected}; dalších {n} je na vrstvách šablony +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; další {n} je mimo izolovanou skupinu|{selected}; další {n} jsou mimo izolovanou skupinu|{selected}; dalších {n} je mimo izolovanou skupinu +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; další {n} teď nelze vybrat|{selected}; další {n} teď nelze vybrat|{selected}; dalších {n} teď nelze vybrat + # Compound Shapes add-on Compound Shapes Složené tvary Shape Mode Buttons Make Compound Shapes Tlačítka režimů tvarů vytvářejí složené tvary diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index b5980d5727..ae8069ffa0 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6231,6 +6231,25 @@ breakText Glyphs Glyffer Minimum angle Mindste vinkel Maximum angle Største vinkel +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Markér linkede + Select Embedded Markér integrerede + Select Missing Markér manglende + Select Modified Markér ændrede + Select by Link Status Markér efter linkstatus + Select by Link Status… Markér efter linkstatus… + Search images Søg i billeder + No images match. Ingen billeder passer. +@msgplural Selected {n} linked image|Selected {n} linked images Markerede {n} linket billede|Markerede {n} linkede billeder +@msgplural Selected {n} embedded image|Selected {n} embedded images Markerede {n} integreret billede|Markerede {n} integrerede billeder +@msgplural Selected {n} missing image|Selected {n} missing images Markerede {n} manglende billede|Markerede {n} manglende billeder +@msgplural Selected {n} modified image|Selected {n} modified images Markerede {n} ændret billede|Markerede {n} ændrede billeder +@msgplural Selected {n} image|Selected {n} images Markerede {n} billede|Markerede {n} billeder +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} mere er skjult eller låst|{selected}; {n} mere er skjult eller låst +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} mere er på et skabelonlag|{selected}; {n} mere er på skabelonlag +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} mere er uden for den isolerede gruppe|{selected}; {n} mere er uden for den isolerede gruppe +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} mere kan ikke markeres nu|{selected}; {n} mere kan ikke markeres nu + # Compound Shapes add-on Compound Shapes Sammensatte figurer Shape Mode Buttons Make Compound Shapes Knapper til formtilstande opretter sammensatte figurer diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 5e38f90f52..436940908e 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5951,6 +5951,25 @@ breakText Glyphs Glyphen Minimum angle Minimaler Winkel Maximum angle Maximaler Winkel +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Verknüpfte auswählen + Select Embedded Eingebettete auswählen + Select Missing Fehlende auswählen + Select Modified Geänderte auswählen + Select by Link Status Nach Verknüpfungsstatus auswählen + Select by Link Status… Nach Verknüpfungsstatus auswählen… + Search images Bilder suchen + No images match. Kein Bild passt. +@msgplural Selected {n} linked image|Selected {n} linked images {n} verknüpftes Bild ausgewählt|{n} verknüpfte Bilder ausgewählt +@msgplural Selected {n} embedded image|Selected {n} embedded images {n} eingebettetes Bild ausgewählt|{n} eingebettete Bilder ausgewählt +@msgplural Selected {n} missing image|Selected {n} missing images {n} fehlendes Bild ausgewählt|{n} fehlende Bilder ausgewählt +@msgplural Selected {n} modified image|Selected {n} modified images {n} geändertes Bild ausgewählt|{n} geänderte Bilder ausgewählt +@msgplural Selected {n} image|Selected {n} images {n} Bild ausgewählt|{n} Bilder ausgewählt +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} weiteres ist ausgeblendet oder gesperrt|{selected}; {n} weitere sind ausgeblendet oder gesperrt +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} weiteres liegt auf einer Vorlagenebene|{selected}; {n} weitere liegen auf Vorlagenebenen +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} weiteres liegt außerhalb der isolierten Gruppe|{selected}; {n} weitere liegen außerhalb der isolierten Gruppe +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} weiteres kann gerade nicht ausgewählt werden|{selected}; {n} weitere können gerade nicht ausgewählt werden + # Compound Shapes add-on Compound Shapes Zusammengesetzte Formen Shape Mode Buttons Make Compound Shapes Formmodus-Schaltflächen erstellen zusammengesetzte Formen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 84232bda24..9dd19335de 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6317,6 +6317,25 @@ breakText Glyphs Γλύφοι Minimum angle Ελάχιστη γωνία Maximum angle Μέγιστη γωνία +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Επιλογή συνδεδεμένων + Select Embedded Επιλογή ενσωματωμένων + Select Missing Επιλογή όσων λείπουν + Select Modified Επιλογή τροποποιημένων + Select by Link Status Επιλογή κατά κατάσταση σύνδεσης + Select by Link Status… Επιλογή κατά κατάσταση σύνδεσης… + Search images Αναζήτηση εικόνων + No images match. Καμία εικόνα δεν ταιριάζει. +@msgplural Selected {n} linked image|Selected {n} linked images Επιλέχθηκε {n} συνδεδεμένη εικόνα|Επιλέχθηκαν {n} συνδεδεμένες εικόνες +@msgplural Selected {n} embedded image|Selected {n} embedded images Επιλέχθηκε {n} ενσωματωμένη εικόνα|Επιλέχθηκαν {n} ενσωματωμένες εικόνες +@msgplural Selected {n} missing image|Selected {n} missing images Επιλέχθηκε {n} εικόνα που λείπει|Επιλέχθηκαν {n} εικόνες που λείπουν +@msgplural Selected {n} modified image|Selected {n} modified images Επιλέχθηκε {n} τροποποιημένη εικόνα|Επιλέχθηκαν {n} τροποποιημένες εικόνες +@msgplural Selected {n} image|Selected {n} images Επιλέχθηκε {n} εικόνα|Επιλέχθηκαν {n} εικόνες +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}· {n} ακόμη είναι κρυφή ή κλειδωμένη|{selected}· {n} ακόμη είναι κρυφές ή κλειδωμένες +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}· {n} ακόμη είναι σε επίπεδο προτύπου|{selected}· {n} ακόμη είναι σε επίπεδα προτύπου +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}· {n} ακόμη είναι εκτός της απομονωμένης ομάδας|{selected}· {n} ακόμη είναι εκτός της απομονωμένης ομάδας +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}· {n} ακόμη δεν μπορεί να επιλεγεί τώρα|{selected}· {n} ακόμη δεν μπορούν να επιλεγούν τώρα + # Compound Shapes add-on Compound Shapes Σύνθετα σχήματα Shape Mode Buttons Make Compound Shapes Τα κουμπιά λειτουργιών σχημάτων δημιουργούν σύνθετα σχήματα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index c09b51167c..46ed40b7db 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6307,6 +6307,25 @@ breakText Glyphs Glifos Minimum angle Ángulo mínimo Maximum angle Ángulo máximo +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Seleccionar vinculadas + Select Embedded Seleccionar incrustadas + Select Missing Seleccionar ausentes + Select Modified Seleccionar modificadas + Select by Link Status Seleccionar por estado de vínculo + Select by Link Status… Seleccionar por estado de vínculo… + Search images Buscar imágenes + No images match. Ninguna imagen coincide. +@msgplural Selected {n} linked image|Selected {n} linked images Se seleccionó {n} imagen vinculada|Se seleccionaron {n} imágenes vinculadas +@msgplural Selected {n} embedded image|Selected {n} embedded images Se seleccionó {n} imagen incrustada|Se seleccionaron {n} imágenes incrustadas +@msgplural Selected {n} missing image|Selected {n} missing images Se seleccionó {n} imagen ausente|Se seleccionaron {n} imágenes ausentes +@msgplural Selected {n} modified image|Selected {n} modified images Se seleccionó {n} imagen modificada|Se seleccionaron {n} imágenes modificadas +@msgplural Selected {n} image|Selected {n} images Se seleccionó {n} imagen|Se seleccionaron {n} imágenes +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} más está oculta o bloqueada|{selected}; {n} más están ocultas o bloqueadas +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} más está en una capa de plantilla|{selected}; {n} más están en capas de plantilla +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} más está fuera del grupo aislado|{selected}; {n} más están fuera del grupo aislado +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} más no se puede seleccionar ahora|{selected}; {n} más no se pueden seleccionar ahora + # Compound Shapes add-on Compound Shapes Formas compuestas Shape Mode Buttons Make Compound Shapes Los botones de modo de forma crean formas compuestas diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 909240b3d2..16860a45f9 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6400,6 +6400,25 @@ breakText Glyphs Merkit Minimum angle Pienin kulma Maximum angle Suurin kulma +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Valitse linkitetyt + Select Embedded Valitse upotetut + Select Missing Valitse puuttuvat + Select Modified Valitse muokatut + Select by Link Status Valitse linkin tilan mukaan + Select by Link Status… Valitse linkin tilan mukaan… + Search images Hae kuvia + No images match. Mikään kuva ei vastaa hakua. +@msgplural Selected {n} linked image|Selected {n} linked images Valittiin {n} linkitetty kuva|Valittiin {n} linkitettyä kuvaa +@msgplural Selected {n} embedded image|Selected {n} embedded images Valittiin {n} upotettu kuva|Valittiin {n} upotettua kuvaa +@msgplural Selected {n} missing image|Selected {n} missing images Valittiin {n} puuttuva kuva|Valittiin {n} puuttuvaa kuvaa +@msgplural Selected {n} modified image|Selected {n} modified images Valittiin {n} muokattu kuva|Valittiin {n} muokattua kuvaa +@msgplural Selected {n} image|Selected {n} images Valittiin {n} kuva|Valittiin {n} kuvaa +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} muu on piilotettu tai lukittu|{selected}; {n} muuta on piilotettu tai lukittu +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} muu on mallitasolla|{selected}; {n} muuta on mallitasoilla +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} muu on eristetyn ryhmän ulkopuolella|{selected}; {n} muuta on eristetyn ryhmän ulkopuolella +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} muuta ei voi valita nyt|{selected}; {n} muuta ei voi valita nyt + # Compound Shapes add-on Compound Shapes Yhdistelmämuodot Shape Mode Buttons Make Compound Shapes Muototilapainikkeet luovat yhdistelmämuotoja diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6738ec8df3..c028d24c8e 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6360,6 +6360,25 @@ breakText Glyphs Glyphes Minimum angle Angle minimal Maximum angle Angle maximal +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Sélectionner les images liées + Select Embedded Sélectionner les images incorporées + Select Missing Sélectionner les images manquantes + Select Modified Sélectionner les images modifiées + Select by Link Status Sélectionner par état de lien + Select by Link Status… Sélectionner par état de lien… + Search images Rechercher des images + No images match. Aucune image ne correspond. +@msgplural Selected {n} linked image|Selected {n} linked images {n} image liée sélectionnée|{n} images liées sélectionnées +@msgplural Selected {n} embedded image|Selected {n} embedded images {n} image incorporée sélectionnée|{n} images incorporées sélectionnées +@msgplural Selected {n} missing image|Selected {n} missing images {n} image manquante sélectionnée|{n} images manquantes sélectionnées +@msgplural Selected {n} modified image|Selected {n} modified images {n} image modifiée sélectionnée|{n} images modifiées sélectionnées +@msgplural Selected {n} image|Selected {n} images {n} image sélectionnée|{n} images sélectionnées +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected} ; {n} autre est masquée ou verrouillée|{selected} ; {n} autres sont masquées ou verrouillées +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected} ; {n} autre est sur un calque modèle|{selected} ; {n} autres sont sur des calques modèles +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected} ; {n} autre est hors du groupe isolé|{selected} ; {n} autres sont hors du groupe isolé +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected} ; {n} autre ne peut pas être sélectionnée pour l’instant|{selected} ; {n} autres ne peuvent pas être sélectionnées pour l’instant + # Compound Shapes add-on Compound Shapes Formes composées Shape Mode Buttons Make Compound Shapes Les boutons de mode de forme créent des formes composées diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 491c89fae0..3eb35419ce 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6349,6 +6349,25 @@ breakText Glyphs Glifák Minimum angle Legkisebb szög Maximum angle Legnagyobb szög +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Csatoltak kijelölése + Select Embedded Beágyazottak kijelölése + Select Missing Hiányzók kijelölése + Select Modified Módosítottak kijelölése + Select by Link Status Kijelölés csatolási állapot szerint + Select by Link Status… Kijelölés csatolási állapot szerint… + Search images Képek keresése + No images match. Nincs egyező kép. +@msgplural Selected {n} linked image|Selected {n} linked images Kijelölt csatolt képek: {n} +@msgplural Selected {n} embedded image|Selected {n} embedded images Kijelölt beágyazott képek: {n} +@msgplural Selected {n} missing image|Selected {n} missing images Kijelölt hiányzó képek: {n} +@msgplural Selected {n} modified image|Selected {n} modified images Kijelölt módosított képek: {n} +@msgplural Selected {n} image|Selected {n} images Kijelölt képek: {n} +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; további rejtett vagy zárolt: {n} +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; további sablonrétegen: {n} +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; további az elkülönített csoporton kívül: {n} +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; további most nem jelölhető ki: {n} + # Compound Shapes add-on Compound Shapes Összetett alakzatok Shape Mode Buttons Make Compound Shapes Az alakzatmód-gombok összetett alakzatokat hoznak létre diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index ffb0cbf56f..33c3296008 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6231,6 +6231,25 @@ breakText Glyphs Glif Minimum angle Sudut minimum Maximum angle Sudut maksimum +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Pilih yang Tertaut + Select Embedded Pilih yang Tersemat + Select Missing Pilih yang Hilang + Select Modified Pilih yang Diubah + Select by Link Status Pilih menurut Status Tautan + Select by Link Status… Pilih menurut Status Tautan… + Search images Cari gambar + No images match. Tidak ada gambar yang cocok. +@msgplural Selected {n} linked image|Selected {n} linked images Telah memilih {n} gambar tertaut +@msgplural Selected {n} embedded image|Selected {n} embedded images Telah memilih {n} gambar tersemat +@msgplural Selected {n} missing image|Selected {n} missing images Telah memilih {n} gambar yang hilang +@msgplural Selected {n} modified image|Selected {n} modified images Telah memilih {n} gambar yang diubah +@msgplural Selected {n} image|Selected {n} images Telah memilih {n} gambar +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} lainnya tersembunyi atau terkunci +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} lainnya berada di layer templat +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} lainnya berada di luar grup yang diisolasi +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} lainnya tidak dapat dipilih sekarang + # Compound Shapes add-on Compound Shapes Bentuk majemuk Shape Mode Buttons Make Compound Shapes Tombol mode bentuk membuat bentuk majemuk diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index cfd99e62b3..e59c310d82 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5985,6 +5985,25 @@ breakText Glyphs Glifi Minimum angle Angolo minimo Maximum angle Angolo massimo +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Seleziona collegate + Select Embedded Seleziona incorporate + Select Missing Seleziona mancanti + Select Modified Seleziona modificate + Select by Link Status Seleziona per stato del collegamento + Select by Link Status… Seleziona per stato del collegamento… + Search images Cerca immagini + No images match. Nessuna immagine corrisponde. +@msgplural Selected {n} linked image|Selected {n} linked images Selezionata {n} immagine collegata|Selezionate {n} immagini collegate +@msgplural Selected {n} embedded image|Selected {n} embedded images Selezionata {n} immagine incorporata|Selezionate {n} immagini incorporate +@msgplural Selected {n} missing image|Selected {n} missing images Selezionata {n} immagine mancante|Selezionate {n} immagini mancanti +@msgplural Selected {n} modified image|Selected {n} modified images Selezionata {n} immagine modificata|Selezionate {n} immagini modificate +@msgplural Selected {n} image|Selected {n} images Selezionata {n} immagine|Selezionate {n} immagini +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; altra {n} è nascosta o bloccata|{selected}; altre {n} sono nascoste o bloccate +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; altra {n} è su un livello modello|{selected}; altre {n} sono su livelli modello +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; altra {n} è fuori dal gruppo isolato|{selected}; altre {n} sono fuori dal gruppo isolato +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; altra {n} non può essere selezionata ora|{selected}; altre {n} non possono essere selezionate ora + # Compound Shapes add-on Compound Shapes Forme composte Shape Mode Buttons Make Compound Shapes I pulsanti dei metodi forma creano forme composte diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 5da2097f26..c0f05308cd 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -6050,6 +6050,25 @@ breakText Glyphs 字形 Minimum angle 最小角度 Maximum angle 最大角度 +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked リンク済みを選択 + Select Embedded 埋め込みを選択 + Select Missing 見つからない画像を選択 + Select Modified 変更された画像を選択 + Select by Link Status リンクの状態で選択 + Select by Link Status… リンクの状態で選択… + Search images 画像を検索 + No images match. 一致する画像はありません。 +@msgplural Selected {n} linked image|Selected {n} linked images リンク済みの画像を {n} 個選択しました +@msgplural Selected {n} embedded image|Selected {n} embedded images 埋め込み画像を {n} 個選択しました +@msgplural Selected {n} missing image|Selected {n} missing images 見つからない画像を {n} 個選択しました +@msgplural Selected {n} modified image|Selected {n} modified images 変更された画像を {n} 個選択しました +@msgplural Selected {n} image|Selected {n} images 画像を {n} 個選択しました +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}。ほかに {n} 個が非表示またはロックされています +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}。ほかに {n} 個がテンプレートレイヤー上にあります +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}。ほかに {n} 個が分離したグループの外にあります +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}。ほかに {n} 個は今は選択できません + # Compound Shapes add-on Compound Shapes 複合シェイプ Shape Mode Buttons Make Compound Shapes シェイプモードボタンで複合シェイプを作成 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index b9f4a70a09..82127af216 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6376,6 +6376,25 @@ font-script Japanese იაპონური Minimum angle მინიმალური კუთხე Maximum angle მაქსიმალური კუთხე +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked დაკავშირებულების არჩევა + Select Embedded ჩაშენებულების არჩევა + Select Missing დაკარგულების არჩევა + Select Modified შეცვლილების არჩევა + Select by Link Status კავშირის მდგომარეობით არჩევა + Select by Link Status… კავშირის მდგომარეობით არჩევა… + Search images გამოსახულებების ძებნა + No images match. შესაბამისი გამოსახულება არ არის. +@msgplural Selected {n} linked image|Selected {n} linked images არჩეულია დაკავშირებული გამოსახულებები: {n} +@msgplural Selected {n} embedded image|Selected {n} embedded images არჩეულია ჩაშენებული გამოსახულებები: {n} +@msgplural Selected {n} missing image|Selected {n} missing images არჩეულია დაკარგული გამოსახულებები: {n} +@msgplural Selected {n} modified image|Selected {n} modified images არჩეულია შეცვლილი გამოსახულებები: {n} +@msgplural Selected {n} image|Selected {n} images არჩეულია გამოსახულებები: {n} +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; დამალული ან ჩაკეტილია კიდევ: {n} +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; შაბლონის ფენაზეა კიდევ: {n} +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; იზოლირებული ჯგუფის გარეთაა კიდევ: {n} +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; ახლა ვერ აირჩევა კიდევ: {n} + # Compound Shapes add-on Compound Shapes შედგენილი ფიგურები Shape Mode Buttons Make Compound Shapes ფიგურის რეჟიმის ღილაკები ქმნის შედგენილ ფიგურებს diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index ac5d1193a7..adbf827100 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5946,6 +5946,25 @@ breakText Glyphs 글리프 Minimum angle 최소 각도 Maximum angle 최대 각도 +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked 연결됨 선택 + Select Embedded 포함됨 선택 + Select Missing 없는 이미지 선택 + Select Modified 수정된 이미지 선택 + Select by Link Status 링크 상태로 선택 + Select by Link Status… 링크 상태로 선택… + Search images 이미지 검색 + No images match. 일치하는 이미지가 없습니다. +@msgplural Selected {n} linked image|Selected {n} linked images 연결된 이미지 {n}개를 선택했습니다 +@msgplural Selected {n} embedded image|Selected {n} embedded images 포함된 이미지 {n}개를 선택했습니다 +@msgplural Selected {n} missing image|Selected {n} missing images 없는 이미지 {n}개를 선택했습니다 +@msgplural Selected {n} modified image|Selected {n} modified images 수정된 이미지 {n}개를 선택했습니다 +@msgplural Selected {n} image|Selected {n} images 이미지 {n}개를 선택했습니다 +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}. {n}개는 숨겨졌거나 잠겨 있습니다 +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}. {n}개는 템플릿 레이어에 있습니다 +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}. {n}개는 격리된 그룹 밖에 있습니다 +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}. {n}개는 지금 선택할 수 없습니다 + # Compound Shapes add-on Compound Shapes 컴파운드 모양 Shape Mode Buttons Make Compound Shapes 모양 모드 버튼으로 컴파운드 모양 만들기 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 62385d6c98..5c00ac9f49 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6275,6 +6275,25 @@ breakText Glyphs Glyphs Minimum angle Minimale hoek Maximum angle Maximale hoek +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Gekoppelde selecteren + Select Embedded Ingesloten selecteren + Select Missing Ontbrekende selecteren + Select Modified Gewijzigde selecteren + Select by Link Status Selecteren op koppelingsstatus + Select by Link Status… Selecteren op koppelingsstatus… + Search images Afbeeldingen zoeken + No images match. Geen afbeelding komt overeen. +@msgplural Selected {n} linked image|Selected {n} linked images {n} gekoppelde afbeelding geselecteerd|{n} gekoppelde afbeeldingen geselecteerd +@msgplural Selected {n} embedded image|Selected {n} embedded images {n} ingesloten afbeelding geselecteerd|{n} ingesloten afbeeldingen geselecteerd +@msgplural Selected {n} missing image|Selected {n} missing images {n} ontbrekende afbeelding geselecteerd|{n} ontbrekende afbeeldingen geselecteerd +@msgplural Selected {n} modified image|Selected {n} modified images {n} gewijzigde afbeelding geselecteerd|{n} gewijzigde afbeeldingen geselecteerd +@msgplural Selected {n} image|Selected {n} images {n} afbeelding geselecteerd|{n} afbeeldingen geselecteerd +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; nog {n} is verborgen of vergrendeld|{selected}; nog {n} zijn verborgen of vergrendeld +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; nog {n} staat op een sjabloonlaag|{selected}; nog {n} staan op sjabloonlagen +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; nog {n} staat buiten de geïsoleerde groep|{selected}; nog {n} staan buiten de geïsoleerde groep +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; nog {n} kan nu niet worden geselecteerd|{selected}; nog {n} kunnen nu niet worden geselecteerd + # Compound Shapes add-on Compound Shapes Samengestelde vormen Shape Mode Buttons Make Compound Shapes Vormmodus-knoppen maken samengestelde vormen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 908f36c948..0754590d46 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -6220,6 +6220,25 @@ breakText Glyphs Glify Minimum angle Kąt minimalny Maximum angle Kąt maksymalny +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Zaznacz połączone + Select Embedded Zaznacz osadzone + Select Missing Zaznacz brakujące + Select Modified Zaznacz zmodyfikowane + Select by Link Status Zaznacz według stanu połączenia + Select by Link Status… Zaznacz według stanu połączenia… + Search images Szukaj obrazów + No images match. Żaden obraz nie pasuje. +@msgplural Selected {n} linked image|Selected {n} linked images Zaznaczono {n} połączony obraz|Zaznaczono {n} połączone obrazy|Zaznaczono {n} połączonych obrazów +@msgplural Selected {n} embedded image|Selected {n} embedded images Zaznaczono {n} osadzony obraz|Zaznaczono {n} osadzone obrazy|Zaznaczono {n} osadzonych obrazów +@msgplural Selected {n} missing image|Selected {n} missing images Zaznaczono {n} brakujący obraz|Zaznaczono {n} brakujące obrazy|Zaznaczono {n} brakujących obrazów +@msgplural Selected {n} modified image|Selected {n} modified images Zaznaczono {n} zmodyfikowany obraz|Zaznaczono {n} zmodyfikowane obrazy|Zaznaczono {n} zmodyfikowanych obrazów +@msgplural Selected {n} image|Selected {n} images Zaznaczono {n} obraz|Zaznaczono {n} obrazy|Zaznaczono {n} obrazów +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; jeszcze {n} jest ukryty lub zablokowany|{selected}; jeszcze {n} są ukryte lub zablokowane|{selected}; jeszcze {n} jest ukrytych lub zablokowanych +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; jeszcze {n} jest na warstwie szablonu|{selected}; jeszcze {n} są na warstwach szablonu|{selected}; jeszcze {n} jest na warstwach szablonu +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; jeszcze {n} jest poza izolowaną grupą|{selected}; jeszcze {n} są poza izolowaną grupą|{selected}; jeszcze {n} jest poza izolowaną grupą +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; jeszcze {n} nie można teraz zaznaczyć|{selected}; jeszcze {n} nie można teraz zaznaczyć|{selected}; jeszcze {n} nie można teraz zaznaczyć + # Compound Shapes add-on Compound Shapes Kształty złożone Shape Mode Buttons Make Compound Shapes Przyciski trybów kształtu tworzą kształty złożone diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index eb376906ca..6ba1f7ff38 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6438,6 +6438,25 @@ swatch Yellow Green Verde-amarelado Minimum angle Ângulo Mínimo Maximum angle Ângulo Máximo +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Selecionar vinculadas + Select Embedded Selecionar incorporadas + Select Missing Selecionar ausentes + Select Modified Selecionar modificadas + Select by Link Status Selecionar por status do vínculo + Select by Link Status… Selecionar por status do vínculo… + Search images Pesquisar imagens + No images match. Nenhuma imagem corresponde. +@msgplural Selected {n} linked image|Selected {n} linked images {n} imagem vinculada selecionada|{n} imagens vinculadas selecionadas +@msgplural Selected {n} embedded image|Selected {n} embedded images {n} imagem incorporada selecionada|{n} imagens incorporadas selecionadas +@msgplural Selected {n} missing image|Selected {n} missing images {n} imagem ausente selecionada|{n} imagens ausentes selecionadas +@msgplural Selected {n} modified image|Selected {n} modified images {n} imagem modificada selecionada|{n} imagens modificadas selecionadas +@msgplural Selected {n} image|Selected {n} images {n} imagem selecionada|{n} imagens selecionadas +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; mais {n} está oculta ou bloqueada|{selected}; mais {n} estão ocultas ou bloqueadas +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; mais {n} está em uma camada de modelo|{selected}; mais {n} estão em camadas de modelo +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; mais {n} está fora do grupo isolado|{selected}; mais {n} estão fora do grupo isolado +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; mais {n} não pode ser selecionada agora|{selected}; mais {n} não podem ser selecionadas agora + # Compound Shapes add-on Compound Shapes Formas Compostas Shape Mode Buttons Make Compound Shapes Os Botões de Modo de Forma Criam Formas Compostas diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d700736c6c..7be753b6f7 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6454,6 +6454,25 @@ shape Open Открытый Minimum angle Минимальный угол Maximum angle Максимальный угол +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Выделить связанные + Select Embedded Выделить внедрённые + Select Missing Выделить отсутствующие + Select Modified Выделить изменённые + Select by Link Status Выделить по состоянию связи + Select by Link Status… Выделить по состоянию связи… + Search images Поиск изображений + No images match. Нет подходящих изображений. +@msgplural Selected {n} linked image|Selected {n} linked images Выделено {n} связанное изображение|Выделено {n} связанных изображения|Выделено {n} связанных изображений +@msgplural Selected {n} embedded image|Selected {n} embedded images Выделено {n} внедрённое изображение|Выделено {n} внедрённых изображения|Выделено {n} внедрённых изображений +@msgplural Selected {n} missing image|Selected {n} missing images Выделено {n} отсутствующее изображение|Выделено {n} отсутствующих изображения|Выделено {n} отсутствующих изображений +@msgplural Selected {n} modified image|Selected {n} modified images Выделено {n} изменённое изображение|Выделено {n} изменённых изображения|Выделено {n} изменённых изображений +@msgplural Selected {n} image|Selected {n} images Выделено {n} изображение|Выделено {n} изображения|Выделено {n} изображений +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; ещё {n} скрыто или заблокировано|{selected}; ещё {n} скрыты или заблокированы|{selected}; ещё {n} скрыты или заблокированы +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; ещё {n} на слое-шаблоне|{selected}; ещё {n} на слоях-шаблонах|{selected}; ещё {n} на слоях-шаблонах +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; ещё {n} вне изолированной группы|{selected}; ещё {n} вне изолированной группы|{selected}; ещё {n} вне изолированной группы +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; ещё {n} сейчас нельзя выделить|{selected}; ещё {n} сейчас нельзя выделить|{selected}; ещё {n} сейчас нельзя выделить + # Compound Shapes add-on Compound Shapes Составные фигуры Shape Mode Buttons Make Compound Shapes Кнопки режимов фигур создают составные фигуры diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 85f4812d15..68eee36052 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6421,6 +6421,25 @@ digits Hindi Hindi Minimum angle Minsta vinkel Maximum angle Största vinkel +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Markera länkade + Select Embedded Markera inbäddade + Select Missing Markera saknade + Select Modified Markera ändrade + Select by Link Status Markera efter länkstatus + Select by Link Status… Markera efter länkstatus… + Search images Sök bilder + No images match. Ingen bild matchar. +@msgplural Selected {n} linked image|Selected {n} linked images Markerade {n} länkad bild|Markerade {n} länkade bilder +@msgplural Selected {n} embedded image|Selected {n} embedded images Markerade {n} inbäddad bild|Markerade {n} inbäddade bilder +@msgplural Selected {n} missing image|Selected {n} missing images Markerade {n} saknad bild|Markerade {n} saknade bilder +@msgplural Selected {n} modified image|Selected {n} modified images Markerade {n} ändrad bild|Markerade {n} ändrade bilder +@msgplural Selected {n} image|Selected {n} images Markerade {n} bild|Markerade {n} bilder +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} till är dold eller låst|{selected}; {n} till är dolda eller låsta +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} till ligger på ett mallager|{selected}; {n} till ligger på mallager +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} till ligger utanför den isolerade gruppen|{selected}; {n} till ligger utanför den isolerade gruppen +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} till kan inte markeras nu|{selected}; {n} till kan inte markeras nu + # Compound Shapes add-on Compound Shapes Sammansatta former Shape Mode Buttons Make Compound Shapes Formlägesknapparna skapar sammansatta former diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 5c6446de73..184bd0b46d 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6322,6 +6322,25 @@ breakText Glyphs Glifler Minimum angle En Küçük Açı Maximum angle En Büyük Açı +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Bağlantılıları Seç + Select Embedded Gömülüleri Seç + Select Missing Eksikleri Seç + Select Modified Değiştirilenleri Seç + Select by Link Status Bağlantı Durumuna Göre Seç + Select by Link Status… Bağlantı Durumuna Göre Seç… + Search images Görüntülerde ara + No images match. Eşleşen görüntü yok. +@msgplural Selected {n} linked image|Selected {n} linked images {n} bağlantılı görüntü seçildi +@msgplural Selected {n} embedded image|Selected {n} embedded images {n} gömülü görüntü seçildi +@msgplural Selected {n} missing image|Selected {n} missing images {n} eksik görüntü seçildi +@msgplural Selected {n} modified image|Selected {n} modified images {n} değiştirilmiş görüntü seçildi +@msgplural Selected {n} image|Selected {n} images {n} görüntü seçildi +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} tane daha gizli veya kilitli +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} tane daha şablon katmanında +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} tane daha izole grubun dışında +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} tane daha şu anda seçilemiyor + # Compound Shapes add-on Compound Shapes Bileşik Şekiller Shape Mode Buttons Make Compound Shapes Şekil Modu Düğmeleri Bileşik Şekiller Yapar diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 4bb7083401..f89aa17e9a 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5965,6 +5965,25 @@ breakText Glyphs Гліфи Minimum angle Мінімальний кут Maximum angle Максимальний кут +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Виділити пов’язані + Select Embedded Виділити вбудовані + Select Missing Виділити відсутні + Select Modified Виділити змінені + Select by Link Status Виділити за станом зв’язку + Select by Link Status… Виділити за станом зв’язку… + Search images Пошук зображень + No images match. Немає відповідних зображень. +@msgplural Selected {n} linked image|Selected {n} linked images Виділено {n} пов’язане зображення|Виділено {n} пов’язані зображення|Виділено {n} пов’язаних зображень +@msgplural Selected {n} embedded image|Selected {n} embedded images Виділено {n} вбудоване зображення|Виділено {n} вбудовані зображення|Виділено {n} вбудованих зображень +@msgplural Selected {n} missing image|Selected {n} missing images Виділено {n} відсутнє зображення|Виділено {n} відсутні зображення|Виділено {n} відсутніх зображень +@msgplural Selected {n} modified image|Selected {n} modified images Виділено {n} змінене зображення|Виділено {n} змінені зображення|Виділено {n} змінених зображень +@msgplural Selected {n} image|Selected {n} images Виділено {n} зображення|Виділено {n} зображення|Виділено {n} зображень +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; ще {n} приховане або заблоковане|{selected}; ще {n} приховані або заблоковані|{selected}; ще {n} приховані або заблоковані +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; ще {n} на шарі-шаблоні|{selected}; ще {n} на шарах-шаблонах|{selected}; ще {n} на шарах-шаблонах +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; ще {n} поза ізольованою групою|{selected}; ще {n} поза ізольованою групою|{selected}; ще {n} поза ізольованою групою +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; ще {n} зараз не можна виділити|{selected}; ще {n} зараз не можна виділити|{selected}; ще {n} зараз не можна виділити + # Compound Shapes add-on Compound Shapes Складені фігури Shape Mode Buttons Make Compound Shapes Кнопки режимів фігур створюють складені фігури diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 330792405e..a76ec9ebec 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5966,6 +5966,25 @@ breakText Glyphs Glyph Minimum angle Góc tối thiểu Maximum angle Góc tối đa +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Chọn ảnh đã liên kết + Select Embedded Chọn ảnh đã nhúng + Select Missing Chọn ảnh bị thiếu + Select Modified Chọn ảnh đã sửa đổi + Select by Link Status Chọn theo trạng thái liên kết + Select by Link Status… Chọn theo trạng thái liên kết… + Search images Tìm ảnh + No images match. Không có ảnh nào khớp. +@msgplural Selected {n} linked image|Selected {n} linked images Đã chọn {n} ảnh đã liên kết +@msgplural Selected {n} embedded image|Selected {n} embedded images Đã chọn {n} ảnh đã nhúng +@msgplural Selected {n} missing image|Selected {n} missing images Đã chọn {n} ảnh bị thiếu +@msgplural Selected {n} modified image|Selected {n} modified images Đã chọn {n} ảnh đã sửa đổi +@msgplural Selected {n} image|Selected {n} images Đã chọn {n} ảnh +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; thêm {n} ảnh bị ẩn hoặc khóa +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; thêm {n} ảnh nằm trên lớp mẫu +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; thêm {n} ảnh nằm ngoài nhóm đã tách biệt +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; thêm {n} ảnh hiện không thể chọn + # Compound Shapes add-on Compound Shapes Hình phức hợp Shape Mode Buttons Make Compound Shapes Nút chế độ hình dạng tạo hình phức hợp diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 48f040a9cb..c1945d7266 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -6206,6 +6206,25 @@ breakText Glyphs 字形 Minimum angle 最小角度 Maximum angle 最大角度 +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked 选择已链接 + Select Embedded 选择嵌入 + Select Missing 选择缺失 + Select Modified 选择已修改 + Select by Link Status 按链接状态选择 + Select by Link Status… 按链接状态选择… + Search images 搜索图像 + No images match. 没有匹配的图像。 +@msgplural Selected {n} linked image|Selected {n} linked images 已选择 {n} 个已链接的图像 +@msgplural Selected {n} embedded image|Selected {n} embedded images 已选择 {n} 个嵌入的图像 +@msgplural Selected {n} missing image|Selected {n} missing images 已选择 {n} 个缺失的图像 +@msgplural Selected {n} modified image|Selected {n} modified images 已选择 {n} 个已修改的图像 +@msgplural Selected {n} image|Selected {n} images 已选择 {n} 个图像 +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected};另有 {n} 个已隐藏或锁定 +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected};另有 {n} 个位于模板图层上 +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected};另有 {n} 个位于隔离的编组之外 +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected};另有 {n} 个现在无法选择 + # Compound Shapes add-on Compound Shapes 复合形状 Shape Mode Buttons Make Compound Shapes 形状模式按钮创建复合形状 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index f0c659b50a..d7347d1745 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -6003,6 +6003,25 @@ breakText Glyphs 字符 Minimum angle 最小角度 Maximum angle 最大角度 +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked 選取已連結 + Select Embedded 選取已內嵌 + Select Missing 選取遺失 + Select Modified 選取已修改 + Select by Link Status 依連結狀態選取 + Select by Link Status… 依連結狀態選取… + Search images 搜尋影像 + No images match. 沒有符合的影像。 +@msgplural Selected {n} linked image|Selected {n} linked images 已選取 {n} 個已連結的影像 +@msgplural Selected {n} embedded image|Selected {n} embedded images 已選取 {n} 個已內嵌的影像 +@msgplural Selected {n} missing image|Selected {n} missing images 已選取 {n} 個遺失的影像 +@msgplural Selected {n} modified image|Selected {n} modified images 已選取 {n} 個已修改的影像 +@msgplural Selected {n} image|Selected {n} images 已選取 {n} 個影像 +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected};另有 {n} 個已隱藏或鎖定 +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected};另有 {n} 個位於範本圖層上 +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected};另有 {n} 個位於隔離的群組之外 +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected};另有 {n} 個現在無法選取 + # Compound Shapes add-on Compound Shapes 複合形狀 Shape Mode Buttons Make Compound Shapes 形狀模式按鈕製作複合形狀 diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index a419204162..ab50fe76dd 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -64,6 +64,8 @@ use bar::{menu_body, pointer_reaches_title}; pub use context::{context_items, context_menu_body, ruler_menu_body, ruler_unit_items}; pub use entries::{MenuEntry, Row, context_entries, entry, menu_entries, pretty_shortcut, shown_shortcut}; pub(crate) use invoke::graph_dialog; +#[cfg(test)] +pub(crate) use invoke::with_held_keys; pub use invoke::{click_target, invoke, invoke_from_system_menu}; #[cfg(test)] pub(crate) use labels::lists_plugin; diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 963eab802f..5b0d0f3c40 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -15,10 +15,13 @@ pub fn click_target(label: &str, id: &str, p: &Value) -> (String, Value) { /// What an in-window menu click on `target` (a [`click_target`]) runs with `held` held: Object › /// Unlock All and Object › Show All chosen with Shift+Alt (Shift+Option) act only inside the groups -/// that hold the selected objects (`scope: "group"`). -pub(super) fn with_held_keys(target: (String, Value), held: egui::Modifiers) -> (String, Value) { +/// that hold the selected objects (`scope: "group"`); Select Linked, Embedded, Missing and Modified +/// chosen with Shift add to the selection (`add: true`). +pub(crate) fn with_held_keys(target: (String, Value), held: egui::Modifiers) -> (String, Value) { match target.0.as_str() { "object.unlockAll" | "object.showAll" if held.shift && held.alt => (target.0, json!({"scope": "group"})), + // Select Linked, Embedded, Missing and Modified with Shift add to the selection. + crate::addons::select::link_status::COMMAND if held.shift => (target.0, crate::addons::select::link_status::with_shift(target.1)), _ => target, } } diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index e9776e78f4..1bb536f76e 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -578,6 +578,7 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::addons::pathtools::corner::open(app), crate::addons::pathtools::shared_edge::COMMAND => crate::addons::pathtools::shared_edge::open(app), crate::addons::arrange::ZOOM => crate::addons::arrange::zoom(app), + crate::addons::select::link_status::COMMAND => crate::addons::select::link_status::run(app, p), crate::addons::document::SAVE_COPY => crate::addons::document::save_copy(app, p), crate::addons::document::EXPORT_ALL => crate::addons::document::export_all(app, p), crate::addons::document::BATCH_TRACE => crate::addons::document::batch_trace(app, p), diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 673ceb81fd..78553cc7bd 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -135,7 +135,7 @@ fn swapped_out(app: &VectorcraftApp, id: &str) -> bool { /// or off), or `None` while they leave it out: an empty slot ([`hidden_when_disabled`]) or an item /// another stands in for ([`swapped_out`]). pub fn shown_state(app: &VectorcraftApp, id: &str, p: &Value) -> Option<(bool, Option)> { - let en = enabled(app, id); + let en = enabled(app, id) && (id != crate::addons::select::link_status::COMMAND || crate::addons::select::link_status::enabled(app, p)); if (!en && hidden_when_disabled(id)) || swapped_out(app, id) { return None; } diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index d924d06f3f..d27603424a 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -4,7 +4,8 @@ //! from the last row clicked without Shift to it (with Ctrl/Cmd, adds them); the buttons Relink, //! Go To, Update and Edit Original act on the selected rows; Link Info shows the details of the //! first. The flyout adds Relink to Folder, Find in Folder (Find Linked Files: -//! `ui.findLinksInFolder`), Embed / Unembed, Placement Options, Show filters, Sort, thumbnail size +//! `ui.findLinksInFolder`), Embed / Unembed, Placement Options, Select Linked / Embedded / Missing / +//! Modified (`addon.select.byLinkStatus`, Shift adds), Show filters, Sort, thumbnail size //! and Show in Folder. //! //! Everything runs through the `links.*` commands (`links.editOriginal` and `links.reveal` are UI @@ -597,6 +598,17 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { crate::menus::invoke(app, "links.reveal", json!({})); } ui.separator(); + // Select Linked, Embedded, Missing and Modified: every such image in the document, not only + // the rows shown; with Shift, added to the selection. + use crate::addons::select::link_status; + for (i, (status, label, _)) in link_status::STATUSES.iter().enumerate() { + if menu_item(ui, tl!(label), app.ui.link_statuses.has.get(i).copied().unwrap_or(false), false) { + let p = json!({ "status": status }); + let p = if ui.input(|i| i.modifiers.shift) { link_status::with_shift(p) } else { p }; + crate::menus::invoke(app, link_status::COMMAND, p); + } + } + ui.separator(); for (id, label) in SHOW { if menu_item(ui, tl!(label), true, o.show == id) { set_options(ui.ctx(), |o| o.show = id); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 2baf6f6ee7..044f3e66bc 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -382,6 +382,11 @@ pub struct UiState { /// is open. Not saved. #[serde(skip)] pub context_intertwine: Option<(u64, vectorcraft_doc::NodeId, vectorcraft_geom::Point, vectorcraft_doc::NodeId)>, + /// Which link statuses the active document's images and placed documents have, for Select › + /// Linked, Embedded, Missing and Modified to be on only when some do (refreshed by + /// [`crate::addons::select::link_status::refresh`]). Not saved. + #[serde(skip)] + pub link_statuses: crate::addons::select::link_status::Present, /// Last tool shown in each toolbar slot (keyed by the slot's first tool id). #[serde(default)] pub slot_tool: std::collections::BTreeMap, @@ -942,6 +947,7 @@ impl Default for UiState { shape_modes_compound: false, context_locked: None, context_intertwine: None, + link_statuses: Default::default(), slot_tool: Default::default(), floating_flyouts: vec![], toolbar_edits: ToolbarEdits::default(), diff --git a/docs/mcp.md b/docs/mcp.md index 1e6fbc2042..fcbb492fdc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6864,6 +6864,30 @@ The dialog lists every artboard with its number, name and size in the document's name; a click chooses one artboard, Shift-click adds a range and Cmd/Ctrl-click toggles one, and Select All / None act on the rows shown (rows hidden by the search stay chosen). It opens with the active artboard chosen and Overlapping. +`addon.select.byLinkStatus {status, ids?, add?, zoom?}` (Select Linked / Embedded / Missing / Modified and Select by +Link Status…, #5526) selects the image objects and placed documents whose link has a status, as `links.list` reports +it: `linked` (its file found unchanged; `links.list` says `ok`), `embedded`, `missing` or `modified` (its file changed +since it was read). `status` is one of them or a list of them (at least one; one listed twice counts once). `ids` picks +only among those objects (other objects among them are passed over); `add: true` adds them to the selection instead of +replacing it; `zoom: true` asks for Zoom to Selection afterwards, which the desktop app runs (`addon.arrange.zoomSelection`) +when something was selected, and which other callers get back as `zoom: true`. 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 left out and listed with the reason. Only the selection changes, so there is nothing to +undo. It returns `{count, selected: [ids] (bottom first), skipped: [{id, reason: hidden|locked|template|isolation}]}`. +A missing or unknown status, an id naming no object, or a value of the wrong type is an error, and the selection is left +as it was. + +```json +{"name":"run_command","arguments":{"command":"addon.select.byLinkStatus","params":{"status":["missing","modified"],"zoom":true}}} +``` + +In the desktop app, Object › Plug-ins › Selection Tools and the Links panel menu have Select Linked, Select Embedded, +Select Missing and Select Modified, each off when no image has that status; with Shift held they add to the selection. +The status bar says what was selected and what was left out, e.g. "Selected 9 missing images; 3 more are hidden or +locked". Select by Link Status… lists every image and placed document with its name, status and format, searches by +name and filters by status (Show), chooses rows with checkboxes (All / None act on the rows shown), and on Select +selects the rows chosen, zooming to them when Zoom to Selection is on (the default). + ### Vector Halftone (live) `addon.color.halftone` (Effect › Color Effects › Vector Halftone…, also in Object › Plug-ins › Color Effects) draws its diff --git a/docs/roadmap.md b/docs/roadmap.md index 6831863a9a..0db3a84355 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-04 · **Change:** minor (Select by Artboards add-on selects by overlap, inside or outside several artboards; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Selection Tools add-on: Select by Link Status selects images and placed documents that are linked, embedded, missing or modified, #5526; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -28,6 +28,7 @@ M7 type: Touch Type moves a right-to-left character along its line and up from i | Date | Change | Summary | |---|---|---| +| 2026-11-05 | minor | Selection Tools add-on: Select Linked, Embedded, Missing and Modified select the images and placed documents with that link status (Object › Plug-ins › Selection Tools and the Links panel menu; Shift adds), and Select by Link Status… lists them by name, status and format to pick from, optionally zooming to them; what is hidden, locked, on a template layer or outside the isolated group is left out and the status bar says how many (#5526, a VectorCraft addition); scores and estimates unchanged (estimated). | | 2026-11-04 | minor | M7: Find Font's Replace With Font lists family and style rows with a search, and the list and the document's font list scroll on their own (#4972); scores and estimates unchanged. | | 2026-11-04 | minor | Selection Tools add-on: Select by Artboards selects the objects overlapping, fully inside or fully outside several chosen artboards, from a dialog that lists, searches and multi-selects the artboards and fits one in the window on double-click (#5525, #5548, #5549, a VectorCraft addition); scores and estimates unchanged. | | 2026-11-04 | minor | New Document: the units chosen in Preset Details belong to the chosen preset; Recent and Saved cards keep the units their document or preset was made in, and the built-in tabs still follow the chosen units (#2078). Scores and estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 004188166e..27b63a9215 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-05 · **Change:** minor (Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; Optical kerning spaces pairs by the font's own stem spacing instead of a fixed tight gap; 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-05 · **Change:** minor (Selection Tools add-on: Select by Link Status selects images and placed documents that are linked, embedded, missing or modified, #5526; 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-05 | minor | Selection Tools add-on: Select Linked, Embedded, Missing and Modified select the images and placed documents with that link status (Object › Plug-ins › Selection Tools and the Links panel menu; Shift adds), and Select by Link Status… lists them by name, status and format to pick from, optionally zooming to them; what is hidden, locked, on a template layer or outside the isolated group is left out and the status bar says how many (#5526, a VectorCraft addition); scores and estimates unchanged (estimated). | | 2026-11-05 | minor | G12: Hyphenation › Default Language sets the language of new type unless Document Setup chose one, stored as a tag; each run hyphenates in its own language, English only so far, so 2 Preferences options stay unused (#394) | | 2026-11-05 | minor | Type Tools add-on: Release Type on a Path (a VectorCraft addition, #5532): evidence added; scores unchanged. | | 2026-11-04 | minor | Path Precision Tools add-on (a VectorCraft addition): Set Corners… and `addon.pathtools.cornerSet` `minAngle`/`maxAngle` round only the corners whose angle is in a range (#5545); evidence added; scores unchanged. | @@ -736,6 +737,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Lasso picks anchor points only on art a click can pick, and the Add Anchor Point, Delete Anchor Point, Anchor Point and Scissors tools pick anchor points and segments only on the selected paths and on art a click can pick: not on a Shaper Group's original shapes outside Construction mode, and in isolation mode only inside the isolated group or object. Smart Guides and Snap to Point do not snap to a Shaper Group's original shapes, and the reference point of the transform tools snaps to one only when it is selected, or under the pointer in Construction mode. Enclosing Lasso provides whole-object enclosure selection under Object › Plug-ins and its own heading in All Tools. It has no default shortcut or Basic toolbar slot. It follows path curves and keeps partially enclosed objects out, including objects crossing a concave part of the loop. Ordinary group members can be selected individually; compound paths remain whole. This is a VectorCraft addition; scores and estimates are unchanged. Select by Artboards (Object › Plug-ins › Selection Tools, a VectorCraft addition: #5525, #5548, #5549) selects the objects overlapping, fully inside or fully outside one or more chosen artboards (`addon.select.byArtboards {artboards, relation}`). Overlapping is All on Active Artboard's test, shared as `select::on_artboard`; Fully inside means within one artboard, edges included; Fully outside means on none. It looks at what Select All takes, so hidden, locked and locked-artboard art stays out. Its dialog lists each artboard's number, name and size in the document's units, filters by name, chooses rows with click, Shift-click and Cmd/Ctrl-click, and fits a row's artboard in the window on double-click (`view.goToArtboard`). Tests: `crates/engine/src/cmd/addons/select/tests.rs`, `crates/ui-egui/src/addons/select/tests.rs`, `crates/engine/tests/command_sweep.rs`. + Select by Link Status (Object › Plug-ins › Selection Tools and the Links panel menu, a VectorCraft addition: #5526) selects the image objects and placed documents whose link is linked (its file found unchanged), embedded, missing or modified, as `links.list` reports it (`addon.select.byLinkStatus {status, ids?, add?, zoom?}`); Select Linked, Embedded, Missing and Modified are off when no image has that status and add to the selection with Shift. Objects that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard, or outside the isolated group are left out (the `select::is_selectable` test) and returned with the reason, and the status bar says how many, in plural forms of every catalog. Select by Link Status… lists each image and placed document with its name, status and format, searches by name, filters by status, picks rows with checkboxes and All / None, and zooms to the selection with the existing Zoom to Selection (`addon.arrange.zoomSelection`). Missing-link markers on the canvas are #5547. Tests: `crates/engine/src/cmd/addons/select/tests.rs` (`by_link_status`), `crates/ui-egui/src/addons/select/link_status/tests.rs`, `crates/engine/tests/command_sweep.rs`. A marquee selects a clip group, or an object on a layer with a clipping mask, only when it reaches the area inside the clipping path, and it measures the art only within that path's bounds. Within the bounds of a mask that is not a rectangle, it can still select art that the mask hides. Direct Selection's marquee still selects the hidden anchor points inside it (#2345). A marquee selects a Shaper Group only when it reaches the art the group shows, not the original shapes kept under it, and Direct Selection's clicks and marquee do not select those shapes' anchor points. In Construction mode a marquee selects the original shapes, and Direct Selection selects their anchor points. While an opacity mask or a pattern is edited, a Shaper double-click on a Shaper Group in the mask or pattern art selects the original shape under the pointer without entering Construction mode, the Shaper Group's mode widget does not show, and a Shaper scribble, Release and Expand keep the editing layer isolated. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index fca5458f04..560fc3edb0 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; Select by Artboards add-on selects by overlap, inside or outside several artboards; Cmd+Space keeps the active drawing cursor during its drag; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Selection Tools add-on: Select by Link Status selects images and placed documents that are linked, embedded, missing or modified, #5526; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) ## Feature submission evidence @@ -30,6 +30,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-05 | minor | Selection Tools add-on: Select Linked, Embedded, Missing and Modified select the images and placed documents with that link status (Object › Plug-ins › Selection Tools and the Links panel menu; Shift adds), and Select by Link Status… lists them by name, status and format to pick from, optionally zooming to them; what is hidden, locked, on a template layer or outside the isolated group is left out and the status bar says how many (#5526, a VectorCraft addition); scores and estimates unchanged (estimated). | | 2026-11-05 | minor | G12: Hyphenation › Default Language sets the language of new type unless Document Setup chose one, stored as a tag; each run hyphenates in its own language, English only so far, so 2 Preferences options stay unused (#394) | | 2026-11-05 | minor | Gradient panel: Delete Stop sits at the right end of the ramp, so it shows whenever the ramp does instead of under the stop fields, where a short panel hid it (#5403); scores and estimates unchanged | | 2026-11-04 | minor | Artboards panel: a Shift- or Ctrl/Cmd-click on a row selects several artboards with any tool, switching to the Artboard tool first, so a preset, orientation, size or Fill set in Properties or the Control bar goes to every selected artboard; Fill used to set the active artboard only (#5698); scores and estimates unchanged | @@ -395,6 +396,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Color Effects add-on (VectorCraft addition): live Exposure, Desaturate and Invert Colors in Effect › Color Effects and Object › Plug-ins › Color Effects; its panel picks a colour adjustment and its values and adds it as a live effect or applies it as a filter, into the colours, as one undo step; Select by Color Kind selects the objects that use spot colours, carry colour effects, or are RGB, CMYK or grayscale images; Vector Halftone draws an object as halftone dots live (the dots Object › Vector Halftone makes), which Expand Appearance and the exporters write as paths; Duotone prints each colour's tone with one to four inks (a tint of a spot tone's swatch, or the CMYK mix of several), live or as a filter, its dialog a row per tone and the picked tone's curve; Print Ink Fixes (a CMYK document's ink limit, white overprint removed, black overprint set) opens its options from the submenu and the panel's Inks | done | `addon.color.*`, `crates/ui-egui/src/addons/color.rs` and its tests; not a feature of the reference app, so it is not scored | | Color Effects add-on (VectorCraft addition): Object › Plug-ins › Color Effects › Find Nearest Swatch… picks a Library (Document Swatches, a built-in library, or a library or colour book the user saved or loaded) and Fill and Stroke, lists each colour of the selection with its three closest swatches (chip, name, ΔE 2000), and Apply gives each colour its nearest swatch (global and spot swatches linked; a library's swatches added to the document first), one undo step | done | #4923; `addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, `crates/engine/src/cmd/addons/color/nearest.rs`, `crates/ui-egui/src/addons/color/nearest.rs` and their tests; not a feature of the reference app, so it is not scored | | Selection Tools add-on (VectorCraft addition): Object › Plug-ins › Selection Tools › Select by Artboards… lists every artboard (number, name, width × height in the document's units), filters them by name, chooses several (click, Shift-click for a range, Cmd/Ctrl-click to toggle; Select All / None act on the rows shown; a count of those chosen), fits a row's artboard in the window on double-click and makes it active, and on OK selects the objects overlapping, fully inside or fully outside the chosen artboards (Overlapping is All on Active Artboard's test) | done | #5525, #5548, #5549; `addon.select.byArtboards`, `crates/engine/src/cmd/addons/select.rs`, `crates/ui-egui/src/addons/select.rs` and their tests; not a feature of the reference app | +| Selection Tools add-on (VectorCraft addition): Select Linked, Select Embedded, Select Missing and Select Modified in Object › Plug-ins › Selection Tools and the Links panel menu (off when no image has that status; Shift adds to the selection) select the images and placed documents with that link status, leaving out hidden, locked, template-layer and outside-isolation ones, which the status bar counts (e.g. "Selected 9 missing images; 3 more are hidden or locked"); Select by Link Status… lists them with name, status and format, searches by name, filters by status, picks with checkboxes and All / None, and selects with Zoom to Selection on by default | done | #5526; `addon.select.byLinkStatus`, `crates/engine/src/cmd/addons/select.rs`, `crates/ui-egui/src/addons/select/link_status.rs` and their tests; not a feature of the reference app | ## Look and feel From 96505d3a77c79e65ecdfe9635ecb8ae02f75072e Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Thu, 5 Nov 2026 12:37:16 +0530 Subject: [PATCH 050/196] Fix #5526: document the functions the link-status selection touches Doc comments for the Select add-on commands, the Select by Link Status dialog body, the Links panel menu and the test helpers (review: docstring coverage). Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/addons/select.rs | 6 ++++++ crates/engine/src/cmd/addons/select/tests.rs | 6 ++++++ crates/ui-egui/src/addons/select/link_status.rs | 3 +++ crates/ui-egui/src/addons/select/link_status/tests.rs | 2 ++ crates/ui-egui/src/panels/links.rs | 2 ++ 5 files changed, 19 insertions(+) diff --git a/crates/engine/src/cmd/addons/select.rs b/crates/engine/src/cmd/addons/select.rs index 4d71895c01..b2ab59d851 100644 --- a/crates/engine/src/cmd/addons/select.rs +++ b/crates/engine/src/cmd/addons/select.rs @@ -25,6 +25,7 @@ pub const RELATIONS: [&str; 3] = ["overlap", "inside", "outside"]; /// in the document, a file not found, a file changed since it was read. pub const LINK_STATUSES: [&str; 4] = ["linked", "embedded", "missing", "modified"]; +/// The add-on's commands: Select by Artboards and Select by Link Status. pub fn specs() -> Vec { vec![ cmd!( @@ -48,6 +49,8 @@ pub fn specs() -> Vec { ] } +/// `addon.select.byArtboards`: select the objects Select All takes that overlap, lie inside or lie +/// outside the chosen artboards. fn by_artboards(s: &mut Session, p: &Value) -> Result { const C: &str = "addon.select.byArtboards"; let relation = text_param(p, "relation", C)?.unwrap_or("overlap"); @@ -151,6 +154,9 @@ fn skip_reason(st: &DocState, locks: &LockedArtboards, id: NodeId) -> Option<&'s }) } +/// `addon.select.byLinkStatus`: select the images and placed documents whose link has one of the +/// statuses asked for (among `ids` when given), replacing the selection or adding to it, and list +/// those left out with the reason ([`skip_reason`]). fn by_link_status(s: &mut Session, p: &Value) -> Result { const C: &str = "addon.select.byLinkStatus"; let wanted = link_statuses(p, C)?; diff --git a/crates/engine/src/cmd/addons/select/tests.rs b/crates/engine/src/cmd/addons/select/tests.rs index ca59565261..c97b278258 100644 --- a/crates/engine/src/cmd/addons/select/tests.rs +++ b/crates/engine/src/cmd/addons/select/tests.rs @@ -150,6 +150,8 @@ mod by_link_status { _dir: Folder, } + /// [`Links`] in a fresh folder named after `name`: the files placed, then one changed and two + /// removed. fn links(name: &str) -> Links { let dir = Folder::new(name); let (a, b, c, e, d) = (dir.file("ok.png"), dir.file("changes.png"), dir.file("goes.png"), dir.file("kept.png"), dir.file("page.vectorcraft")); @@ -168,19 +170,23 @@ mod by_link_status { Links { s, ok, modified, missing, embedded, document, _dir: dir } } + /// Run the command with `p`, which must succeed. fn run(s: &mut Session, p: Value) -> Value { s.execute(C, &p).unwrap_or_else(|e| panic!("{p}: {e}")) } + /// `v` sorted. fn sorted(mut v: Vec) -> Vec { v.sort(); v } + /// The selected objects, sorted. fn selection(s: &Session) -> Vec { sorted(s.doc().unwrap().selection.objects.clone()) } + /// The ids of a JSON list, sorted. fn ids(v: &Value) -> Vec { sorted(v.as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()) } diff --git a/crates/ui-egui/src/addons/select/link_status.rs b/crates/ui-egui/src/addons/select/link_status.rs index 7b7203276c..0b367a7ba0 100644 --- a/crates/ui-egui/src/addons/select/link_status.rs +++ b/crates/ui-egui/src/addons/select/link_status.rs @@ -138,6 +138,7 @@ pub(crate) fn message(statuses: &[&str], count: u64, reasons: &[&str]) -> String }; let Some(first) = reasons.first() else { return selected }; // Hidden and locked go together; a template layer, or the isolated group, alone. + /// The group reason `r` is told in: hidden and locked are one. fn kind(r: &str) -> &str { match r { "hidden" | "locked" => "locked", @@ -217,6 +218,8 @@ fn status_label(status: &str) -> &'static str { STATUSES.iter().find(|(s, ..)| *s == status).map_or("", |&(.., label)| tl!(label)) } +/// The dialog: the search, the Show filter, a checkbox row per image shown (name, status, format), +/// All / None with the count chosen, and Zoom to Selection. Returns false: nothing to preview. fn body(_app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { let t = Tokens::get(ui.ctx()); let rows: Vec = d.fields.get("__rows").and_then(Value::as_array).cloned().unwrap_or_default(); diff --git a/crates/ui-egui/src/addons/select/link_status/tests.rs b/crates/ui-egui/src/addons/select/link_status/tests.rs index 22b07ccace..8ad61f6e5a 100644 --- a/crates/ui-egui/src/addons/select/link_status/tests.rs +++ b/crates/ui-egui/src/addons/select/link_status/tests.rs @@ -28,6 +28,7 @@ impl Drop for Folder { } } +/// A `w` × `h` red PNG. fn png(w: u32, h: u32) -> Vec { let mut out = vec![]; image::RgbaImage::from_pixel(w, h, image::Rgba([200, 40, 40, 255])) @@ -53,6 +54,7 @@ fn app(dir: &Folder) -> (VectorcraftApp, u64, u64, u64) { (app, river, harbour, stamp) } +/// The selected objects' ids, sorted. fn selected(app: &VectorcraftApp) -> Vec { let mut ids: Vec = app.session.active().unwrap().selection.objects.iter().map(|id| id.0).collect(); ids.sort_unstable(); diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index d27603424a..a7fe30185f 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -535,6 +535,8 @@ fn link_info(ui: &mut Ui, info: Option<&Value>, units: vectorcraft_doc::Unit) { row(ui, tl!("Status"), status.into()); } +/// The panel's flyout menu: the link commands for the selected rows, Select Linked / Embedded / +/// Missing / Modified for the whole document, and the Show, Sort and thumbnail options. pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let o = options(ui.ctx()); // The rows the panel shows (the menu opens from it). From 50128e6025fd7c07494b8ad0873c01549e2600fe Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 19:47:11 -0800 Subject: [PATCH 051/196] Render: adding or deleting an anchor of a long path splices the kept path When anchors of a kept path (a path or compound path of 1,024 anchors or more) are added or deleted, or a subpath is closed or opened, the next frame writes again only the path elements from the first anchor that changed to the last, and the closing segment and ClosePath when an end anchor changed or the subpath was closed or opened. The elements after the change move with it. Before, such an edit made the whole path again and measured it whole. - The runs of segments now carry their own ends. The runs that held the segments written become one run, split into runs of 128 when it grows past 256, and only those runs are measured again, with the miter tips of the run of the segment with length before each span. When a subpath is closed or opened and the stroke reaches farther from one than from the other, all of that subpath's tips are measured again. - On a subpath that is open before and after the edit, the handle before the first anchor and the one after the last are not compared, so Delete Anchor Point, which clears them, writes again only the segments around the anchor deleted. - A subpath that has fewer than two anchors before or after the edit is written again whole. A compound path member that gains or loses subpaths is made again. When members are added or removed, those members and every member between the first and the last of them are made again, and the members before and after them stay. - An edit that adds or deletes anchors in, closes or opens more than 16 subpaths makes the whole path again, as before. - An edit that leaves every anchor as it was, such as a new stroke, leaves the kept path as it is. The pixels and the cull bounds are the same as with a path made again. Docs: docs/target-app-parity.md. --- crates/render/src/kept_paths.rs | 487 ++++++++++++++++++++++------ crates/render/src/tests/keptpath.rs | 202 +++++++++++- docs/target-app-parity.md | 1 + 3 files changed, 579 insertions(+), 111 deletions(-) diff --git a/crates/render/src/kept_paths.rs b/crates/render/src/kept_paths.rs index 4525a0f1c3..dc48d3cafb 100644 --- a/crates/render/src/kept_paths.rs +++ b/crates/render/src/kept_paths.rs @@ -1,25 +1,39 @@ //! The paths of long paths and compound paths kept by object id, with the boxes of their segments //! and of their miter tips by runs of segments. When an object's anchors move, the renderer changes -//! only the path elements, boxes and tips of the segments that start or end at a moved anchor, -//! instead of making its path again and measuring it whole. +//! only the path elements, boxes and tips of the segments that start or end at a moved anchor. +//! When anchors are added or deleted, or a subpath is closed or opened, it replaces only the path +//! elements of the segments between the first and the last anchor that changed, and measures again +//! only the runs that hold them. When a compound path gains or loses members, or a member gains or +//! loses subpaths, it makes the path of those members again. In each case it does not make the +//! object's path again or measure it whole. use std::sync::Arc; use vectorcraft_doc::{LineJoin, Node, NodeKind, StrokeLayer}; use vectorcraft_geom::bez::has_length; use vectorcraft_geom::path::segment_bounds; -use vectorcraft_geom::{Anchor, BezPath, PathData, PathEl, PathSeg, Rect, SubPath}; +use vectorcraft_geom::{Anchor, BezPath, PathData, PathEl, PathSeg, Point, Rect, SubPath}; /// Paths and compound paths with at least this many anchors are kept ([`KeptPath`]). pub(crate) const KEPT_ANCHORS: usize = 1024; -/// Segments measured together into one box. -const RUN: usize = 128; +/// Segments measured together into one box in a subpath measured whole. A run that anchors were +/// added to or deleted from holds more or fewer, and one that grows past twice this is split. +pub(crate) const RUN: usize = 128; + +/// The most subpaths one edit may add anchors to, delete anchors from, close or open: past this, +/// the kept path is made again whole. +const SPLICES: usize = 16; /// The boxes and the miter tips' boxes of a subpath's runs ([`KeptPath::runs`]). #[cfg(test)] pub(crate) type RunBoxes = (Vec>, Vec>); +/// A subpath's MoveTo, segments and anchors, whether it is closed, and the segments of each of its +/// runs ([`KeptPath::layout`]). +#[cfg(test)] +pub(crate) type Layout = ((usize, usize, usize, bool), Vec); + /// A subpath of a kept path. struct Sub { /// Where its MoveTo is in the path's elements. @@ -28,7 +42,9 @@ struct Sub { segs: usize, anchors: usize, closed: bool, - /// The box of each run of [`RUN`] segments ([`segment_bounds`]). + /// The segment after the last of each run of segments. + ends: Vec, + /// The box of each run of segments ([`segment_bounds`]). boxes: Vec>, /// The box of the miter tips of `tips_of` at the joints whose first segment is in each run. tips: Vec>, @@ -72,8 +88,14 @@ pub(crate) fn kept(n: &Node) -> bool { /// Whether anchors `a` and `b` have the same points, bit for bit. fn same(a: &Anchor, b: &Anchor) -> bool { - let bits = |a: &Anchor| [a.p.x, a.p.y, a.h_in.x, a.h_in.y, a.h_out.x, a.h_out.y].map(f64::to_bits); - bits(a) == bits(b) + same_drawn(a, b, true, true) +} + +/// Whether anchors `a` and `b` have the same point, bit for bit, and the same incoming handle when +/// `h_in` and outgoing handle when `h_out`. +fn same_drawn(a: &Anchor, b: &Anchor, h_in: bool, h_out: bool) -> bool { + let bits = |p: Point| [p.x, p.y].map(f64::to_bits); + bits(a.p) == bits(b.p) && (!h_in || bits(a.h_in) == bits(b.h_in)) && (!h_out || bits(a.h_out) == bits(b.h_out)) } /// The path element of segment `i` of `sp`, as [`SubPath::to_bezpath_into`] writes it. @@ -82,15 +104,62 @@ fn element(sp: &SubPath, i: usize) -> PathEl { if sp.segment_is_line(i) { PathEl::LineTo(c.p3) } else { PathEl::CurveTo(c.p1, c.p2, c.p3) } } +/// Element `o` of the elements [`SubPath::to_bezpath_into`] writes for `sp`, a subpath with +/// anchors: its MoveTo, then its segments, then its ClosePath. +fn element_at(sp: &SubPath, o: usize) -> PathEl { + match o { + 0 => PathEl::MoveTo(sp.anchors.first().map_or(Point::ORIGIN, |a| a.p)), + o if o <= sp.segment_count() => element(sp, o - 1), + _ => PathEl::ClosePath, + } +} + /// The point a path element ends at (`None` for a ClosePath). -fn end(el: &PathEl) -> Option { +fn end(el: &PathEl) -> Option { match *el { PathEl::MoveTo(p) | PathEl::LineTo(p) | PathEl::QuadTo(_, p) | PathEl::CurveTo(_, _, p) => Some(p), PathEl::ClosePath => None, } } +/// The ends of the runs of a subpath of `segs` segments measured whole: [`RUN`] segments each. +fn whole_runs(segs: usize) -> Vec { + (1..=segs.div_ceil(RUN)).map(|r| (r * RUN).min(segs)).collect() +} + +/// The paths `ps` written over the `len` elements at `at` in `els`, and their subpaths measured +/// whole with the tips of `st`. `at` moves past them. +fn made_again(ps: &[&PathData], len: usize, els: &mut Vec, at: &mut usize, st: Option<&StrokeLayer>) -> Vec> { + let mut bp = BezPath::new(); + ps.iter().flat_map(|p| &p.subpaths).for_each(|sp| sp.to_bezpath_into(&mut bp)); + let to = (*at + len).min(els.len()); + els.splice((*at).min(to)..to, bp.into_elements()); + let mut measure = |sp: &SubPath| { + let sub = Sub::measured(sp, *at, els, st); + *at += sub.len(); + sub + }; + ps.iter().map(|p| p.subpaths.iter().map(&mut measure).collect()).collect() +} + impl Sub { + /// Subpath `sp`, its MoveTo at `start` in `els`, measured whole, with the tips of `st`. + fn measured(sp: &SubPath, start: usize, els: &[PathEl], st: Option<&StrokeLayer>) -> Self { + let segs = sp.segment_count(); + let mut sub = Sub { start, segs, anchors: sp.anchors.len(), closed: sp.closed, ends: whole_runs(segs), boxes: vec![], tips: vec![] }; + sub.boxes = (0..sub.runs()).map(|r| sub.run_box(els, r)).collect(); + if let Some(st) = st { + sub.tips = (0..sub.runs()).map(|r| sub.run_tips(els, r, st)).collect(); + } + sub + } + + /// Its elements in the path: none without anchors, otherwise its MoveTo, its segments and + /// its ClosePath when closed. + fn len(&self) -> usize { + if self.anchors == 0 { 0 } else { 1 + self.segs + usize::from(self.closed) } + } + /// Segment `i`, as kurbo's `segments` makes it from the path's elements. fn seg(&self, els: &[PathEl], i: usize) -> Option { let p0 = end(els.get(self.start + i)?)?; @@ -103,12 +172,23 @@ impl Sub { } fn runs(&self) -> usize { - self.segs.div_ceil(RUN) + self.ends.len() + } + + /// The segments of run `r`. + fn range(&self, r: usize) -> std::ops::Range { + let from = r.checked_sub(1).and_then(|p| self.ends.get(p)).copied().unwrap_or(0); + from..self.ends.get(r).copied().unwrap_or(from) + } + + /// The run that holds segment `i` (the last run for a segment past the end). + fn run_of(&self, i: usize) -> usize { + self.ends.partition_point(|&e| e <= i).min(self.runs().saturating_sub(1)) } /// The box of the segments of run `r`. fn run_box(&self, els: &[PathEl], r: usize) -> Option { - (r * RUN..((r + 1) * RUN).min(self.segs)).filter_map(|i| self.seg(els, i)).map(segment_bounds).reduce(|a, b| a.union(b)) + self.range(r).filter_map(|i| self.seg(els, i)).map(segment_bounds).reduce(|a, b| a.union(b)) } /// The segment with length that follows segment `i` (round to the start when closed), or @@ -140,7 +220,7 @@ impl Sub { /// ([`StrokeLayer::miter_tip`]). fn run_tips(&self, els: &[PathEl], r: usize, st: &StrokeLayer) -> Option { let mut out: Option = None; - for i in r * RUN..((r + 1) * RUN).min(self.segs) { + for i in self.range(r) { let Some(a) = self.seg(els, i).filter(has_length) else { continue }; let Some(b) = self.next_drawn(els, i) else { continue }; if let Some(tip) = st.miter_tip(self.closed, &a, &b) { @@ -149,6 +229,200 @@ impl Sub { } out } + + /// Bring the subpath, its MoveTo now at `at` in `els`, up to date from `was` to `now`, with the + /// tips of `st`. + fn update(&mut self, was: &SubPath, now: &SubPath, at: usize, els: &mut Vec, st: Option<&StrokeLayer>) { + self.start = at; + if was.anchors.len() == now.anchors.len() && was.closed == now.closed { + self.moved(was, now, els, st); + } else if was.anchors.len() < 2 || now.anchors.len() < 2 { + let to = (at + self.len()).min(els.len()); + let len = if now.anchors.is_empty() { 0 } else { 1 + now.segment_count() + usize::from(now.closed) }; + els.splice(at.min(to)..to, (0..len).map(|o| element_at(now, o))); + *self = Sub::measured(now, at, els, st); + } else { + self.spliced(was, now, els, st); + } + } + + /// [`Self::update`] for a subpath with the same anchor count and closed state: the elements of + /// the segments that start or end at an anchor that moved are made again, with the boxes of + /// their runs and the tips of those runs and of the runs of the segments with length before + /// them. + fn moved(&mut self, was: &SubPath, now: &SubPath, els: &mut [PathEl], st: Option<&StrokeLayer>) { + let (mut first, mut segs) = (false, vec![]); + for (k, (a, b)) in was.anchors.iter().zip(&now.anchors).enumerate() { + if same(a, b) { + continue; + } + if k >= 1 && k - 1 < self.segs { + segs.push(k - 1); + } + if k == 0 { + first = true; + if self.closed && self.segs > 0 { + segs.push(self.segs - 1); + } + } + if k < self.segs { + segs.push(k); + } + } + if !first && segs.is_empty() { + return; + } + segs.sort_unstable(); + segs.dedup(); + if first && let (Some(a), Some(el)) = (now.anchors.first(), els.get_mut(self.start)) { + *el = PathEl::MoveTo(a.p); + } + for &i in &segs { + if let Some(el) = els.get_mut(self.start + 1 + i) { + *el = element(now, i); + } + } + let els: &[PathEl] = els; + // Many moved: the subpath is measured again whole. + let all = segs.len() * 4 > self.segs; + let mut boxes: Vec = if all { (0..self.runs()).collect() } else { segs.iter().map(|&i| self.run_of(i)).collect() }; + boxes.dedup(); + for r in boxes { + let b = self.run_box(els, r); + if let Some(slot) = self.boxes.get_mut(r) { + *slot = b; + } + } + let Some(st) = st else { return }; + // A joint's tip changes with its segments and with which segment with length comes next: + // the runs of the moved segments and of the segments with length before them. + let mut runs = vec![]; + let mut whole = all; + for &i in &segs { + runs.push(self.run_of(i)); + match self.prev_drawn(els, i) { + Ok(Some(j)) => runs.push(self.run_of(j)), + Ok(None) => {} + Err(()) => whole = true, + } + } + self.measure_tips(els, runs, whole, st); + } + + /// [`Self::update`] for a subpath of at least two anchors before and after that gained or lost + /// anchors or was closed or opened. Its elements from the first anchor that changed to the + /// last are written again, and the closing segment and the ClosePath when the first or last + /// anchor changed or it was closed or opened; the elements before and after stay. The runs + /// that held the segments written are measured again, with the tips of the runs of the + /// segments with length before them. + fn spliced(&mut self, was: &SubPath, now: &SubPath, els: &mut Vec, st: Option<&StrokeLayer>) { + let (n0, n1) = (was.anchors.len(), now.anchors.len()); + let least = n0.min(n1); + // On a subpath open before and after, the handle before the first anchor and the one after + // the last draw nothing. + let open = !was.closed && !now.closed; + let a = was.anchors.iter().zip(&now.anchors).enumerate().take_while(|(i, (x, y))| same_drawn(x, y, !open || *i > 0, true)).count().min(least); + let b = was + .anchors + .iter() + .rev() + .zip(now.anchors.iter().rev()) + .take(least - a) + .enumerate() + .take_while(|(i, (x, y))| same_drawn(x, y, true, !open || *i > 0)) + .count(); + let (s0, s1) = (self.segs, now.segment_count()); + let (c0, c1) = (self.closed, now.closed); + let (len0, len1) = (1 + s0 + usize::from(c0), 1 + s1 + usize::from(c1)); + // Elements `a..mid` change: the MoveTo when the first anchor changed and the segments up + // to the first of those between the last `b` anchors. + let (mid0, mid1) = ((1 + n0 - b).min(1 + s0), (1 + n1 - b).min(1 + s1)); + // Elements `tail..len` follow the segments between the last `b` anchors: the closing + // segment and the ClosePath. They stay when the anchors either side of the closing segment + // stayed and the subpath was neither closed nor opened. + let (tail0, tail1) = if b >= 1 { (n0, n1) } else { (mid0, mid1) }; + let keep_tail = c0 == c1 && (!c1 || b == 0 || a >= 1); + let at = self.start; + let mut stale = vec![false; self.runs()]; + let tips = st.is_some(); + if !keep_tail { + let to = (at + len0).min(els.len()); + els.splice((at + tail0).min(to)..to, (tail1..len1).map(|o| element_at(now, o))); + let (lo, old, new) = (tail0 - 1, (1 + s0).saturating_sub(tail0), (1 + s1).saturating_sub(tail1)); + self.resize(lo, old, new, &mut stale, tips); + } + let to = (at + mid0).min(els.len()); + els.splice((at + a).min(to)..to, (a..mid1).map(|o| element_at(now, o))); + let lo = a.max(1) - 1; + self.resize(lo, mid0 - 1 - lo, mid1 - 1 - lo, &mut stale, tips); + self.anchors = n1; + self.closed = c1; + let els: &[PathEl] = els; + for (r, _) in stale.iter().enumerate().filter(|(_, s)| **s) { + let b = self.run_box(els, r); + if let Some(slot) = self.boxes.get_mut(r) { + *slot = b; + } + } + let Some(st) = st else { return }; + let mut runs: Vec = stale.iter().enumerate().filter(|(_, s)| **s).map(|(r, _)| r).collect(); + // Closed or opened: the tips of every joint change when the stroke reaches farther from one + // than from the other. + let mut whole = c0 != c1 && st.side_reach(c0).to_bits() != st.side_reach(c1).to_bits(); + for i in [lo].into_iter().chain((!keep_tail).then_some(tail1 - 1)) { + match self.prev_drawn(els, i) { + Ok(Some(j)) => runs.push(self.run_of(j)), + Ok(None) => {} + Err(()) => whole = true, + } + } + self.measure_tips(els, runs, whole, st); + } + + /// Replace the `old` segments from segment `lo` with `new` segments in the runs: the runs that + /// held them become one run, split into runs of [`RUN`] segments when longer than twice that, + /// whose boxes and (with `tips`) tips are marked in `stale` to be measured again. + fn resize(&mut self, lo: usize, old: usize, new: usize, stale: &mut Vec, tips: bool) { + if old == 0 && new == 0 { + return; + } + let (r0, r1, first, last) = match self.runs() { + 0 => (0, 0, 0, new), + _ => { + let r0 = self.run_of(lo); + let r1 = if old == 0 { r0 } else { self.run_of(lo + old - 1) }; + let last = self.ends.get(r1).copied().unwrap_or(lo + old) + new - old; + (r0, r1 + 1, self.range(r0).start, last) + } + }; + let len = last - first; + let count = if len > 2 * RUN { len.div_ceil(RUN) } else { usize::from(len > 0) }; + for e in self.ends.iter_mut().skip(r1) { + *e = *e + new - old; + } + self.ends.splice(r0..r1, (1..=count).map(|j| if j == count { last } else { first + j * RUN })); + self.boxes.splice(r0..r1, std::iter::repeat_n(None, count)); + if tips { + self.tips.splice(r0.min(self.tips.len())..r1.min(self.tips.len()), std::iter::repeat_n(None, count)); + } + stale.splice(r0..r1, std::iter::repeat_n(true, count)); + self.segs = self.segs + new - old; + } + + /// Measure again the tips of `st` in `runs`, or in every run when `whole`. + fn measure_tips(&mut self, els: &[PathEl], mut runs: Vec, whole: bool, st: &StrokeLayer) { + if whole { + runs = (0..self.runs()).collect(); + } + runs.sort_unstable(); + runs.dedup(); + for r in runs { + let t = self.run_tips(els, r, st); + if let Some(slot) = self.tips.get_mut(r) { + *slot = t; + } + } + } } /// What [`KeptPath::tips`] measures `st`'s tips by: its reach from an open and a closed path and @@ -157,6 +431,24 @@ fn tips_key(st: &StrokeLayer) -> [u64; 3] { [st.side_reach(false).to_bits(), st.side_reach(true).to_bits(), st.miter_limit.to_bits()] } +/// Whether the subpaths of `was` and `now` differ: in number, in anchors or in being closed. +fn differs(was: &PathData, now: &PathData) -> bool { + !std::ptr::eq(was, now) + && (was.subpaths.len() != now.subpaths.len() + || was.subpaths.iter().zip(&now.subpaths).any(|(w, p)| { + w.closed != p.closed || w.anchors.len() != p.anchors.len() || w.anchors.iter().zip(&p.anchors).any(|(a, b)| !same(a, b)) + })) +} + +/// The subpaths of `was` and `now`, paths with as many subpaths, whose anchors were added or +/// deleted or that were closed or opened. +fn splices(was: &PathData, now: &PathData) -> usize { + if std::ptr::eq(was, now) || was.subpaths.len() != now.subpaths.len() { + return 0; + } + was.subpaths.iter().zip(&now.subpaths).filter(|(w, p)| w.anchors.len() != p.anchors.len() || w.closed != p.closed).count() +} + impl KeptPath { /// The kept path of `n`, or `None` when it has none ([`kept`]). pub(crate) fn new(n: &Arc, stamp: u64) -> Option { @@ -170,12 +462,8 @@ impl KeptPath { for pd in paths(n)? { let mut subs = vec![]; for sp in &pd.subpaths { - let segs = sp.segment_count(); - let mut sub = Sub { start, segs, anchors: sp.anchors.len(), closed: sp.closed, boxes: vec![], tips: vec![] }; - sub.boxes = (0..sub.runs()).map(|r| sub.run_box(els, r)).collect(); - if !sp.anchors.is_empty() { - start += 1 + segs + usize::from(sp.closed); - } + let sub = Sub::measured(sp, start, els, None); + start += sub.len(); subs.push(sub); } parts.push(subs); @@ -183,106 +471,79 @@ impl KeptPath { (start == els.len()).then(|| Self { node: n.clone(), path: Arc::new(path), parts, tips_of: None, stamp }) } - /// Bring the path up to date with `n`, a path with the same subpaths and anchor counts as the - /// object it was made from: the elements of the segments that start or end at an anchor that - /// moved are made again, with the boxes of their runs and the tips of those runs and of the - /// runs of the segments with length before them. False, and nothing changed, when `n` has - /// other subpaths, other anchor counts or no kept path. + /// Bring the path up to date with `n`, a later version of the object it was made from. The + /// subpaths whose anchors moved change as [`Sub::moved`] says, and those whose anchors were + /// added or deleted or that were closed or opened as [`Sub::spliced`] says. A member of a + /// compound path that gained or lost subpaths is made again, and so are the members added + /// between the first and the last member that the edit left as they were, when the edit added + /// or removed members. False, and nothing changed, when `n` has no kept path, or when the edit + /// added or deleted anchors in or closed or opened more than [`SPLICES`] subpaths. False as well + /// when the path written does not end where the subpaths measured end. The renderer makes the + /// path again whole after a false. pub(crate) fn update(&mut self, n: &Arc) -> bool { let old = self.node.clone(); let (Some(was), Some(now)) = (paths(&old), paths(n)) else { return false }; - let shape = - |ps: &[&PathData]| ps.iter().map(|p| p.subpaths.iter().map(|s| (s.anchors.len(), s.closed)).collect::>()).collect::>(); - if !kept(n) || shape(&was) != shape(&now) { + if !kept(n) || self.parts.len() != was.len() || self.parts.iter().zip(&was).any(|(s, p)| s.len() != p.subpaths.len()) { return false; } - // Per subpath whose anchors moved: (member, subpath, whether its first anchor moved, the - // segments that start or end at a moved anchor). - let mut moved: Vec<(usize, usize, bool, Vec)> = vec![]; - for (pi, (w, p)) in was.iter().zip(&now).enumerate() { - if std::ptr::eq(*w, *p) { - continue; - } - for (si, (ws, ps)) in w.subpaths.iter().zip(&p.subpaths).enumerate() { - let Some(sub) = self.parts.get(pi).and_then(|s| s.get(si)) else { return false }; - let (mut first, mut segs) = (false, vec![]); - for (k, (a, b)) in ws.anchors.iter().zip(&ps.anchors).enumerate() { - if same(a, b) { - continue; - } - if k >= 1 && k - 1 < sub.segs { - segs.push(k - 1); - } - if k == 0 { - first = true; - if sub.closed && sub.segs > 0 { - segs.push(sub.segs - 1); - } - } - if k < sub.segs { - segs.push(k); - } - } - if first || !segs.is_empty() { - segs.sort_unstable(); - segs.dedup(); - moved.push((pi, si, first, segs)); - } - } + // The members paired with one of `was`: all when there are as many, otherwise those + // before the first and after the last that is not the same. The others are made again. + let (head, tail) = if was.len() == now.len() { + (was.len(), 0) + } else { + let head = was.iter().zip(&now).take_while(|(w, p)| std::ptr::eq(**w, **p)).count(); + let rest = (was.len() - head).min(now.len() - head); + (head, was.iter().rev().zip(now.iter().rev()).take(rest).take_while(|(w, p)| std::ptr::eq(**w, **p)).count()) + }; + let paired = |i: usize| if i < head { Some(i) } else { (now.len() - i <= tail).then(|| was.len() - (now.len() - i)) }; + let spliced: usize = (0..now.len()).filter_map(|i| paired(i).map(|w| splices(was[w], now[i]))).sum(); + if spliced > SPLICES { + return false; } self.node = n.clone(); - if moved.is_empty() { + // Nothing to change: the path is left as it is, shared or not. + if was.len() == now.len() && was.iter().zip(&now).all(|(w, p)| !differs(w, p)) { return true; } + let st = self.tips_of.clone(); + let st = st.as_ref(); let path = Arc::make_mut(&mut self.path); - let els = path.elements_mut(); - for (pi, si, first, segs) in &moved { - let (Some(sub), Some(sp)) = (self.parts.get(*pi).and_then(|s| s.get(*si)), now.get(*pi).and_then(|p| p.subpaths.get(*si))) else { + let mut els = std::mem::take(path).into_elements(); + let mut old_parts: Vec>> = std::mem::take(&mut self.parts).into_iter().map(Some).collect(); + let mut at = 0; + let mut parts = Vec::with_capacity(now.len()); + for (i, p) in now.iter().enumerate() { + if i == head { + // The members of `was` that are not paired give way to those of `now`. + let gone: usize = old_parts[head..was.len() - tail].iter_mut().flat_map(|s| s.take().into_iter().flatten()).map(|s| s.len()).sum(); + parts.extend(made_again(&now[head..now.len() - tail], gone, &mut els, &mut at, st)); + } + let Some(w) = paired(i) else { continue }; + let Some(mut subs) = old_parts.get_mut(w).and_then(Option::take) else { continue }; + if was[w].subpaths.len() != p.subpaths.len() { + let len = subs.iter().map(Sub::len).sum(); + parts.extend(made_again(&[*p], len, &mut els, &mut at, st)); continue; - }; - if *first && let (Some(a), Some(el)) = (sp.anchors.first(), els.get_mut(sub.start)) { - *el = PathEl::MoveTo(a.p); } - for &i in segs { - if let Some(el) = els.get_mut(sub.start + 1 + i) { - *el = element(sp, i); + let moved = !std::ptr::eq(was[w], *p); + for (sub, (ws, ps)) in subs.iter_mut().zip(was[w].subpaths.iter().zip(&p.subpaths)) { + if moved { + sub.update(ws, ps, at, &mut els, st); } + sub.start = at; + at += sub.len(); } + parts.push(subs); } - let els = path.elements(); - for (pi, si, _, segs) in moved { - let tips_of = self.tips_of.as_ref(); - let Some(sub) = self.parts.get_mut(pi).and_then(|s| s.get_mut(si)) else { continue }; - // Many moved: the subpath is measured again whole. - let all = segs.len() * 4 > sub.segs; - let mut boxes: Vec = if all { (0..sub.runs()).collect() } else { segs.iter().map(|i| i / RUN).collect() }; - boxes.dedup(); - for r in boxes { - sub.boxes[r] = sub.run_box(els, r); - } - let Some(st) = tips_of else { continue }; - // A joint's tip changes with its segments and with which segment with length comes - // next: the runs of the moved segments and of the segments with length before them. - let mut runs = vec![]; - let mut whole = all; - for &i in &segs { - runs.push(i / RUN); - match sub.prev_drawn(els, i) { - Ok(Some(j)) => runs.push(j / RUN), - Ok(None) => {} - Err(()) => whole = true, - } - } - if whole { - runs = (0..sub.runs()).collect(); - } - runs.sort_unstable(); - runs.dedup(); - for r in runs { - sub.tips[r] = sub.run_tips(els, r, st); - } + if head == now.len() && head < was.len() { + // Members were removed from the end. + let gone: usize = old_parts[head..].iter_mut().flat_map(|s| s.take().into_iter().flatten()).map(|s| s.len()).sum(); + parts.extend(made_again(&[], gone, &mut els, &mut at, st)); } - true + let made = at == els.len(); + *path = BezPath::from_vec(els); + self.parts = parts; + made } /// The object's geometric bounds ([`Node::geometric_bounds`]): each path's as @@ -318,9 +579,25 @@ impl KeptPath { self.parts.iter().flatten().flat_map(|s| s.tips.iter().flatten()).copied().reduce(|a, b| a.union(b)) } - /// The boxes and tips kept per run of each subpath, and the stroke the tips were measured for. + /// Each subpath's MoveTo, segments and anchors, whether it is closed, and the segments of each + /// of its runs. #[cfg(test)] - pub(crate) fn runs(&self) -> (Vec, Option) { - (self.parts.iter().flatten().map(|s| (s.boxes.clone(), s.tips.clone())).collect(), self.tips_of.clone()) + pub(crate) fn layout(&self) -> Vec { + let runs = |s: &Sub| (0..s.runs()).map(|r| s.range(r).len()).collect(); + self.parts.iter().flatten().map(|s| ((s.start, s.segs, s.anchors, s.closed), runs(s))).collect() + } + + /// The boxes and tips kept per run of each subpath, the same measured again from the path + /// over the same runs, and the stroke the tips were measured for. + #[cfg(test)] + pub(crate) fn runs(&self) -> (Vec, Vec, Option) { + let els = self.path.elements(); + let kept = self.parts.iter().flatten().map(|s| (s.boxes.clone(), s.tips.clone())).collect(); + let again = self.parts.iter().flatten().map(|s| { + let boxes = (0..s.runs()).map(|r| s.run_box(els, r)).collect(); + let tips = self.tips_of.as_ref().map_or(vec![], |st| (0..s.runs()).map(|r| s.run_tips(els, r, st)).collect()); + (boxes, tips) + }); + (kept, again.collect(), self.tips_of.clone()) } } diff --git a/crates/render/src/tests/keptpath.rs b/crates/render/src/tests/keptpath.rs index 94c5621b97..3ec7fee229 100644 --- a/crates/render/src/tests/keptpath.rs +++ b/crates/render/src/tests/keptpath.rs @@ -71,19 +71,43 @@ fn check(r: &mut Renderer, d: &Document, id: NodeId, what: &str) { } let k = r.kept.get(&id).unwrap_or_else(|| panic!("{what}: its path kept")); assert!(std::ptr::eq(Arc::as_ptr(&k.node), n), "{what}: its path kept"); - // The boxes and miter tips kept, run by run, are those of the path measured whole. - let (runs, tips_of) = k.runs(); - let mut whole = crate::kept_paths::KeptPath::new(&Arc::new(n.clone()), 0).unwrap(); - if let Some(st) = &tips_of { - whole.tips(st); + // The subpaths kept are those of the path measured whole, each run holds from one segment to + // twice the segments of a run, and the boxes and miter tips kept, run by run, are those + // measured again from the path. + let whole = crate::kept_paths::KeptPath::new(&Arc::new(n.clone()), 0).unwrap(); + let (layout, fresh) = (k.layout(), whole.layout()); + assert!(layout.iter().map(|l| l.0).eq(fresh.iter().map(|l| l.0)), "{what}: the same subpaths as the path measured whole"); + for ((sub, runs), ((_, segs, ..), _)) in layout.iter().zip(&fresh) { + assert_eq!(runs.iter().sum::(), *segs, "{what}: the runs of {sub:?} hold its segments"); + assert!(runs.iter().all(|&s| (1..=2 * crate::kept_paths::RUN).contains(&s)), "{what}: the runs of {sub:?}: {runs:?}"); + } + let (runs, again, _) = k.runs(); + assert!(runs == again, "{what}: the same boxes and tips as measured again"); +} + +/// Check `d` as [`check`] does, then the document before the edit (undone) and `d` again (redone). +fn check_undo(r: &mut Renderer, before: &Document, d: &Document, id: NodeId, what: &str) { + check(r, d, id, what); + check(r, before, id, &format!("{what}, undone")); + check(r, d, id, &format!("{what}, redone")); +} + +/// The members of compound path `id` of `d`. +fn members(d: &mut Document, id: NodeId) -> &mut Vec> { + match d.node_mut(id).map(|n| &mut n.kind) { + Some(NodeKind::Compound { children, .. }) => children, + _ => panic!("a compound path"), } - assert!(runs == whole.runs().0, "{what}: the same boxes and tips as the path measured whole"); } fn path_of(d: &mut Document, id: NodeId) -> &mut PathData { d.node_mut(id).and_then(|n| n.path_data_mut()).unwrap() } +fn corner(x: f64, y: f64) -> Anchor { + Anchor::corner(Point::new(x, y)) +} + fn moved(a: &mut Anchor, by: Vec2) { *a = a.transform(Affine::translate(by)); } @@ -194,6 +218,172 @@ fn edits_in_runs_of_segments_without_length_measure_as_when_the_path_is_made_aga } } +#[test] +fn a_long_path_draws_and_culls_after_anchors_are_added_or_deleted_as_when_its_path_is_made_again() { + let mut d = Document::new(1000.0, 1000.0); + let path = PathData::new(vec![ + zigzag(3000, 0.0), + ring(1200, Point::new(12_000.0, 15.0), 45.0), + SubPath::new(vec![Anchor::corner(Point::new(11_990.0, 20.0))], false), + SubPath::new(vec![], false), + SubPath::new(vec![Anchor::corner(Point::new(11_995.0, 0.0)), Anchor::corner(Point::new(12_005.0, 30.0))], false), + ]); + let n = Node::path(d.alloc_id(), path, look(vec![stroke(6.0, LineJoin::Miter, LineCap::Butt), stroke(14.0, LineJoin::Round, LineCap::Round)])); + let id = add(&mut d, n); + let mut r = Renderer::new(); + check(&mut r, &d, id, "drawn first"); + type Edit = fn(&mut PathData); + let edits: [(&str, Edit); 28] = [ + // Anchor 1,152, a corner at (9,032, 30), ends the segments of the first nine runs: the + // joint there is in the run before. + ("an anchor added where a run of segments starts", |p| p.subpaths[0].anchors.insert(1153, corner(9_036.0, -30.0))), + ("an anchor added", |p| _ = p.subpaths[0].insert_anchor(1520, 0.5)), + ("an anchor deleted", |p| _ = p.subpaths[0].anchors.remove(1521)), + ("an anchor added at the start", |p| p.subpaths[0].anchors.insert(0, corner(-8.0, 30.0))), + ("an anchor added at the end", |p| p.subpaths[0].anchors.push(corner(24_100.0, 0.0))), + ("the first anchor deleted", |p| _ = p.subpaths[0].anchors.remove(0)), + ("the last anchor deleted", |p| _ = p.subpaths[0].anchors.pop()), + ("an anchor added onto the one before it", |p| { + let a = p.subpaths[0].anchors[1499]; + p.subpaths[0].anchors.insert(1500, Anchor::corner(a.p)); + }), + ("300 anchors deleted", |p| _ = p.subpaths[0].anchors.drain(1100..1400)), + ("400 anchors added", |p| { + let at: Vec = (0..400).map(|i| corner(8_800.0 + f64::from(i) * 0.5, if i % 2 == 0 { -20.0 } else { 50.0 })).collect(); + p.subpaths[0].anchors.splice(1100..1100, at); + }), + ("anchors moved and others deleted", |p| { + p.subpaths[0].anchors[10] = corner(80.0, -40.0); + p.subpaths[0].anchors.drain(2000..2010); + }), + ("the subpath closed", |p| p.subpaths[0].closed = true), + ("an anchor added at the start of the closed subpath", |p| p.subpaths[0].anchors.insert(0, corner(-8.0, 60.0))), + ("an anchor added after the first of the closed subpath", |p| p.subpaths[0].anchors.insert(1, corner(-20.0, -30.0))), + ("an anchor added at the end of the closed subpath", |p| p.subpaths[0].anchors.push(corner(24_000.0, 60.0))), + ("the first anchor of the closed subpath deleted", |p| _ = p.subpaths[0].anchors.remove(0)), + ("the last anchor of the closed subpath deleted", |p| _ = p.subpaths[0].anchors.pop()), + ("the subpath opened", |p| p.subpaths[0].closed = false), + ("an anchor of the ring added in the view", |p| p.subpaths[1].anchors.insert(300, corner(12_010.0, 10.0))), + ("an anchor of the ring deleted", |p| _ = p.subpaths[1].anchors.remove(600)), + ("the ring opened", |p| p.subpaths[1].closed = false), + ("the ring closed", |p| p.subpaths[1].closed = true), + ("the one-anchor subpath given a second anchor", |p| p.subpaths[2].anchors.push(corner(12_000.0, 40.0))), + ("the second anchor deleted again", |p| _ = p.subpaths[2].anchors.pop()), + ("the one-anchor subpath emptied", |p| p.subpaths[2].anchors.clear()), + ("the empty subpath given an anchor", |p| p.subpaths[3].anchors.push(corner(12_015.0, 5.0))), + ("the two-anchor subpath closed", |p| p.subpaths[4].closed = true), + ("an anchor deleted from the two-anchor subpath", |p| _ = p.subpaths[4].anchors.remove(0)), + ]; + for (what, edit) in edits { + let before = d.clone(); + edit(path_of(&mut d, id)); + check_undo(&mut r, &before, &d, id, what); + } +} + +#[test] +fn a_long_compound_path_draws_and_culls_after_members_are_added_or_removed_as_when_its_path_is_made_again() { + let mut d = Document::new(1000.0, 1000.0); + let none = Appearance::default(); + let member = |d: &mut Document, p: PathData| Arc::new(Node::path(d.alloc_id(), p, none.clone())); + let children = vec![ + member(&mut d, PathData::single(zigzag(1500, 6000.0))), + member(&mut d, PathData::single(ring(1500, Point::new(12_000.0, 15.0), 45.0))), + member(&mut d, PathData::single(SubPath::new(vec![Anchor::corner(Point::new(11_980.0, 0.0))], false))), + ]; + let mut n = Node::new(d.alloc_id(), NodeKind::Compound { children, rule: FillRule::EvenOdd }); + n.appearance = look(vec![stroke(4.0, LineJoin::Miter, LineCap::Square)]).into(); + let id = add(&mut d, n); + let mut r = Renderer::new(); + check(&mut r, &d, id, "drawn first"); + let edits: [(&str, PathData, usize); 4] = [ + ("a member added at the end", PathData::single(ring(40, Point::new(12_010.0, 20.0), 8.0)), 3), + ("a member added at the start", PathData::single(zigzag(30, 11_950.0)), 0), + ("a member added between", PathData::new(vec![]), 2), + ("a member of two subpaths added between", PathData::new(vec![ring(5, Point::new(11_990.0, 25.0), 4.0), zigzag(3, 11_970.0)]), 1), + ]; + for (what, p, at) in edits { + let before = d.clone(); + let m = member(&mut d, p); + members(&mut d, id).insert(at, m); + check_undo(&mut r, &before, &d, id, what); + } + // Seven members: the first, the last, then the third removed. + for (what, at) in [("the first member removed", 0), ("the last member removed", 5), ("a member removed between", 2)] { + let before = d.clone(); + members(&mut d, id).remove(at); + check_undo(&mut r, &before, &d, id, what); + } + // Left: the member of two subpaths, the zigzag, the ring and the one-anchor member. + let ids: Vec = members(&mut d, id).iter().map(|m| m.id).collect(); + let before = d.clone(); + path_of(&mut d, ids[1]).subpaths.push(SubPath::new(vec![corner(12_020.0, 30.0)], false)); + check_undo(&mut r, &before, &d, id, "a subpath added to a member"); + let before = d.clone(); + path_of(&mut d, ids[1]).subpaths[0].anchors.insert(10, corner(12_000.0, 60.0)); + path_of(&mut d, ids[2]).subpaths[0].anchors.remove(700); + check_undo(&mut r, &before, &d, id, "anchors added and deleted in two members"); +} + +#[test] +fn adding_and_deleting_anchors_of_a_long_path_changes_its_kept_path_in_place() { + let mut d = Document::new(1000.0, 1000.0); + let n = Node::path(d.alloc_id(), PathData::single(zigzag(3000, 0.0)), look(vec![stroke(6.0, LineJoin::Miter, LineCap::Butt)])); + let id = add(&mut d, n); + let mut r = Renderer::new(); + render(&mut r, &d); + let kept = |r: &Renderer| r.kept.get(&id).map(|k| Arc::as_ptr(&k.path) as usize); + let before = kept(&r); + assert!(before.is_some(), "the path is kept"); + type Edit = fn(&mut PathData); + let edits: [(&str, Edit); 3] = [ + ("an anchor added", |p| _ = p.subpaths[0].insert_anchor(1500, 0.5)), + ("an anchor deleted", |p| _ = p.subpaths[0].anchors.remove(1700)), + ("the subpath closed", |p| p.subpaths[0].closed = true), + ]; + for (what, edit) in edits { + edit(path_of(&mut d, id)); + check(&mut r, &d, id, what); + assert_eq!(kept(&r), before, "{what}: the kept path changed in place"); + } + // An edit that leaves the anchors as they were leaves the kept path as it is, also while + // something else holds it. + let held = r.kept.get(&id).map(|k| k.path.clone()).unwrap(); + d.node_mut(id).unwrap().appearance = look(vec![stroke(8.0, LineJoin::Miter, LineCap::Butt)]).into(); + check(&mut r, &d, id, "the stroke changed"); + assert!(Arc::ptr_eq(&held, &r.kept.get(&id).unwrap().path), "the stroke changed: the kept path left as it is"); +} + +#[test] +fn deleting_an_anchor_of_an_open_path_and_clearing_the_handles_past_its_ends_measures_one_run_again() { + let mut d = Document::new(1000.0, 1000.0); + let mut sp = zigzag(3000, 0.0); + if let Some(a) = sp.anchors.last_mut() { + a.h_out = a.p + Vec2::new(3.0, 4.0); + } + assert!(sp.anchors[0].has_in(), "the first anchor has a handle before it"); + let n = Node::path(d.alloc_id(), PathData::single(sp), look(vec![stroke(6.0, LineJoin::Miter, LineCap::Butt)])); + let id = add(&mut d, n); + let mut r = Renderer::new(); + render(&mut r, &d); + let runs = |r: &Renderer| r.kept.get(&id).map(|k| k.layout()[0].1.clone()).unwrap(); + let before = runs(&r); + // Anchor 1,500 deleted, and the handles before the first anchor and after the last cleared: + // they draw nothing on an open subpath. + let p = &mut path_of(&mut d, id).subpaths[0]; + p.anchors.remove(1500); + if let Some(a) = p.anchors.first_mut() { + a.h_in = a.p; + } + if let Some(a) = p.anchors.last_mut() { + a.h_out = a.p; + } + check(&mut r, &d, id, "an anchor deleted and the end handles cleared"); + let after = runs(&r); + let changed: Vec = (0..before.len().max(after.len())).filter(|&i| before.get(i) != after.get(i)).collect(); + assert_eq!(changed, vec![1499 / crate::kept_paths::RUN], "only the run that held the anchor changed: {before:?} -> {after:?}"); +} + #[test] fn moving_one_anchor_of_a_long_path_changes_its_kept_path_in_place() { let mut d = Document::new(1000.0, 1000.0); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 27b63a9215..3051202252 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1280,6 +1280,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With more than 10,000 type on a path objects selected, the Selection and Direct Selection tools neither draw nor hit-test the objects' brackets. The renderer outlines the stroke of a path object with more than 1,024 path elements, without dashes or a width profile, only in and around the view, with a margin of the view's size on each side, and outlines it again when the view moves past that margin. The pixels are the same. At 1600 × 1200, the frame after one anchor of an open path of 200,000 anchors moves takes 28 to 30 ms instead of 103 ms, and with a closed path of 50,000 anchors 10 ms instead of 30 ms (`cargo run --release -p vectorcraft-engine --example anchor_bench`). The renderer outlines a dashed stroke of such a path the same way, without a width profile, and draws its dashes and dots in the same places as when the whole path is dashed, so the pixels are the same. A pattern too fine to draw is drawn solid, as before, and its stroke is outlined near the view too. At 1600 × 1200, the frame after one anchor moves takes 14 ms instead of 102 ms with a filled closed path of 50,000 anchors and a stroke of 6 pt dashes and 4 pt gaps (`cargo run --release -p vectorcraft-engine --example anchor_bench`, which now includes that document). + When anchors of a path or compound path of 1,024 anchors or more are added or deleted, or a subpath is closed or opened, the next frame writes again only the path elements from the first anchor that changed to the last, and the closing segment when an end anchor changed or the subpath was closed or opened. It measures again only the runs of segments that held them; a run grows or shrinks with the segments added or deleted, and one that grows past 256 segments is split. When a member gains or loses subpaths, the renderer makes the path of that member again. When a compound path gains or loses members, it makes the path of those members and of every member between the first and the last of them again. An edit that adds or deletes anchors in, closes or opens more than 16 subpaths makes the whole path again. The pixels and the cull bounds are the same. The renderer keeps the path of a path or compound path of 1,024 anchors or more by object, with the bounds of its segments and of its miter spikes in runs of 128 segments. When anchors move and the subpaths and anchor counts stay the same, the next frame changes only the segments that start or end at a moved anchor and measures again only the runs that hold them or the segments with length before them, instead of making the whole path again and measuring it whole for culling. The pixels and the cull bounds are the same. On Windows at 1600 × 1200, the frame after one anchor moves takes 8.2 ms instead of 30.1 ms with an open path of 200,000 anchors, 4.3 ms instead of 10.4 ms with a closed path of 50,000 anchors, and 6.6 ms instead of 11.9 ms with the filled closed path of 50,000 anchors and a dashed stroke (medians of five runs of `anchor_bench`). When a path object moves without changing shape, the renderer draws its stroke from the outline it made before the move, moved by the same offset. It outlines the stroke again when the path is scaled, rotated or edited, when the stroke changes, and when the move takes the view past the part of a long path it outlined. The pixels are the same. At 1600 × 1200, the frame after a 1 pt nudge takes 123 ms instead of 403 ms with an open path of 200,000 anchors in view (103 ms with nothing changed), and 13 ms instead of 26 ms with a closed path of 50,000 anchors whose stroke is dashed and has a width profile. When a path object moves without changing shape, the renderer draws its stroke from the outline it made before the move, moved by the same offset. It outlines the stroke again when the path is scaled, rotated or edited, when the stroke changes, and when the move takes the view past the part of a long path it outlined. The pixels are the same. At 1600 × 1200, the frame after a 1 pt nudge takes 128 ms instead of 405 ms with an open path of 200,000 anchors in view (104 ms with nothing changed), and 14 ms instead of 28 ms with a closed path of 50,000 anchors whose stroke is dashed and has a width profile. From e3d30a704798a5cbde6575834137f919b1cfab6f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 22:55:03 -0800 Subject: [PATCH 052/196] Render: kept-path splices check their arithmetic and make the subpath again on a mismatch The index arithmetic in `Sub::spliced`, `Sub::resize` and `KeptPath::update` uses `checked_sub` and `checked_add` instead of plain subtraction. When the segments or runs kept for a subpath do not fit its anchors before the edit, `resize` returns `None` without changing anything, and `update` writes the subpath's elements again from the new anchors and measures it whole, as it does for a subpath of fewer than two anchors. A compound path whose kept members do not pair with the new ones returns false, and the renderer makes the path again whole. --- crates/render/src/kept_paths.rs | 104 ++++++++++++++++++++++---------- 1 file changed, 72 insertions(+), 32 deletions(-) diff --git a/crates/render/src/kept_paths.rs b/crates/render/src/kept_paths.rs index dc48d3cafb..293e824664 100644 --- a/crates/render/src/kept_paths.rs +++ b/crates/render/src/kept_paths.rs @@ -237,15 +237,24 @@ impl Sub { if was.anchors.len() == now.anchors.len() && was.closed == now.closed { self.moved(was, now, els, st); } else if was.anchors.len() < 2 || now.anchors.len() < 2 { - let to = (at + self.len()).min(els.len()); - let len = if now.anchors.is_empty() { 0 } else { 1 + now.segment_count() + usize::from(now.closed) }; - els.splice(at.min(to)..to, (0..len).map(|o| element_at(now, o))); - *self = Sub::measured(now, at, els, st); + self.remade(now, at, self.len(), els, st); } else { - self.spliced(was, now, els, st); + let mut span = self.len(); + if self.spliced(was, now, els, st, &mut span).is_none() { + self.remade(now, at, span, els, st); + } } } + /// Write the elements of `now` over the `span` elements at `at` in `els` that the subpath holds, + /// and measure it whole with the tips of `st`. + fn remade(&mut self, now: &SubPath, at: usize, span: usize, els: &mut Vec, st: Option<&StrokeLayer>) { + let to = at.saturating_add(span).min(els.len()); + let len = if now.anchors.is_empty() { 0 } else { 1 + now.segment_count() + usize::from(now.closed) }; + els.splice(at.min(to)..to, (0..len).map(|o| element_at(now, o))); + *self = Sub::measured(now, at, els, st); + } + /// [`Self::update`] for a subpath with the same anchor count and closed state: the elements of /// the segments that start or end at an anchor that moved are made again, with the boxes of /// their runs and the tips of those runs and of the runs of the segments with length before @@ -314,8 +323,10 @@ impl Sub { /// last are written again, and the closing segment and the ClosePath when the first or last /// anchor changed or it was closed or opened; the elements before and after stay. The runs /// that held the segments written are measured again, with the tips of the runs of the - /// segments with length before them. - fn spliced(&mut self, was: &SubPath, now: &SubPath, els: &mut Vec, st: Option<&StrokeLayer>) { + /// segments with length before them. `span` is the count of elements the subpath holds in + /// `els`, kept up to date as they are written. `None` when the segments and runs kept do not + /// fit `was`: the caller then makes the subpath again from those `span` elements. + fn spliced(&mut self, was: &SubPath, now: &SubPath, els: &mut Vec, st: Option<&StrokeLayer>, span: &mut usize) -> Option<()> { let (n0, n1) = (was.anchors.len(), now.anchors.len()); let least = n0.min(n1); // On a subpath open before and after, the handle before the first anchor and the one after @@ -336,25 +347,36 @@ impl Sub { let (len0, len1) = (1 + s0 + usize::from(c0), 1 + s1 + usize::from(c1)); // Elements `a..mid` change: the MoveTo when the first anchor changed and the segments up // to the first of those between the last `b` anchors. - let (mid0, mid1) = ((1 + n0 - b).min(1 + s0), (1 + n1 - b).min(1 + s1)); + let (mid0, mid1) = ((1 + n0.checked_sub(b)?).min(1 + s0), (1 + n1.checked_sub(b)?).min(1 + s1)); // Elements `tail..len` follow the segments between the last `b` anchors: the closing // segment and the ClosePath. They stay when the anchors either side of the closing segment // stayed and the subpath was neither closed nor opened. let (tail0, tail1) = if b >= 1 { (n0, n1) } else { (mid0, mid1) }; let keep_tail = c0 == c1 && (!c1 || b == 0 || a >= 1); + // The `old` segments from segment `lo` become `new` segments, and when the tail is written, + // the segments from the one before it do too. + let lo = a.saturating_sub(1); + let (old, new) = (mid0.checked_sub(1)?.checked_sub(lo)?, mid1.checked_sub(1)?.checked_sub(lo)?); + let tail = match keep_tail { + true => None, + false => Some((tail0.checked_sub(1)?, (1 + s0).saturating_sub(tail0), (1 + s1).saturating_sub(tail1), tail1.checked_sub(1)?)), + }; let at = self.start; let mut stale = vec![false; self.runs()]; let tips = st.is_some(); - if !keep_tail { - let to = (at + len0).min(els.len()); - els.splice((at + tail0).min(to)..to, (tail1..len1).map(|o| element_at(now, o))); - let (lo, old, new) = (tail0 - 1, (1 + s0).saturating_sub(tail0), (1 + s1).saturating_sub(tail1)); - self.resize(lo, old, new, &mut stale, tips); + // Writes elements `e0..e1` of `now` over elements `o0..o1` of the subpath and updates `span`. + let mut write = |els: &mut Vec, (o0, o1): (usize, usize), (e0, e1): (usize, usize)| { + let to = at.saturating_add(o1).min(els.len()); + let from = at.saturating_add(o0).min(to); + els.splice(from..to, (e0..e1).map(|o| element_at(now, o))); + *span = from.saturating_sub(at) + e1.saturating_sub(e0) + at.saturating_add(*span).saturating_sub(to); + }; + if let Some((lo, old, new, _)) = tail { + self.resize(lo, old, new, &mut stale, tips)?; + write(els, (tail0, len0), (tail1, len1)); } - let to = (at + mid0).min(els.len()); - els.splice((at + a).min(to)..to, (a..mid1).map(|o| element_at(now, o))); - let lo = a.max(1) - 1; - self.resize(lo, mid0 - 1 - lo, mid1 - 1 - lo, &mut stale, tips); + self.resize(lo, old, new, &mut stale, tips)?; + write(els, (a, mid0), (a, mid1)); self.anchors = n1; self.closed = c1; let els: &[PathEl] = els; @@ -364,12 +386,12 @@ impl Sub { *slot = b; } } - let Some(st) = st else { return }; + let Some(st) = st else { return Some(()) }; let mut runs: Vec = stale.iter().enumerate().filter(|(_, s)| **s).map(|(r, _)| r).collect(); // Closed or opened: the tips of every joint change when the stroke reaches farther from one // than from the other. let mut whole = c0 != c1 && st.side_reach(c0).to_bits() != st.side_reach(c1).to_bits(); - for i in [lo].into_iter().chain((!keep_tail).then_some(tail1 - 1)) { + for i in [lo].into_iter().chain(tail.map(|(.., last)| last)) { match self.prev_drawn(els, i) { Ok(Some(j)) => runs.push(self.run_of(j)), Ok(None) => {} @@ -377,36 +399,43 @@ impl Sub { } } self.measure_tips(els, runs, whole, st); + Some(()) } /// Replace the `old` segments from segment `lo` with `new` segments in the runs: the runs that /// held them become one run, split into runs of [`RUN`] segments when longer than twice that, - /// whose boxes and (with `tips`) tips are marked in `stale` to be measured again. - fn resize(&mut self, lo: usize, old: usize, new: usize, stale: &mut Vec, tips: bool) { + /// whose boxes and (with `tips`) tips are marked in `stale` to be measured again. `None`, and + /// nothing changed, when the runs kept do not hold those `old` segments. + fn resize(&mut self, lo: usize, old: usize, new: usize, stale: &mut Vec, tips: bool) -> Option<()> { if old == 0 && new == 0 { - return; + return Some(()); } let (r0, r1, first, last) = match self.runs() { 0 => (0, 0, 0, new), _ => { let r0 = self.run_of(lo); let r1 = if old == 0 { r0 } else { self.run_of(lo + old - 1) }; - let last = self.ends.get(r1).copied().unwrap_or(lo + old) + new - old; + let last = self.ends.get(r1).copied().unwrap_or(lo + old).checked_add(new)?.checked_sub(old)?; (r0, r1 + 1, self.range(r0).start, last) } }; - let len = last - first; - let count = if len > 2 * RUN { len.div_ceil(RUN) } else { usize::from(len > 0) }; - for e in self.ends.iter_mut().skip(r1) { - *e = *e + new - old; + let len = last.checked_sub(first)?; + let segs = self.segs.checked_add(new)?.checked_sub(old)?; + let after: Vec = self.ends.get(r1..)?.iter().map(|&e| e.checked_add(new)?.checked_sub(old)).collect::>()?; + if r1 > self.boxes.len() || r1 > stale.len() { + return None; } + let count = if len > 2 * RUN { len.div_ceil(RUN) } else { usize::from(len > 0) }; + self.ends.truncate(r1); + self.ends.extend(after); self.ends.splice(r0..r1, (1..=count).map(|j| if j == count { last } else { first + j * RUN })); self.boxes.splice(r0..r1, std::iter::repeat_n(None, count)); if tips { self.tips.splice(r0.min(self.tips.len())..r1.min(self.tips.len()), std::iter::repeat_n(None, count)); } stale.splice(r0..r1, std::iter::repeat_n(true, count)); - self.segs = self.segs + new - old; + self.segs = segs; + Some(()) } /// Measure again the tips of `st` in `runs`, or in every run when `whole`. @@ -477,7 +506,9 @@ impl KeptPath { /// compound path that gained or lost subpaths is made again, and so are the members added /// between the first and the last member that the edit left as they were, when the edit added /// or removed members. False, and nothing changed, when `n` has no kept path, or when the edit - /// added or deleted anchors in or closed or opened more than [`SPLICES`] subpaths. False as well + /// added or deleted anchors in or closed or opened more than [`SPLICES`] subpaths, or when the + /// members kept do not pair with those of `n`. A subpath whose segments or runs kept do not fit + /// its anchors before the edit is made again whole ([`Sub::spliced`]). False as well /// when the path written does not end where the subpaths measured end. The renderer makes the /// path again whole after a false. pub(crate) fn update(&mut self, n: &Arc) -> bool { @@ -495,7 +526,15 @@ impl KeptPath { let rest = (was.len() - head).min(now.len() - head); (head, was.iter().rev().zip(now.iter().rev()).take(rest).take_while(|(w, p)| std::ptr::eq(**w, **p)).count()) }; - let paired = |i: usize| if i < head { Some(i) } else { (now.len() - i <= tail).then(|| was.len() - (now.len() - i)) }; + // Where the members that are not paired end in `was` and in `now`. + let (Some(was_end), Some(now_end)) = (was.len().checked_sub(tail), now.len().checked_sub(tail)) else { return false }; + if head > was_end || head > now_end { + return false; + } + let paired = |i: usize| match i < head { + true => Some(i), + false => now.len().checked_sub(i).filter(|&back| back <= tail).and_then(|back| was.len().checked_sub(back)), + }; let spliced: usize = (0..now.len()).filter_map(|i| paired(i).map(|w| splices(was[w], now[i]))).sum(); if spliced > SPLICES { return false; @@ -515,8 +554,9 @@ impl KeptPath { for (i, p) in now.iter().enumerate() { if i == head { // The members of `was` that are not paired give way to those of `now`. - let gone: usize = old_parts[head..was.len() - tail].iter_mut().flat_map(|s| s.take().into_iter().flatten()).map(|s| s.len()).sum(); - parts.extend(made_again(&now[head..now.len() - tail], gone, &mut els, &mut at, st)); + let gone: usize = + old_parts.get_mut(head..was_end).into_iter().flatten().flat_map(|s| s.take().into_iter().flatten()).map(|s| s.len()).sum(); + parts.extend(made_again(now.get(head..now_end).unwrap_or_default(), gone, &mut els, &mut at, st)); } let Some(w) = paired(i) else { continue }; let Some(mut subs) = old_parts.get_mut(w).and_then(Option::take) else { continue }; From 924ec6f0d6f4bd7c50c2967651a672a7eb26a078 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 22:55:04 -0800 Subject: [PATCH 053/196] Tests: random edits of long paths keep what making the path again makes Two seeded tests run 300 random edits each on a long path and a long compound path: anchors added and deleted at the start, middle and end of a subpath and where a run of segments ends, subpaths closed and opened, anchors and handles moved, and in the compound path members added and removed and subpaths added to a member. The subpaths range from 2 anchors to 3,000, open and closed. After each edit the kept path's elements, subpaths, bounds and miter tips equal those of a new `KeptPath`, its runs hold each subpath's segments, and each run's box and tips equal those measured again. --- crates/render/src/tests/keptpath.rs | 180 ++++++++++++++++++++++++++++ 1 file changed, 180 insertions(+) diff --git a/crates/render/src/tests/keptpath.rs b/crates/render/src/tests/keptpath.rs index 3ec7fee229..a2f8b3ad85 100644 --- a/crates/render/src/tests/keptpath.rs +++ b/crates/render/src/tests/keptpath.rs @@ -384,6 +384,186 @@ fn deleting_an_anchor_of_an_open_path_and_clearing_the_handles_past_its_ends_mea assert_eq!(changed, vec![1499 / crate::kept_paths::RUN], "only the run that held the anchor changed: {before:?} -> {after:?}"); } +/// Numbers from a fixed seed (a linear congruential generator). +struct Seeded(u64); + +impl Seeded { + /// A number below `m` (0 when `m` is 0). + fn below(&mut self, m: usize) -> usize { + self.0 = self.0.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + (self.0 >> 33) as usize % m.max(1) + } + + /// A whole number of points from -`r` to `r`. + fn offset(&mut self, r: usize) -> f64 { + self.below(2 * r + 1) as f64 - r as f64 + } + + /// Where in a subpath of `n` anchors to edit: at the start, at the end, where a run of segments + /// ends, or anywhere. + fn at(&mut self, n: usize) -> usize { + match self.below(4) { + 0 => self.below(3).min(n), + 1 => n.saturating_sub(self.below(3)), + 2 => (crate::kept_paths::RUN * (1 + self.below(24)) + self.below(3)).min(n), + _ => self.below(n + 1), + } + } +} + +/// An anchor to add after `before`: on it (a segment without length), a corner near it, or a +/// smooth anchor near it. +fn anchor_after(g: &mut Seeded, before: Point) -> Anchor { + let p = before + Vec2::new(g.offset(20), g.offset(40)); + match g.below(5) { + 0 => Anchor::corner(before), + 1 => Anchor::smooth(p, p + Vec2::new(g.offset(6), g.offset(6))), + _ => Anchor::corner(p), + } +} + +/// Edit `p` at random: anchors added or deleted at the start, middle or end of a subpath, a +/// subpath closed or opened, an anchor or a handle moved, or many anchors moved. Says what it did. +fn random_edit(g: &mut Seeded, p: &mut PathData) -> String { + let s = g.below(p.subpaths.len()); + let Some(sp) = p.subpaths.get_mut(s) else { return "nothing".into() }; + let n = sp.anchors.len(); + match g.below(6) { + 0 | 1 => { + let (at, k) = (g.at(n), 1 + g.below(3)); + for j in 0..k { + let before = sp.anchors.get((at + j).saturating_sub(1)).map_or(Point::new(12_000.0, 15.0), |a| a.p); + let a = anchor_after(g, before); + sp.anchors.insert(at + j, a); + } + format!("{k} anchors added at {at} of subpath {s} of {n}") + } + 2 | 3 if n > 0 => { + let at = g.at(n - 1); + let k = (1 + g.below(3)).min(n - at); + sp.anchors.drain(at..at + k); + format!("{k} anchors deleted at {at} of subpath {s} of {n}") + } + 4 => { + sp.closed = !sp.closed; + format!("subpath {s} of {n} closed: {}", sp.closed) + } + _ if n > 0 => { + let at = g.below(n); + match g.below(3) { + 0 => moved(&mut sp.anchors[at], Vec2::new(g.offset(30), g.offset(30))), + 1 => sp.anchors[at].h_out = sp.anchors[at].p + Vec2::new(g.offset(10), g.offset(10)), + _ => sp.anchors[at..].iter_mut().take(n / 10).for_each(|a| moved(a, Vec2::new(1.0, -1.0))), + } + format!("anchors moved at {at} of subpath {s} of {n}") + } + _ => "nothing".into(), + } +} + +/// Bring `k` up to date with `n` and check that it holds what [`KeptPath::new`] makes from `n`: +/// the same path elements and subpaths, runs that hold each subpath's segments, the boxes and miter +/// tips of `st` measured again over its runs, and the same bounds and tips in all. +fn same_as_made_again(k: &mut crate::kept_paths::KeptPath, n: &Arc, st: &StrokeLayer, what: &str) { + assert!(k.update(n), "{what}: brought up to date"); + let mut fresh = crate::kept_paths::KeptPath::new(n, 0).unwrap_or_else(|| panic!("{what}: kept")); + assert!(*k.path == *fresh.path, "{what}: the same path elements"); + let (layout, whole) = (k.layout(), fresh.layout()); + assert!(layout.iter().map(|l| l.0).eq(whole.iter().map(|l| l.0)), "{what}: the same subpaths: {layout:?}"); + for ((sub, runs), ((_, segs, ..), _)) in layout.iter().zip(&whole) { + assert_eq!(runs.iter().sum::(), *segs, "{what}: the runs of {sub:?} hold its segments"); + assert!(runs.iter().all(|&s| (1..=2 * crate::kept_paths::RUN).contains(&s)), "{what}: the runs of {sub:?}: {runs:?}"); + } + let (runs, again, _) = k.runs(); + assert!(runs == again, "{what}: the same boxes and tips as measured again"); + assert_eq!(k.geometric(), fresh.geometric(), "{what}: the same bounds"); + assert_eq!(k.tips(st), fresh.tips(st), "{what}: the same miter tips"); +} + +#[test] +fn random_edits_of_a_long_path_keep_what_making_its_path_again_makes() { + let st = stroke(6.0, LineJoin::Miter, LineCap::Butt); + let mut g = Seeded(5744); + let closed = |sp: SubPath| SubPath::new(sp.anchors, true); + let path = PathData::new(vec![ + zigzag(2, 11_990.0), + closed(zigzag(3, 12_000.0)), + zigzag(7, 11_960.0), + closed(zigzag(40, 11_800.0)), + ring(300, Point::new(12_000.0, 15.0), 60.0), + zigzag(3000, 0.0), + closed(zigzag(2000, 4000.0)), + ]); + let mut n = Arc::new(Node::path(NodeId(1), path, look(vec![st.clone()]))); + let mut k = crate::kept_paths::KeptPath::new(&n, 0).unwrap(); + k.tips(&st); + for step in 0..300 { + let mut next = (*n).clone(); + let what = random_edit(&mut g, next.path_data_mut().unwrap()); + n = Arc::new(next); + same_as_made_again(&mut k, &n, &st, &format!("step {step}, {what}")); + } +} + +#[test] +fn random_edits_of_a_long_compound_path_keep_what_making_its_path_again_makes() { + let st = stroke(4.0, LineJoin::Miter, LineCap::Square); + let mut g = Seeded(1050); + let ids = std::cell::Cell::new(10); + let member = |p: PathData| { + ids.set(ids.get() + 1); + Arc::new(Node::path(NodeId(ids.get()), p, Appearance::default())) + }; + let children = vec![ + member(PathData::new(vec![SubPath::new(zigzag(3, 11_990.0).anchors, true), zigzag(5, 12_010.0)])), + member(PathData::single(zigzag(3000, 0.0))), + member(PathData::single(ring(40, Point::new(12_000.0, 15.0), 30.0))), + member(PathData::single(zigzag(2, 12_020.0))), + ]; + let mut n = Node::new(NodeId(1), NodeKind::Compound { children, rule: FillRule::EvenOdd }); + n.appearance = look(vec![st.clone()]).into(); + let mut n = Arc::new(n); + let mut k = crate::kept_paths::KeptPath::new(&n, 0).unwrap(); + k.tips(&st); + for step in 0..300 { + let mut next = (*n).clone(); + let NodeKind::Compound { children, .. } = &mut next.kind else { panic!("a compound path") }; + let what = match g.below(8) { + 0 => { + let at = [0, children.len(), g.below(children.len() + 1)][g.below(3)]; + let size = [1, 2, 4, 30, 200][g.below(5)]; + let mut sp = zigzag(size, 11_900.0 + g.offset(100)); + sp.closed = g.below(2) == 0; + children.insert(at, member(PathData::single(sp))); + format!("a member of {size} anchors added at {at}") + } + // The member of 3,000 anchors stays, so that the path stays kept. + 1 if children.len() > 2 => { + let at = [0, children.len() - 1, g.below(children.len())][g.below(3)]; + if children[at].path_data().is_some_and(|p| p.subpaths.iter().map(|s| s.anchors.len()).sum::() > 1000) { + "nothing".into() + } else { + children.remove(at); + format!("member {at} removed") + } + } + 2 => { + let at = g.below(children.len()); + let m = Arc::make_mut(&mut children[at]).path_data_mut().unwrap(); + m.subpaths.push(zigzag(1 + g.below(4), 12_030.0)); + format!("a subpath added to member {at}") + } + _ => { + let at = g.below(children.len()); + let what = random_edit(&mut g, Arc::make_mut(&mut children[at]).path_data_mut().unwrap()); + format!("member {at}: {what}") + } + }; + n = Arc::new(next); + same_as_made_again(&mut k, &n, &st, &format!("step {step}, {what}")); + } +} + #[test] fn moving_one_anchor_of_a_long_path_changes_its_kept_path_in_place() { let mut d = Document::new(1000.0, 1000.0); From 19d9843971589ed4ddc966e236efb358f9b3f788 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 23:03:08 -0800 Subject: [PATCH 054/196] Shape Builder: a merge or erase takes the stretch of every coincident line Where two open paths lie along the same stretch, the planar map gave that stretch to one of them only, so a merge or an erase across it left the other path in place there. Every other open path along an edge now has its own piece in `lines_under`, under a closed path's outline or along a line in front. `lines`, `edges` and Live Paint's edges stay one per stretch, and an Alt-click there still takes the piece in front. --- crates/engine/src/tests/build.rs | 33 +++++++++++ crates/pathops/src/planar/map.rs | 66 ++++++++++++---------- crates/pathops/src/planar/shape_builder.rs | 5 +- crates/pathops/src/planar/tests.rs | 25 ++++++++ crates/tools/src/builder/map.rs | 5 +- crates/tools/src/builder/tests.rs | 24 ++++++++ 6 files changed, 123 insertions(+), 35 deletions(-) diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index c6bd07ecff..b4be82c2ec 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -830,6 +830,39 @@ fn shape_builder_drag_from_a_merged_shape_over_a_line_under_its_edge_makes_one_r assert!(left_half_gone(&s, h)); } +#[test] +fn shape_builder_removes_the_stretch_of_every_line_under_a_merged_edge() { + // Two lines along the same stretch, under the bottom edge of the merged top row: merging the + // row with the cell below takes the stretch between them from both lines. + for erase in [false, true] { + let mut s = session(); + let h1 = line(&mut s, (100.0, 200.0), (300.0, 200.0)); + let h2 = line(&mut s, (100.0, 200.0), (300.0, 200.0)); + let v = line(&mut s, (200.0, 100.0), (200.0, 300.0)); + let sq = rect(&mut s, 100.0, 100.0, 200.0, 200.0); + s.edit("t", |d, _| { + for id in [h1, h2, v, sq] { + d.node_mut(id).unwrap().appearance.set_fill(Paint::None); + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [h1.0, h2.0, v.0, sq.0]})).unwrap(); + s.execute("shapeBuilder.merge", &json!({"points": [[150, 150], [250, 150]]})).unwrap(); + s.execute("shapeBuilder.merge", &json!({"points": [[250, 150], [150, 250]], "erase": erase})).unwrap(); + let d = &s.doc().unwrap().doc; + let left: Vec = d + .children(d.default_layer()) + .into_iter() + .flatten() + .filter(|n| !outline(n).0.is_closed()) + .filter_map(|n| n.geometric_bounds()) + .filter(|b| b.height() < 1e-6 && (b.y0 - 200.0).abs() < 1e-6 && b.x0 < 199.0) + .collect(); + assert!(left.is_empty(), "erase {erase}: {left:?}"); + } +} + #[test] fn shape_builder_alt_deletes_a_region_or_a_line_piece() { let mut s = session(); diff --git a/crates/pathops/src/planar/map.rs b/crates/pathops/src/planar/map.rs index 3abf7cfeaa..aa853b2469 100644 --- a/crates/pathops/src/planar/map.rs +++ b/crates/pathops/src/planar/map.rs @@ -423,8 +423,8 @@ impl Map { } /// Faces and edges of `shapes`, and the pieces of the open paths (those with no closed subpath) -/// that lie under the outline of a closed path in front of them, whose edges are that closed -/// path's. +/// that lie under another path in front of them, whose edges are that path's: under a closed +/// path's outline, or along an open path in front. pub(super) fn build(shapes: &[Shape], precision: f64) -> Option<(Vec, Vec, Vec)> { let m = map_with(shapes, false, precision)?; let Map { edges, around, faces, holes, face_holes, tidy, anchors, snap, .. } = &m; @@ -461,61 +461,65 @@ pub(super) fn build(shapes: &[Shape], precision: f64) -> Option<(Vec, Ve }) .collect() }; - let edge_shapes = to_shapes(chains_by(edges, around, |e| Some(e.source))); let is_line = |i: usize| shapes.get(i).is_some_and(|s| !s.path.subpaths.iter().any(|sp| sp.closed)); - let under = to_shapes(chains_by(edges, around, |e| if is_line(e.source) { None } else { e.sources.iter().rev().copied().find(|&i| is_line(i)) })); + // An edge is the front-most input's. Every other open path along it has a piece there too. + let edge_shapes = to_shapes(chains_by(edges, around, |e| vec![e.source])); + let under = to_shapes(chains_by(edges, around, |e| e.sources.iter().rev().copied().filter(|&i| i != e.source && is_line(i)).collect())); Some((regions, edge_shapes, under)) } -/// The edges that `key` gives an input, joined into chains through the vertices where only two -/// edges of the same input meet, each with that input. A chain is closed when it comes back round -/// to where it started. -fn chains_by(edges: &[Edge], around: &[Vec], key: impl Fn(&Edge) -> Option) -> Vec<(Vec, bool, usize)> { - let keys: Vec> = edges.iter().map(&key).collect(); - let key_of = |h: usize| keys.get(h / 2).copied().flatten(); - let passes = |v: usize| -> Option<(usize, usize)> { +/// The edges that `keys` gives each input, joined into chains through the vertices where only two +/// edges of the same input meet, each with that input. An edge that several inputs share is in a +/// chain for each of them. A chain is closed when it comes back round to where it started. +fn chains_by(edges: &[Edge], around: &[Vec], keys: impl Fn(&Edge) -> Vec) -> Vec<(Vec, bool, usize)> { + let keys: Vec> = edges.iter().map(&keys).collect(); + // Where input `k` is among the inputs half-edge `h` gives. + let slot = |h: usize, k: usize| keys.get(h / 2).and_then(|ks| ks.iter().position(|&x| x == k)); + let passes = |v: usize, k: usize| -> Option<(usize, usize)> { let list = around.get(v)?; let (&a, &b) = (list.first()?, list.get(1)?); - (list.len() == 2 && key_of(a).is_some() && key_of(a) == key_of(b)).then_some((a, b)) + (list.len() == 2 && slot(a, k).is_some() && slot(b, k).is_some()).then_some((a, b)) }; - // Edges with no input to give are never walked. - let mut used: Vec = keys.iter().map(Option::is_none).collect(); + // Each edge's inputs, and whether its chain for each has been walked. + let mut used: Vec> = keys.iter().map(|ks| vec![false; ks.len()]).collect(); let mut chains: Vec<(Vec, bool, usize)> = Vec::new(); - // A chain from half-edge `h0` up to the next vertex where it doesn't pass straight through. - let walk = |h0: usize, used: &mut Vec| -> Option<(Vec, bool, usize)> { - let source = key_of(h0)?; + // A chain of input `k` from half-edge `h0` up to the next vertex where it doesn't pass straight through. + let walk = |h0: usize, k: usize, used: &mut Vec>| -> Option<(Vec, bool, usize)> { let mut segs = Vec::new(); let mut h = h0; loop { - let u = used.get_mut(h / 2)?; + let u = used.get_mut(h / 2)?.get_mut(slot(h, k)?)?; if *u { - return Some((segs, true, source)); + return Some((segs, true, k)); } *u = true; segs.extend(half_segs(edges, h)); let v = origin(edges, twin(h))?; - let Some((a, b)) = passes(v) else { return Some((segs, origin(edges, h0) == Some(v), source)) }; + let Some((a, b)) = passes(v, k) else { return Some((segs, origin(edges, h0) == Some(v), k)) }; h = if a == twin(h) { b } else { a }; } }; + let unwalked = |used: &[Vec], h: usize, k: usize| slot(h, k).is_some_and(|s| used.get(h / 2).and_then(|u| u.get(s)) == Some(&false)); for v in 0..around.len() { - if passes(v).is_some() { - continue; - } for &h in around.get(v).map(Vec::as_slice).unwrap_or_default() { - if !used.get(h / 2).copied().unwrap_or(true) - && let Some(c) = walk(h, &mut used) - { - chains.push(c); + for &k in keys.get(h / 2).map(Vec::as_slice).unwrap_or_default() { + if passes(v, k).is_none() + && unwalked(&used, h, k) + && let Some(c) = walk(h, k, &mut used) + { + chains.push(c); + } } } } // What's left are closed loops with no junction on them. for e in 0..edges.len() { - if !used.get(e).copied().unwrap_or(true) - && let Some(c) = walk(2 * e, &mut used) - { - chains.push(c); + for &k in keys.get(e).map(Vec::as_slice).unwrap_or_default() { + if unwalked(&used, 2 * e, k) + && let Some(c) = walk(2 * e, k, &mut used) + { + chains.push(c); + } } } chains diff --git a/crates/pathops/src/planar/shape_builder.rs b/crates/pathops/src/planar/shape_builder.rs index 290bc270d4..fde156f9b3 100644 --- a/crates/pathops/src/planar/shape_builder.rs +++ b/crates/pathops/src/planar/shape_builder.rs @@ -19,8 +19,9 @@ pub struct BuilderArrangement { /// share one); only when asked for. pub edges: Vec, /// The pieces of the paths with no closed subpath that lie under the outline of a closed path - /// in front of them, keyed by input index. No piece of `lines` covers them; there the edge is - /// the closed path's (in `edges`, when asked for). + /// in front of them, or along another such path in front of them, keyed by input index. No + /// piece of theirs is in `lines`; there the edge is the path's in front (in `edges` when it is + /// a closed path's and they were asked for, else in `lines`). pub lines_under: Vec, } diff --git a/crates/pathops/src/planar/tests.rs b/crates/pathops/src/planar/tests.rs index 654d7d5cb7..3cee370df8 100644 --- a/crates/pathops/src/planar/tests.rs +++ b/crates/pathops/src/planar/tests.rs @@ -444,6 +444,31 @@ fn shape_builder_keeps_the_pieces_of_a_line_under_an_outline_in_front() { assert!(shape_builder(&s, true).lines_under.is_empty()); } +#[test] +fn shape_builder_gives_each_coincident_line_its_pieces() { + // Two lines along the same stretch, whose left half lies under the bottom edge of a rectangle + // in front of them: each has its own pieces, under the edge and beyond it. Beyond the edge the + // front line's piece is the edge, and the back line's lies under it. + let s = [line((0.0, 50.0), (200.0, 50.0), 0), line((0.0, 50.0), (200.0, 50.0), 1), rect(0.0, 0.0, 100.0, 50.0, 2)]; + let BuilderArrangement { lines, lines_under, .. } = shape_builder(&s, false); + let spans = |pieces: &[Shape], key: u64| { + let mut v: Vec<_> = pieces.iter().filter(|l| l.key == key).filter_map(|l| l.path.bounds().map(|b| (b.x0, b.x1))).collect(); + v.sort_by(|a, b| a.0.total_cmp(&b.0)); + v + }; + assert_eq!(spans(&lines, 1), [(100.0, 200.0)], "{lines:?}"); + assert_eq!(spans(&lines_under, 1), [(0.0, 100.0)], "{lines_under:?}"); + assert_eq!(spans(&lines, 0), [], "{lines:?}"); + assert_eq!(spans(&lines_under, 0), [(0.0, 100.0), (100.0, 200.0)], "{lines_under:?}"); + // Without the rectangle, both lines are cut where the line across them crosses. + let s = [line((0.0, 50.0), (200.0, 50.0), 0), line((0.0, 50.0), (200.0, 50.0), 1), line((100.0, 0.0), (100.0, 100.0), 2)]; + let BuilderArrangement { lines, lines_under, .. } = shape_builder(&s, false); + assert_eq!(spans(&lines, 1), [(0.0, 100.0), (100.0, 200.0)], "{lines:?}"); + assert_eq!(spans(&lines_under, 0), [(0.0, 100.0), (100.0, 200.0)], "{lines_under:?}"); + // Live Paint's edges stay one per stretch, the front line's. + assert_eq!(live_paint(&s).1.iter().filter(|e| e.key == 0).count(), 0); +} + #[test] fn shape_builder_merges_adjacent_gap_closed_faces_without_keeping_bridges() { let outline = Shape::new( diff --git a/crates/tools/src/builder/map.rs b/crates/tools/src/builder/map.rs index ddcbcb310e..b1ccfa949d 100644 --- a/crates/tools/src/builder/map.rs +++ b/crates/tools/src/builder/map.rs @@ -81,8 +81,9 @@ impl BuilderMap { }) .collect() }; - // A line keeps its pieces under the outline of a closed path in front of it, so a merge - // or an erase removes them as it does the rest of the line. + // A line keeps its pieces under the outline of a closed path or along a line in front of + // it, so a merge or an erase removes them as it does the rest of the line. The pieces in + // front come first, so a hit where pieces lie on each other takes the one in front. let lines = arr.lines.into_iter().chain(arr.lines_under).collect(); Self { shapes, regions: faces_of(arr.regions), lines: bounded(lines), edges: bounded(arr.edges) } } diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index 2104609cf7..fc3ed294c3 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -363,6 +363,30 @@ fn shape_builder_keeps_a_line_under_an_edge_in_front_and_alt_click_there_takes_t assert!(matches!(map.hit(Point::new(150.0, 51.0), Some(4.0)), Some(Hit::Line(_)))); } +#[test] +fn shape_builder_alt_click_on_coincident_lines_takes_the_front_one() { + // Two lines from (0, 50) to (200, 50), crossed by a line at x = 100: each keeps its own + // pieces, and a hit where they lie on each other takes the piece of the line in front. + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let mut s = Selection::default(); + let line = |a: (f64, f64), b: (f64, f64)| PathData::new(vec![SubPath::polyline(&[Point::new(a.0, a.1), Point::new(b.0, b.1)], false)]); + let paths = [line((0.0, 50.0), (200.0, 50.0)), line((0.0, 50.0), (200.0, 50.0)), line((100.0, 0.0), (100.0, 100.0))]; + for (k, path) in paths.into_iter().enumerate() { + let id = d.alloc_id(); + d.insert(Some(l), k, Node::path(id, path, Appearance::default_art())).unwrap(); + s.add(id); + } + let map = map_of(&d, &s); + for key in [0, 1] { + assert_eq!(map.lines.iter().filter(|(piece, _)| piece.key == key).count(), 2, "line {key}: {:?}", map.lines); + } + for x in [50.0, 150.0] { + let Some(Hit::Line(i)) = map.hit(Point::new(x, 51.0), Some(4.0)) else { panic!("no line hit at {x}") }; + assert_eq!(map.lines.get(i).map(|(piece, _)| piece.key), Some(1), "at {x}"); + } +} + #[test] fn shape_builder_erase_drag_across_an_overlap_narrower_than_twice_the_tolerance_touches_it() { let (d, s) = sliver_rects(); From e9be911c9b8d1f2315126fc7c9fbf26ede529d43 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 22:41:09 -0800 Subject: [PATCH 055/196] MCP: pointer_gesture rejects a backquote that is not a boolean A `backquote` given as a string or a number, on the request or on an event, was read as absent, so `"true"` moved the object's geometry instead of its pattern. `pointer_gesture` and `ui.pointer`, headless and desktop, now answer with an error before any event runs. --- crates/mcp/src/headless.rs | 6 +++--- crates/mcp/src/tests.rs | 28 ++++++++++++++++++++++++++++ crates/mcp/src/tools/dispatch.rs | 6 ++++++ crates/tools/src/input.rs | 16 ++++++++++++++++ crates/ui-egui/src/control.rs | 9 +++++++-- crates/ui-egui/src/control/tests.rs | 23 +++++++++++++++++++++++ docs/mcp.md | 1 + 7 files changed, 84 insertions(+), 5 deletions(-) diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs index 64a7f0ea1f..0a81bb127f 100644 --- a/crates/mcp/src/headless.rs +++ b/crates/mcp/src/headless.rs @@ -181,9 +181,11 @@ impl Headless { fn pointer(&mut self, p: &Value) -> Result { let events = p.get("events").and_then(Value::as_array).ok_or("missing `events`")?; let base: Mods = p.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or_default(); + let default = PointerEvent::json_backquote(p, false)?; + let held = events.iter().map(|e| PointerEvent::json_backquote(e, default)).collect::, _>>()?; self.ensure_document(); let mut requests = vec![]; - for e in events { + for (e, backquote) in events.iter().zip(held) { let kind = s(e, "kind").unwrap_or(""); let kind = pointer_kind(kind).ok_or_else(|| format!("unknown pointer kind `{kind}` (down|drag|up|move|doubleclick)"))?; if s(e, "space") == Some("screen") { @@ -192,8 +194,6 @@ impl Headless { let x = e.get("x").and_then(Value::as_f64).ok_or("pointer event needs numeric `x`")?; let y = e.get("y").and_then(Value::as_f64).ok_or("pointer event needs numeric `y`")?; let mods = e.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or(base); - let backquote = - e.get("backquote").and_then(Value::as_bool).unwrap_or_else(|| p.get("backquote").and_then(Value::as_bool).unwrap_or(false)); let ev = PointerEvent { kind, pos: Point::new(x, y), diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 2e153b62b7..90df3349ec 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -1431,6 +1431,34 @@ fn pointer_gesture_forwards_backquote_on_each_event() { assert_eq!(rect["bounds"]["x"], 100.0, "{doc}"); } +/// A `backquote` that is not a boolean is an error, and none of the gesture's events runs. +#[test] +fn pointer_gesture_rejects_a_backquote_that_is_not_a_boolean() { + let mut s = server(); + let made = call(&mut s, 1, "draw_shape", json!({"shape": "rectangle", "x": 100, "y": 100, "width": 50, "height": 50, "fill": "#ff0000"})); + let id = serde_json::from_str::(&text_of(&made)).unwrap()["id"].as_u64().unwrap(); + let drag = |top: Option, first: Option| { + let mut down = json!({"kind": "down", "x": 300, "y": 300}); + if let Some(b) = first { + down["backquote"] = b; + } + let mut a = json!({"tool": "rectangle", "events": [down, {"kind": "drag", "x": 350, "y": 350}, {"kind": "up", "x": 350, "y": 350}]}); + if let Some(b) = top { + a["backquote"] = b; + } + a + }; + for (n, args) in [drag(Some(json!("true")), None), drag(None, Some(json!(1)))].into_iter().enumerate() { + let r = call(&mut s, 2 + n as u64, "pointer_gesture", args); + assert_eq!(r["isError"], true, "{r}"); + assert!(text_of(&r).contains("`backquote` must be a boolean"), "{r}"); + } + let inspected = call(&mut s, 4, "inspect_document", json!({})); + let doc = serde_json::from_str::(&text_of(&inspected)).unwrap(); + let children = doc["layers"][0]["children"].as_array().unwrap(); + assert_eq!(children.iter().map(|n| n["id"].as_u64()).collect::>(), vec![Some(id)], "{doc}"); +} + /// A Shift-drag marquee reaches agents (#483): `pointer_gesture` with `mods.shift` toggles the /// objects it reaches, so a selected one leaves the selection and an unselected one joins it. #[test] diff --git a/crates/mcp/src/tools/dispatch.rs b/crates/mcp/src/tools/dispatch.rs index 9e3af3dbaa..f9d768eaa5 100644 --- a/crates/mcp/src/tools/dispatch.rs +++ b/crates/mcp/src/tools/dispatch.rs @@ -125,6 +125,12 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Args) -> Result f64 { e.get("holdMs").and_then(Value::as_f64).filter(|f| f.is_finite()).map_or(0.0, |ms| ms.clamp(0.0, 60_000.0) / 1000.0) } + /// Whether backquote is held, from the `backquote` of a JSON pointer event or request (control + /// channel, MCP): `default` when the key is absent, an error when it is not a boolean. + pub fn json_backquote(v: &Value, default: bool) -> Result { + v.get("backquote").map_or(Ok(default), |b| b.as_bool().ok_or_else(|| "`backquote` must be a boolean".to_owned())) + } } #[cfg(test)] @@ -119,6 +124,17 @@ mod tests { value["backquote"] = serde_json::json!(true); assert!(serde_json::from_value::(value).unwrap().backquote); } + + #[test] + fn json_backquote_takes_the_default_only_when_absent() { + use serde_json::json; + assert_eq!(PointerEvent::json_backquote(&json!({}), true), Ok(true)); + assert_eq!(PointerEvent::json_backquote(&json!({"backquote": false}), true), Ok(false)); + assert_eq!(PointerEvent::json_backquote(&json!({"backquote": true}), false), Ok(true)); + for bad in [json!("true"), json!(1), json!(null)] { + assert!(PointerEvent::json_backquote(&json!({"backquote": bad}), false).is_err(), "{bad}"); + } + } } /// Keys tools care about. diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 045ad97328..3734be480b 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -540,7 +540,13 @@ fn pointer_events(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlRe let base_mods: Mods = p.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or_default(); let view = app.view_info(); let xf = app.canvas_rect.zip(app.view().copied()).map(|(rect, v)| Xf::new(rect, &v)); - for e in events { + let held = + PointerEvent::json_backquote(p, false).and_then(|d| events.iter().map(|e| PointerEvent::json_backquote(e, d)).collect::, _>>()); + let held = match held { + Ok(held) => held, + Err(e) => return err(e), + }; + for (e, backquote) in events.iter().zip(held) { let kind = match e.get("kind").and_then(Value::as_str).unwrap_or("") { "down" => PointerKind::Down, "drag" => PointerKind::Drag, @@ -566,7 +572,6 @@ fn pointer_events(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlRe Some(xf) if screen => crate::canvas::pose_on_page(q, &xf), _ => q, }); - let backquote = e.get("backquote").and_then(Value::as_bool).unwrap_or_else(|| p.get("backquote").and_then(Value::as_bool).unwrap_or(false)); crate::canvas::dispatch(app, &PointerEvent { kind, pos, mods, backquote, pressure: PointerEvent::json_pressure(e), pen }, view); let hold = PointerEvent::json_hold(e); if hold > 0.0 { diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index d084d7ee04..e587c0489f 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -293,6 +293,29 @@ fn synthetic_pointer_backquote_keeps_solid_object_in_place() { assert_eq!(xf.as_coeffs()[4], 20.0, "synthetic backquote drag changes pattern paint"); } +/// `ui.pointer` rejects a `backquote` that is not a boolean, given for the request or for any +/// event, before any of the events runs. +#[test] +fn synthetic_pointer_rejects_a_backquote_that_is_not_a_boolean() { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + assert_eq!(input_request(&mut app, "ui.tool.select", json!({"tool": "selection"}))["ok"], true); + let before = app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone(); + let down = json!({"kind": "down", "x": 125, "y": 125}); + let drag = json!({"kind": "drag", "x": 145, "y": 125}); + for params in [ + json!({"events": [down, drag, {"kind": "up", "x": 145, "y": 125}], "backquote": "true"}), + json!({"events": [down, drag, {"kind": "up", "x": 145, "y": 125, "backquote": 1}]}), + ] { + let r = input_request(&mut app, "ui.pointer", params.clone()); + assert_eq!(r["ok"], false, "{params}: {r}"); + assert!(r["error"].as_str().is_some_and(|e| e.contains("`backquote` must be a boolean")), "{r}"); + assert_eq!(app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap(), &before, "{params}"); + } +} + /// `ui.pointer` replies with the key object: a click on one of two selected objects makes it /// the key, and a click on the key again lets it go. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index fcbb492fdc..da1c1658e9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -426,6 +426,7 @@ opens the picker through `run_command` with the remote backend. | `inspect_document` | `{depth?, childLimit?, ids?, kind?, limit?, offset?}` | Artboards (with `color`, `#rrggbb`, for one with a background color), layer tree (ids, kinds, bounds, paint), selection, history, tool. A type node's `fill`, `stroke` and `strokeWidth` are the paint its characters show (its first run's); fills and strokes of the type object itself come as `objectFill`, `objectStroke` and `objectStrokeWidth`. Paint comes as a label (`"#ff0000"`, `"None"`, `"G1 40% (#ff9999)"` for a swatch at a tint); `paint.proxies` gives it as an object. | | `inspect_ui` | `{}` | UI state. Remote mode only. | | `select_tool` | `{tool}` | `selection`, `directSelection`, `pen`, `rectangle`, `ellipse`, `polygon`, `star`, `lineSegment`, … | +| `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`. `backquote` is the held state for each event; the top-level value supplies its default, and a `backquote` that is not a boolean is an error. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. | | `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`. `backquote` is the held state for each event; the top-level value supplies its default. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. Remote, the events wait until the keys and other input sent before them (`press_key`, `type_text`) have reached the app, so a key pressed between two calls of one drag applies before the release. | | `draw_path` | `{points \| d, closed?, fill?, stroke?, strokeWidth?, dash?, cap?, join?, opacity?, name?, effects?}` | `points` is `[[x,y],…]` or `[{x,y,in?,out?,smooth?},…]`. `d` is SVG path data. The options are below. | | `draw_shape` | `{shape, …geometry, fill?, stroke?, strokeWidth?, dash?, cap?, join?, opacity?, name?, effects?}` | `rectangle`/`ellipse`: `x,y,width,height` (plus `radius` for corners). `polygon`: `cx,cy,radius,sides`. `star`: `cx,cy,radius1,radius2,points`. `line`: `x1,y1,x2,y2`. | From 2038dc7849f051c2fbae925e4b69e3ab80a9090d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 22:51:22 -0800 Subject: [PATCH 056/196] SVG export: numbers are written from integers, not through the exact float formatter push_num formatted every number with write!("{:.*}"), which runs the exact decimal float formatter, then scanned and trimmed the text. That formatter was about 95% of the time to export a path of 200,000 anchors. At 9 decimals or fewer, push_num now scales the value by 10^decimals and writes the digits of the rounded integer when that rounding is certain: the scaled value is below 2^53 and further from a half than the scaling's rounding error. Ties and larger values still go through the formatter, so the output is the same byte for byte. Exporting one path of 200,000 anchors takes a median of 43.4 ms instead of 167.0 ms, and 20,000 rectangles 81.4 ms instead of 141.4 ms (Windows 11, release build). --- crates/svg/src/lib.rs | 90 +++++++++++++++++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 2 files changed, 91 insertions(+) diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index ccc154a383..58cb434ed2 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -624,6 +624,49 @@ pub fn xml_escape(s: &str) -> String { o } +/// [`push_num`] through integer arithmetic, for the values it writes the same as the decimal +/// formatter: `decimals` of at most 9, and `v` scaled by 10^`decimals` below 2^53 and further from +/// halfway between two integers than the scaling's rounding error. Returns false, writing nothing, +/// for any other value. +fn push_num_scaled(out: &mut String, v: f64, decimals: u8) -> bool { + const SCALE: [f64; 10] = [1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9]; + let Some(&scale) = SCALE.get(usize::from(decimals)) else { return false }; + // Each power of ten here is exact, so `x` is within half an ulp (`x * EPSILON / 2`) of |v| × 10^decimals. + let x = v.abs() * scale; + if x.is_nan() || x >= 9.0e15 { + return false; + } + let whole = x.floor(); + let frac = x - whole; + if (frac - 0.5).abs() <= x * f64::EPSILON { + return false; + } + let mut n = whole as u64 + u64::from(frac > 0.5); + let places = usize::from(decimals); + // The digits of `n` from the last one, at least one more than `places` of them. + let mut digits = [0u8; 24]; + let mut len = 0; + for d in digits.iter_mut() { + if n == 0 && len > places { + break; + } + *d = b'0' + (n % 10) as u8; + n /= 10; + len += 1; + } + let Some((fraction, int)) = digits.get(..len).and_then(|d| d.split_at_checked(places)) else { return false }; + let zeros = fraction.iter().take_while(|&&d| d == b'0').count(); + if v < 0.0 && (zeros < places || int.iter().any(|&d| d != b'0')) { + out.push('-'); + } + out.extend(int.iter().rev().map(|&d| char::from(d))); + if zeros < places { + out.push('.'); + out.extend(fraction.iter().skip(zeros).rev().map(|&d| char::from(d))); + } + true +} + /// Format a number with at most `decimals` places, trimming trailing zeros. pub fn fmt_num(v: f64, decimals: u8) -> String { let mut s = String::new(); @@ -635,6 +678,9 @@ pub fn fmt_num(v: f64, decimals: u8) -> String { pub fn push_num(out: &mut String, v: f64, decimals: u8) { use std::fmt::Write as _; let v = if v.is_finite() { v } else { 0.0 }; + if push_num_scaled(out, v, decimals) { + return; + } let start = out.len(); let _ = write!(out, "{:.*}", decimals as usize, v); // writing to a String can't fail let s = out.get(start..).unwrap_or_default(); @@ -674,4 +720,48 @@ mod tests { fn escaping() { assert_eq!(xml_escape("a&\"'"), "a<b>&"'"); } + + /// `v` at `decimals` places by the decimal formatter, trailing zeros trimmed. + fn formatted(v: f64, decimals: u8) -> String { + let s = format!("{:.*}", usize::from(decimals), if v.is_finite() { v } else { 0.0 }); + let s = if s.contains('.') { s.trim_end_matches('0').trim_end_matches('.') } else { &s }; + if matches!(s, "-0" | "") { "0".into() } else { s.into() } + } + + #[test] + fn numbers_match_the_decimal_formatter() { + let mut values = + vec![0.0, -0.0, 0.5, -0.5, 2.5, 0.0005, -0.0005, 1.0005, 0.125, 1e-12, 9.0e15, 4503599627370495.5, 1e20, f64::NAN, f64::INFINITY]; + // Coordinates of every size, and values on and just off the halfway points between written numbers. + let mut seed = 0x2545_f491_4f6c_dd1d_u64; + for _ in 0..20_000 { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + let unit = (seed >> 11) as f64 / (1u64 << 53) as f64; + let v = (unit - 0.5) * 10f64.powi((seed % 13) as i32 - 3); + let tie = ((v * 1000.0).trunc() + 0.5) / 1000.0; + values.extend([v, tie, f64::from_bits(tie.to_bits() + 1), f64::from_bits(tie.to_bits() - 1)]); + } + for v in values { + for d in 0..=12 { + assert_eq!(fmt_num(v, d), formatted(v, d), "{v:e} at {d} decimals"); + } + } + } + + #[test] + fn coordinates_are_written_through_integers() { + for (v, d, want) in [(123.4567, 3, "123.457"), (-0.25, 3, "-0.25"), (-0.0004, 3, "0"), (1600.0, 3, "1600"), (7.0, 0, "7")] { + let mut s = String::new(); + assert!(push_num_scaled(&mut s, v, d), "{v} at {d} decimals"); + assert_eq!(s, want); + } + // Halfway as stored, too large, or too many places: the decimal formatter writes them. + for (v, d) in [(0.5, 0), (0.125, 2), (1e16, 0), (1.0, 10)] { + let mut s = String::new(); + assert!(!push_num_scaled(&mut s, v, d), "{v} at {d} decimals"); + assert!(s.is_empty()); + } + } } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3051202252..a1b4194126 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1169,6 +1169,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur SVG import's style cascade, used for hidden objects, non-scaling strokes and type, tests each element only against the ` + + + + + + + + "#; + let counts: Vec = imported_gradients(svg).iter().map(|g| g.stops.len()).collect(); + assert_eq!(counts.len(), 5); + assert!(counts[..3].iter().all(|&n| n > 2), "{counts:?}"); + assert_eq!(counts[3], 2, "{counts:?}"); + assert!(counts[4] > 2, "{counts:?}"); +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 811a014839..4186db3eb7 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (`.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (SVG import: `color-interpolation="linearRGB"` gradients, #5878) · **Target:** Adobe Illustrator 2026 (30.x) Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`, `OPEN_EXTS`, `PLACE_EXTS` in `crates/engine/src/cmd/fileio/formats.rs`). Illustrator's list comes from its public @@ -189,6 +189,7 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri | Date | Change | Summary | |---|---|---| +| 2026-11-06 | minor | SVG import: a gradient with `color-interpolation="linearRGB"` (on it, inherited, or from a style sheet) mixes its stops in linear light, as SVG 1.1 §11.7.1 asks: the document gradient gets extra stops wherever display-RGB mixing would stray by half a colour level or more, so black to white is about 188/255 mid-way instead of 128 (#5878). A gradient several objects share is mixed so on every one. Opacity still mixes evenly; at most 4096 stops per gradient. Tests `import::linear_rgb`, `gradients::linear_rgb_*` (crate `vectorcraft-svg`); scores unchanged | | 2026-11-05 | minor | `.ai` import (#372): a path with a Calligraphic brush comes in as the path with the brush on its stroke (its weight scales the brush) when its art style's brush settings are the brush's own and its angle is on the page, else as its drawn look; a Calligraphic brush's Tilt, Bearing and Rotation codes come in as those channels instead of Random. Checked against a user's file of 6D Art Pen strokes (used locally, not committed); synthetic tests in `import::ai::tests` | | 2026-11-05 | minor | PDF import: the stops of an axial or radial shading in a DeviceN space of one spot ink and process plates link to the ink's swatch and keep the plates (`GradientStop.plates` in the native format); PDF and EPS export write them in a DeviceN space again (#3235) | | 2026-11-04 | minor | Raster/PSD export uses document resolution unless ppi or scale is supplied; CLI run/convert accept --ppi. Synthetic engine, CLI and MCP regressions cover dimensions and override precedence; scores and hours unchanged. | From d58d47312ffd5c7c18dc1243bfed4bf4b208109a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 6 Nov 2026 00:16:24 -0800 Subject: [PATCH 188/196] Legacy .ai export: black-and-white colorized images save as image masks A colorized image whose pixels are all black or white (or clear) is written as a 1-bit image mask (ImageMask 1): its color as the fill, a 0 bit for each black pixel and a 1 bit for each white or clear one. The legacy reader opens it colorized again with the same clear pixels, so the engine no longer flattens or omits it. Other colorized images are written with their color in their pixels, over white, with the note for transparent images. --- crates/engine/src/cmd/fileio/legacy_ai.rs | 13 +-- crates/engine/src/cmd/fileio/native.rs | 2 +- crates/engine/src/tests/colorize.rs | 10 ++- crates/engine/src/tests/legacy_ai.rs | 97 ++++++++++++++++++++++- crates/eps/src/legacy_ai.rs | 21 +++++ crates/eps/src/legacy_ai/prolog.rs | 8 +- crates/eps/src/legacy_ai/tests.rs | 88 ++++++++++++++++++++ crates/eps/src/legacy_ai/writer.rs | 81 ++++++++++++++----- crates/eps/src/lib.rs | 2 +- docs/file-format-parity.md | 6 +- docs/mcp.md | 4 +- 11 files changed, 297 insertions(+), 35 deletions(-) diff --git a/crates/engine/src/cmd/fileio/legacy_ai.rs b/crates/engine/src/cmd/fileio/legacy_ai.rs index d4820242d9..691c0e8364 100644 --- a/crates/engine/src/cmd/fileio/legacy_ai.rs +++ b/crates/engine/src/cmd/fileio/legacy_ai.rs @@ -20,7 +20,9 @@ //! pixels, or opacity or a blending mode on the image, the fill, the shape or a group it is in) is //! expanded into its tiles first so its images flatten too. With `omit` the images with //! see-through pixels, opacity or a blending mode of their own are left out, and pattern fills stay -//! as the writer draws them (their tiles opaque over white). An image that can't be decoded is +//! as the writer draws them (their tiles opaque over white). A colorized image is flattened or +//! left out the same way, unless its pixels are all black or white: the writer writes that one as +//! a 1-bit image mask in its color, which keeps its white pixels clear. An image that can't be decoded is //! missing from the images that flattening and expanding raster effects draw, and the warnings //! then carry the raster exports' note once. //! @@ -179,8 +181,10 @@ fn expand_image_patterns(d: &mut Document) -> Result<()> { } /// The images of `d` a legacy `.ai` can't hold, in paint order with their places in it (as -/// [`Document::walk`] counts). These have see-through pixels or a colorize paint, or have opacity -/// or a blending mode of their own or, with `flatten`, of a group they are in. +/// [`Document::walk`] counts). These have see-through pixels or a colorize paint (except the +/// colorized images the writer writes as image masks, clear pixels included, +/// [`vectorcraft_eps::writes_image_mask`]), or +/// have opacity or a blending mode of their own or, with `flatten`, of a group they are in. /// With `flatten` only visible images are returned, because a hidden one (which the hidden objects /// option may write) is written over white. With `omit` all of them are returned. fn see_through_images(d: &Document, mode: SeeThrough) -> Vec<(usize, NodeId)> { @@ -189,8 +193,7 @@ fn see_through_images(d: &Document, mode: SeeThrough) -> Vec<(usize, NodeId)> { let mut at = 0; d.walk(|n| { if let NodeKind::Image(im) = &n.kind - && (keys.contains(&im.key) - || n.extras().colorize.is_some() + && (((keys.contains(&im.key) || n.extras().colorize.is_some()) && !vectorcraft_eps::writes_image_mask(d, n)) || n.opacity < 1.0 || n.blend != BlendMode::Normal || (mode == SeeThrough::Flatten && transparent(d, n.id))) diff --git a/crates/engine/src/cmd/fileio/native.rs b/crates/engine/src/cmd/fileio/native.rs index 6cb513db62..4d293fe69d 100644 --- a/crates/engine/src/cmd/fileio/native.rs +++ b/crates/engine/src/cmd/fileio/native.rs @@ -121,7 +121,7 @@ pub const AI_OPTIONS: &[FormatOption] = &[ name: "transparentImages", ty: "string", default: "\"flatten\"", - description: "with aiVersion 7, the images version 7 can't hold (see-through pixels, opacity or a blending mode): flatten (the default: each becomes an opaque image of itself and the art under it, clipped to where it changes what shows; that art stays as it is) or omit (left out)", + description: "with aiVersion 7, the images version 7 can't hold (see-through pixels, opacity, a blending mode, or a colorize color unless every pixel is black or white): flatten (the default: each becomes an opaque image of itself and the art under it, clipped to where it changes what shows; that art stays as it is) or omit (left out)", }, FormatOption { name: "hiddenObjects", diff --git a/crates/engine/src/tests/colorize.rs b/crates/engine/src/tests/colorize.rs index 2dab48c9f0..40152af747 100644 --- a/crates/engine/src/tests/colorize.rs +++ b/crates/engine/src/tests/colorize.rs @@ -370,13 +370,21 @@ fn colorized_gray_image_is_flattened_for_pdf_x_1a() { assert!(!String::from_utf8_lossy(&bytes).contains("/SMask"), "PDF/X-1a has no soft mask"); } +/// A colorized image with a gray pixel is left out; one of black and white pixels is written as an +/// image mask and kept. #[test] fn colorized_gray_image_is_omitted_from_legacy_ai_when_requested() { + let mut s = session(); + let mid = png(image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(2, 1, vec![0, 128]).unwrap())); + let id = image(&mut s, "mid", mid); + s.execute("paint.setFill", &json!({"color": "#ff0000", "ids": [id.0]})).unwrap(); + let out = s.execute("file.saveCopy", &json!({"format": "ai", "aiVersion": "7", "transparentImages": "omit"})).unwrap(); + assert!(out["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("are left out")), "{}", out["warnings"]); let mut s = session(); let id = image(&mut s, "gray", gray(false)); s.execute("paint.setFill", &json!({"color": "#ff0000", "ids": [id.0]})).unwrap(); let out = s.execute("file.saveCopy", &json!({"format": "ai", "aiVersion": "7", "transparentImages": "omit"})).unwrap(); - assert!(out["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("are left out")), "{}", out["warnings"]); + assert!(!out["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("are left out")), "{}", out["warnings"]); } #[test] diff --git a/crates/engine/src/tests/legacy_ai.rs b/crates/engine/src/tests/legacy_ai.rs index b9f67f51aa..c4722c9c16 100644 --- a/crates/engine/src/tests/legacy_ai.rs +++ b/crates/engine/src/tests/legacy_ai.rs @@ -447,6 +447,100 @@ fn transparent_images_can_be_left_out_and_opacity_makes_one_transparent() { assert_eq!(v["options"]["transparentImages"]["value"], "flatten", "{v}"); } +/// A red square (10–50 × 10–50) half under a 4 × 2 black-and-white image (30–70 × 10–30) that the +/// spot color `Ink` colorizes. Returns the session and the image's pixels. +fn colorized_bitmap_over_square() -> (Session, Vec) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + s.execute("swatch.new", &json!({"name": "Ink", "color": {"c": 100, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let gray = vec![0, 255, 0, 255, 255, 0, 255, 0]; + let mut bytes = vec![]; + image::GrayImage::from_raw(4, 2, gray.clone()).unwrap().write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + let p = json!({"name": "b.png", "dataBase64": vectorcraft_format::base64_encode(&bytes), "rect": [30, 10, 40, 20]}); + s.execute("file.place", &p).unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap(); + (s, gray) +} + +/// An image's pixels' coverage and its colorize paint. +type Colorized = (Option<(u32, u32, Vec)>, Option); + +/// The colorized image of each image node of `d`, with its pixels' coverage. +fn colorized(d: &vectorcraft_doc::Document) -> Vec { + let mut out = vec![]; + d.walk(|n| { + if let vectorcraft_doc::NodeKind::Image(im) = &n.kind { + out.push((d.image_blob(im).and_then(vectorcraft_doc::ImageBlob::coverage), n.extras().colorize.as_deref().cloned())); + } + }); + out +} + +/// A colorized image of black and white pixels is neither flattened nor left out: it is written as +/// a 1-bit image mask in its color, with either setting of `transparentImages`, and opens again +/// colorized with that color, its white pixels clear over the square, and the square as it was. +#[test] +fn a_colorized_black_and_white_image_is_written_as_an_image_mask() { + let (mut s, gray) = colorized_bitmap_over_square(); + let before = colorized(&s.doc().unwrap().doc); + let want: Vec = gray.iter().map(|v| 255 - v).collect(); + assert!(matches!(before.as_slice(), [(Some((4, 2, c)), Some(_))] if *c == want), "{before:?}"); + for mode in ["flatten", "omit"] { + let r = s.execute("file.saveCopy", &json!({"format": "ai", "aiVersion": "7", "transparentImages": mode})).unwrap(); + assert!(!warnings(&r).iter().any(|w| w.contains("transparent images") || w.contains("flattened")), "{mode}: {r}"); + let mut t = Session::new(); + t.execute("document.open", &json!({"name": "t.ai", "dataBase64": r["dataBase64"]})).unwrap(); + let d = &t.doc().unwrap().doc; + let after = colorized(d); + assert_eq!(after.len(), 1, "{mode}: {after:?}"); + assert_eq!(after[0].0, before[0].0, "{mode}"); + let (Some(a), Some(b)) = (&after[0].1, &before[0].1) else { panic!("{mode}: {after:?}") }; + let rgb = |p: &vectorcraft_color::Paint| p.color().map(|c| c.to_rgb()).unwrap(); + assert!(rgb(a).iter().zip(rgb(b)).all(|(x, y)| (x - y).abs() < 0.01), "{mode}: {a:?} {b:?}"); + assert_eq!(images(d), (1, 0), "{mode}"); + // The first row draws as before: black (the color) and white (clear) over the square, then + // black and white (clear) over the page. + let src = &s.doc().unwrap().doc; + for x in [35.0, 45.0, 55.0, 65.0] { + let (now, was) = (colour_at(d, x, 15.0), colour_at(src, x, 15.0)); + assert!(now.iter().zip(was).all(|(a, b)| a.abs_diff(b) <= 3), "{mode} at {x}: {now:?} {was:?}"); + } + assert_ne!(colour_at(src, 35.0, 15.0), colour_at(src, 45.0, 15.0), "{mode}"); + assert_ne!(colour_at(src, 55.0, 15.0), colour_at(src, 65.0, 15.0), "{mode}"); + } +} + +/// A colorized image of black and clear pixels is written as an image mask too, its clear pixels +/// clear, instead of being flattened or left out for its see-through pixels. +#[test] +fn a_colorized_image_of_black_and_clear_pixels_is_written_as_an_image_mask() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + s.execute("swatch.new", &json!({"name": "Ink", "color": {"c": 100, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap(); + let mut bytes = vec![]; + image::GrayAlphaImage::from_raw(2, 1, vec![0, 255, 0, 0]) + .unwrap() + .write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png) + .unwrap(); + let p = json!({"name": "c.png", "dataBase64": vectorcraft_format::base64_encode(&bytes), "rect": [30, 10, 20, 10]}); + s.execute("file.place", &p).unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap(); + let before = colorized(&s.doc().unwrap().doc); + assert!(matches!(before.as_slice(), [(Some((2, 1, c)), Some(_))] if *c == [255, 0]), "{before:?}"); + for mode in ["flatten", "omit"] { + let r = s.execute("file.saveCopy", &json!({"format": "ai", "aiVersion": "7", "transparentImages": mode})).unwrap(); + assert!(!warnings(&r).iter().any(|w| w.contains("transparent images") || w.contains("flattened")), "{mode}: {r}"); + let mut t = Session::new(); + t.execute("document.open", &json!({"name": "t.ai", "dataBase64": r["dataBase64"]})).unwrap(); + let after = colorized(&t.doc().unwrap().doc); + assert_eq!(after.len(), 1, "{mode}: {after:?}"); + assert_eq!(after[0].0, before[0].0, "{mode}"); + assert!(after[0].1.is_some(), "{mode}: {after:?}"); + } +} + /// #2692's file, an image clipped to a circle inside a circle's stroke, and #2830's, an image with /// see-through pixels (which the save flattens into an image inside a clipping group), each with /// an orange square on the next layer. @@ -639,7 +733,8 @@ fn colorized_grayscale_image_pattern_keeps_its_colors_in_legacy_ai() { for (a, b) in before.iter().zip(&after) { assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(*b) <= 3), "before {before:?} after {after:?}"); } - assert!(saved_warnings.iter().any(|w| w.contains("flattened with the art under them")), "{saved_warnings:?}"); + // The tile's pixels are black or white: its images are written as image masks, not flattened. + assert!(!saved_warnings.iter().any(|w| w.contains("flattened with the art under them")), "{saved_warnings:?}"); } /// #3666: a pattern fill whose tile is an image, under opacity, is flattened with the art under it diff --git a/crates/eps/src/legacy_ai.rs b/crates/eps/src/legacy_ai.rs index 290fe3c414..4129618027 100644 --- a/crates/eps/src/legacy_ai.rs +++ b/crates/eps/src/legacy_ai.rs @@ -150,6 +150,27 @@ pub struct LegacyAiOutput { pub warnings: Vec, } +/// Whether image node `n` of `doc` is written as a 1-bit image mask in its colorize color +/// (ImageMask 1, §8.1) that draws as the document does: it is colorized with a solid color, its +/// pixels take the color and are all black or white (or clear), it has no opacity mask turned on, +/// and it has no more pixels than the writer writes. Such an image keeps its clear pixels in the file. +pub fn writes_image_mask(doc: &Document, n: &Node) -> bool { + let NodeKind::Image(im) = &n.kind else { return false }; + // The size from the file's header, before any pixels are decoded. + let fits = |bytes: &[u8]| { + image::ImageReader::new(std::io::Cursor::new(bytes)) + .with_guessed_format() + .ok() + .and_then(|r| r.into_dimensions().ok()) + .is_some_and(|(w, h)| w > 0 && h > 0 && u64::from(w) * u64::from(h) <= MAX_IMAGE_PIXELS) + }; + matches!(n.extras().colorize.as_deref(), Some(Paint::Solid { .. })) + && !n.extras().mask.as_ref().is_some_and(|m| !m.disabled) + && doc + .image_blob(im) + .is_some_and(|b| b.takes_colorize() && fits(&b.bytes) && b.coverage().is_some_and(|(_, _, c)| c.iter().all(|&v| v == 0 || v == 255))) +} + /// Write `doc`'s first artboard and every layer (all its art, on the artboard or not) as a /// legacy `.ai` file of version 7. Art space is y up, its origin at the artboard's left edge and /// just under its bottom edge: the artboard's top is on a whole point, where readers that place diff --git a/crates/eps/src/legacy_ai/prolog.rs b/crates/eps/src/legacy_ai/prolog.rs index 554447cecb..b0d606bba9 100644 --- a/crates/eps/src/legacy_ai/prolog.rs +++ b/crates/eps/src/legacy_ai/prolog.rs @@ -36,7 +36,7 @@ pub(crate) const PROCSET: &str = "VectorCraft_Legacy 1 0"; /// application's procedure set): paths and their painting with the fill and stroke colours, /// compound paths painted as one path, clipping groups, guides that don't print, layers that are /// hidden or don't print marking nothing, and images drawn from the samples on the comment lines -/// that follow `XI`. Gradients fill with the colour set before them (the writer sets the first +/// that follow `XI` (an image mask's 0 bits in the fill color). Gradients fill with the colour set before them (the writer sets the first /// stop's), and type marks nothing: apps that read the format draw both. The page trailer's /// `annotatepage` (§3, Script Setup: `gsave annotatepage grestore showpage`) marks nothing. pub(super) const PROLOG: &str = "%%BeginResource: procset VectorCraft_Legacy 1 0 @@ -96,9 +96,11 @@ VCLegacy begin /_l 256 string def /_s 128 string def /_row {{currentfile _l readline not {exit} if dup length 1 gt {exit} if pop} loop dup length 1 gt {dup length 1 sub 1 exch getinterval /ASCIIHexDecode filter _s readstring pop} {pop ()} ifelse} bd -/XI {pop pop pop pop /_ic exch def /_ib exch def /_ih exch def /_iw exch def pop pop pop pop +% An image mask (ImageMask 1) paints its 0 bits in the fill color. +/XI {1 eq /_im exch def pop pop pop /_ic exch def /_ib exch def /_ih exch def /_iw exch def pop pop pop pop [1 0 0 -1 0 0] exch matrix concatmatrix - _on {gsave concat _iw _ih _ib [1 0 0 1 0 0] /_row load false _ic 1 eq {1} {_ic} ifelse colorimage grestore} {pop} ifelse} bd + _on {gsave concat _im {_fc _iw _ih false [1 0 0 1 0 0] /_row load imagemask} + {_iw _ih _ib [1 0 0 1 0 0] /_row load false _ic 1 eq {1} {_ic} ifelse colorimage} ifelse grestore} {pop} ifelse} bd % Type (15) is set by the app that reads the file: its operators take their operands and mark % nothing; encodings (3.3) are skipped. /TE {cleartomark} bd /TZ {cleartomark} bd diff --git a/crates/eps/src/legacy_ai/tests.rs b/crates/eps/src/legacy_ai/tests.rs index 617aa54552..851228ea6d 100644 --- a/crates/eps/src/legacy_ai/tests.rs +++ b/crates/eps/src/legacy_ai/tests.rs @@ -442,6 +442,94 @@ fn empty_images_get_the_size_note_and_undecodable_ones_the_decode_note() { assert_eq!(notes(b"not an image".to_vec()), [UNDECODED]); } +/// A gray image of `doc`, `w` × `h` pixels of `gray`, colorized `paint`, placed 10 pt a pixel +/// at (`x`, `y`). +fn colorized_image(doc: &mut Document, (w, h): (u32, u32), gray: Vec, paint: &Paint, (x, y): (f64, f64)) -> Node { + let mut png = vec![]; + image::GrayImage::from_raw(w, h, gray).unwrap().write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let blob = ImageBlob::new("image/png", png); + let key = blob.content_key(); + doc.images.insert(key.clone(), blob); + let xf = Affine::new([10.0, 0.0, 0.0, 10.0, x, y]); + let im = ImageObject { key, width: w, height: h, xf, link: None, placement: Default::default(), pixels: None }; + let mut n = Node::new(doc.alloc_id(), NodeKind::Image(Box::new(im))); + n.extras_mut().colorize = Some(Box::new(paint.clone())); + n +} + +/// A colorized image whose pixels are black or white is written as a 1-bit image mask +/// (ImageMask 1) after its color as the fill: its black pixels are 0 bits, which take the color, and its +/// white pixels 1 bits, which are clear. It prints in its color over the square behind it and +/// reads back colorized with that color and with the same clear pixels. A colorized image with +/// gray pixels is written with its color in its pixels, over white, with the note for +/// transparent pixels. +#[test] +fn colorized_images_keep_their_color() { + let mut doc = Document::new(200.0, 100.0); + doc.layers.clear(); + let layer = doc.add_layer(Some("Art")); + let square = shape(&mut doc, shapes::rectangle(Rect::new(5.0, 5.0, 45.0, 30.0)), red(), Paint::None); + doc.insert(Some(layer), usize::MAX, square).unwrap(); + let paint = Paint::solid(Color::cmyk(0.0, 0.5, 1.0, 0.0)); + // 1 0 0 1 0 1 1 0 / 0 1 1 0 1 0 0 1 in black (1) and white (0). + let mask: Vec = "1001011001101001".bytes().map(|b| if b == b'1' { 0 } else { 255 }).collect(); + let bitmap = colorized_image(&mut doc, (8, 2), mask.clone(), &paint, (10.0, 10.0)); + doc.insert(Some(layer), usize::MAX, bitmap).unwrap(); + let out = write(&doc); + let text = String::from_utf8(out.bytes.clone()).unwrap(); + let images = rasters(&text); + assert_eq!(images.len(), 1, "{text}"); + let [_, _, xi, data @ .., _, _] = images[0].as_slice() else { panic!("{:?}", images[0]) }; + assert!(xi.ends_with(" ] 0 0 8 2 8 2 1 1 0 0 0 1 XI"), "{xi}"); + // Each row is a byte: the black pixels are 0 bits. + assert_eq!(data, &["%6996"], "{text}"); + let at = text.find("%AI5_File:\n").unwrap(); + assert!(text[..at].ends_with("0 0.5 1 0 k\n"), "{text}"); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let read = crate::import(&out.bytes).unwrap().document; + let mut found = vec![]; + read.walk(|n| { + if let NodeKind::Image(im) = &n.kind { + found.push((read.image_blob(im).and_then(ImageBlob::coverage), n.extras().colorize.as_deref().cloned())); + } + }); + let want: Vec = mask.iter().map(|&v| 255 - v).collect(); + assert_eq!(found, [(Some((8, 2, want)), Some(paint.clone()))]); + + // Gray pixels: the color at each pixel's strength, over white. + let mut doc = Document::new(200.0, 100.0); + doc.layers.clear(); + let layer = doc.add_layer(Some("Art")); + let tint = colorized_image(&mut doc, (2, 1), vec![0, 128], &Paint::solid(Color::rgb(1.0, 0.0, 0.0)), (10.0, 10.0)); + doc.insert(Some(layer), usize::MAX, tint).unwrap(); + let out = write(&doc); + let text = String::from_utf8(out.bytes.clone()).unwrap(); + let images = rasters(&text); + let [_, _, xi, data @ .., _, _] = images[0].as_slice() else { panic!("{:?}", images[0]) }; + assert!(xi.ends_with(" ] 0 0 2 1 2 1 8 3 0 0 0 0 XI"), "{xi}"); + assert_eq!(data, &["%FF0000FF8080"], "{text}"); + assert_eq!(out.warnings, [IMAGE_ALPHA]); +} + +/// An image mask is only for a colorized image the writer draws as the document does: not one +/// with an opacity mask turned on, and not one with more pixels than the writer writes. +#[test] +fn image_masks_are_for_images_the_writer_draws_as_they_are() { + let mut doc = Document::new(200.0, 100.0); + let paint = Paint::solid(Color::cmyk(0.0, 0.5, 1.0, 0.0)); + let mut n = colorized_image(&mut doc, (2, 1), vec![0, 255], &paint, (10.0, 10.0)); + assert!(writes_image_mask(&doc, &n)); + let art = shape(&mut doc, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Paint::solid(Color::gray(1.0)), Paint::None); + n.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(art, false))); + assert!(!writes_image_mask(&doc, &n)); + if let Some(m) = n.extras_mut().mask.as_mut() { + m.disabled = true; + } + assert!(writes_image_mask(&doc, &n)); + let big = colorized_image(&mut doc, (8193, 8193), vec![255; 8193 * 8193], &paint, (10.0, 10.0)); + assert!(!writes_image_mask(&doc, &big)); +} + #[test] fn a_gradient_fill_and_its_stroke_are_one_object() { let mut doc = Document::new(100.0, 100.0); diff --git a/crates/eps/src/legacy_ai/writer.rs b/crates/eps/src/legacy_ai/writer.rs index 1fe58d6595..ae8fddc70b 100644 --- a/crates/eps/src/legacy_ai/writer.rs +++ b/crates/eps/src/legacy_ai/writer.rs @@ -272,7 +272,11 @@ impl<'a> Writer<'a> { } NodeKind::Image(im) => { self.lock(locked); - self.image(self.doc.image_blob(im), im.width, im.height, im.xf); + let blob = self.doc.image_blob(im); + // A colorize color the renderer draws the image in. + let colorize = + n.extras().colorize.as_deref().filter(|p| matches!(p, Paint::Solid { .. }) && blob.is_some_and(ImageBlob::takes_colorize)); + self.image(blob, im.width, im.height, im.xf, colorize); } NodeKind::SymbolInstance { symbol, xf } => { self.warn(LIVE); @@ -835,7 +839,7 @@ impl<'a> Writer<'a> { // Colour bitmap glyphs (emoji): their images, which the runs' paint doesn't paint. for g in &layout.glyphs { if let Some((image, to_text)) = g.placed_image() { - self.image(Some(&image.blob), image.width, image.height, t.xf * to_text); + self.image(Some(&image.blob), image.width, image.height, t.xf * to_text, None); } // COLR glyphs: their layers, as art. if let Some(art) = g.placed_colour(t.xf) { @@ -853,8 +857,12 @@ impl<'a> Writer<'a> { /// `%AI5_EndRaster`, then `F`. §8.4's examples have no `F`; without it, an app reading the file /// can leave out an image in a clipping group and the art after it. No path is open there, so /// the `F` paints nothing. `blob` holds the pixels, placed as a grid of `width` × `height` - /// by `xf`. - fn image(&mut self, blob: Option<&ImageBlob>, width: u32, height: u32, xf: Affine) { + /// by `xf`, and `colorize` is the solid color the image is colorized with. A colorized image + /// whose pixels are all black or white is written as an image mask (ImageMask 1, §8.1): its + /// color as the fill, then 1-bit samples, a 0 bit for each black pixel, which takes the color, + /// and a 1 bit for each white pixel, which is clear. Another colorized image is written with + /// its color in its pixels. + fn image(&mut self, blob: Option<&ImageBlob>, width: u32, height: u32, xf: Affine, colorize: Option<&Paint>) { let flip = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 0.0]); let m = self.to_art * xf * flip; if !invertible(m) { @@ -876,25 +884,61 @@ impl<'a> Writer<'a> { // The object places the image's own pixel grid (its width × height) wherever the file's is. let fit = Affine::scale_non_uniform(f64::from(width.max(1)) / f64::from(w), f64::from(height.max(1)) / f64::from(h)); let m = self.to_art * xf * fit * flip; + // Over white. + let over = |c: u8, a: u8| ((u32::from(c) * u32::from(a) + 255 * (255 - u32::from(a)) + 127) / 255) as u8; + if let Some(paint) = colorize { + let Some((_, _, coverage)) = blob.and_then(ImageBlob::coverage).filter(|(cw, ch, _)| (*cw, *ch) == (w, h)) else { + self.warn(UNDECODED); + return; + }; + if coverage.iter().all(|&v| v == 0 || v == 255) { + let stride = (w as usize).div_ceil(8); + let mut bits = vec![0xFF; stride.saturating_mul(h as usize)]; + for (i, _) in coverage.iter().enumerate().filter(|(_, v)| **v == 255) { + let (x, y) = (i % w as usize, i / w as usize); + if let Some(byte) = bits.get_mut(y * stride + x / 8) { + *byte &= !(0x80 >> (x % 8)); + } + } + self.color(paint, false); + self.raster(m, &format!("0 0 {w} {h} {w} {h} 1 1 0 0 0 1"), &bits); + return; + } + let rgb = paint.color().map_or([0; 3], |c| c.to_rgb().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)); + let samples: Vec = coverage.iter().flat_map(|&a| rgb.map(|c| over(c, a))).collect(); + self.warn(IMAGE_ALPHA); + self.raster(m, &format!("0 0 {w} {h} {w} {h} 8 3 0 0 0 0"), &samples); + return; + } let rgba = img.to_rgba8(); - let mut hex = String::with_capacity(rgba.len() / 4 * 7); - hex.push('%'); - let mut on_line = 0; + let mut samples = Vec::with_capacity(rgba.len() / 4 * 3); let mut see_through = false; for px in rgba.pixels() { let [r, g, b, a] = px.0; if a < 255 { see_through = true; } - // Over white. - let over = |c: u8| ((u32::from(c) * u32::from(a) + 255 * (255 - u32::from(a)) + 127) / 255) as u8; - for c in [over(r), over(g), over(b)] { - let _ = write!(hex, "{c:02X}"); - on_line += 2; - if on_line >= HEX_LINE { - hex.push_str("\n%"); - on_line = 0; - } + samples.extend([over(r, a), over(g, a), over(b, a)]); + } + if see_through { + self.warn(IMAGE_ALPHA); + } + self.raster(m, &format!("0 0 {w} {h} {w} {h} 8 3 0 0 0 0"), &samples); + } + + /// An image's lines (§8.4): `%AI5_File:`, `%AI5_BeginRaster`, matrix `m` as `[ a b c d tx ty ]` + /// and the numbers `operands` with `XI`, `samples` in hex on comment lines of [`HEX_LINE`] + /// digits, `%AI5_EndRaster`, then `F`. + fn raster(&mut self, m: Affine, operands: &str, samples: &[u8]) { + let mut hex = String::with_capacity(samples.len() * 2 + samples.len() / HEX_LINE * 2 + 2); + hex.push('%'); + let mut on_line = 0; + for c in samples { + let _ = write!(hex, "{c:02X}"); + on_line += 2; + if on_line >= HEX_LINE { + hex.push_str("\n%"); + on_line = 0; } } if hex.ends_with('%') { @@ -902,14 +946,11 @@ impl<'a> Writer<'a> { } else { hex.push('\n'); } - if see_through { - self.warn(IMAGE_ALPHA); - } let [a, b, c, d, e, f] = m.as_coeffs(); let s = &mut self.body; s.push_str("%AI5_File:\n%AI5_BeginRaster\n[ "); ps::push_nums(s, &[a, b, c, d, e, f]); - let _ = writeln!(s, "] 0 0 {w} {h} {w} {h} 8 3 0 0 0 0 XI"); + let _ = writeln!(s, "] {operands} XI"); s.push_str(&hex); s.push_str("%AI5_EndRaster\nF\n"); } diff --git a/crates/eps/src/lib.rs b/crates/eps/src/lib.rs index 51d2447523..c5ee02e72e 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -47,7 +47,7 @@ pub use import::{ AiLayers, Imported, POSTSCRIPT_ERRORS, ai_alone, ai_alone_on_page, ai_layers_alone, family_style, import, import_trusting, import_with, is_loss, layered_ai, layered_ai_from, page, }; -pub use legacy_ai::{HiddenObjects, LegacyAiOptions, LegacyAiOutput, export_legacy_ai}; +pub use legacy_ai::{HiddenObjects, LegacyAiOptions, LegacyAiOutput, export_legacy_ai, writes_image_mask}; pub use print::{PrintJob, PrintPage, print}; use vectorcraft_doc::Document; diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 4186db3eb7..4791a586e5 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (SVG import: `color-interpolation="linearRGB"` gradients, #5878) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`, `OPEN_EXTS`, `PLACE_EXTS` in `crates/engine/src/cmd/fileio/formats.rs`). Illustrator's list comes from its public @@ -82,7 +82,9 @@ private editing data. VectorCraft: PostScript form, from the published *Adobe Illustrator File Format Specification* version 7.0 ([PRONOM fmt/423](https://www.nationalarchives.gov.uk/PRONOM/fmt/423)), which apps reading `.ai` open with its structure (#868). It keeps layers (names, order, visibility, lock), groups, compound paths, clipping groups, - solid colours, linear and radial gradients and RGB images. The format has one artboard: each artboard chosen in + solid colours, linear and radial gradients and RGB images. A colorized image whose pixels are all black or white + is written as a 1-bit image mask (ImageMask 1) in its color, with its white pixels clear, and opens colorized + again; other colorized images are flattened or omitted as the Transparent Images setting below says. The format has one artboard: each artboard chosen in the options dialog's artboard picker (thumbnails to check, default all) is a file of its own, `{name}-{artboard}.ai` when there are several. It has no transparency: objects are written opaque, and images with see-through pixels, opacity or a blending mode are flattened (an opaque image of themselves and the art diff --git a/docs/mcp.md b/docs/mcp.md index c70283b703..de4a76d6f2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -879,7 +879,9 @@ document, takes the PDF options and keeps its path when reopened, so Save writes without giving the document a path. `options: {aiVersion: "7"}` writes legacy `.ai` files of version 7 instead (the PostScript form, which keeps layers, groups, compound paths and clipping groups in apps that read it), one per artboard of `range` (default all; `{name}-{artboard}.ai` when several, listed in the result's `files`), with -`transparentImages: "flatten"` (default) or `"omit"` for images with see-through pixels, opacity or a blending mode, +`transparentImages: "flatten"` (default) or `"omit"` for images with see-through pixels, opacity, a blending mode +or a colorize color (except a colorized image of black and white pixels, which is written as a 1-bit image mask in +its color with its white pixels clear), `hiddenObjects: "layer"` (default: a hidden layer of each layer's hidden objects), `"omit"` or `"visible"`, and `outlineText: true` to write type as outlines instead of text objects. Type with rotated characters (Character Rotation) is always written as outlines, which keep the rotation; without `outlineText: true` this gives the warning "type with rotated characters is From dbbe8a9298fdc3da6e520a6a58dddd5880b2b880 Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Fri, 6 Nov 2026 03:36:48 -0500 Subject: [PATCH 189/196] PDF and .ai export: objects' URLs become clickable links (#5785) Each visible object with a URL (Attributes panel) is written as a Link annotation with a URI action over its bounds on the page, trimmed to its clipping groups. Hidden objects, non-printing layers and printed sheets get none; PDF/X files leave them out with a warning. URIs are percent-encoded to 7-bit ASCII. --- crates/engine/src/cmd/attributes.rs | 2 +- crates/pdf/src/export.rs | 1 + crates/pdf/src/export/entry.rs | 11 +++ crates/pdf/src/export/links.rs | 121 ++++++++++++++++++++++++++++ crates/pdf/src/export/writer.rs | 11 +++ crates/pdf/src/print.rs | 2 + crates/pdf/src/tests.rs | 1 + crates/pdf/src/tests/links.rs | 119 +++++++++++++++++++++++++++ docs/file-format-parity.md | 5 +- 9 files changed, 270 insertions(+), 3 deletions(-) create mode 100644 crates/pdf/src/export/links.rs create mode 100644 crates/pdf/src/tests/links.rs diff --git a/crates/engine/src/cmd/attributes.rs b/crates/engine/src/cmd/attributes.rs index 0265b4ccd4..684d33a53d 100644 --- a/crates/engine/src/cmd/attributes.rs +++ b/crates/engine/src/cmd/attributes.rs @@ -22,7 +22,7 @@ pub fn specs() -> Vec { "Attributes", [], None, - "{overprintFill?: bool, overprintStroke?: bool (aimed as object.setOverprint's fill and stroke, item? too), showCenter?: bool (the canvas shows the selected object's centre point), imageMap?: \"none\"|\"rectangle\"|\"polygon\", url?: string (\"\" removes it; SVG export links the object), note?: string, ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} set the Attributes panel's values on ids or the selection, as one undo step; a URL given joins the recent URLs (attributes.info) → {changed: objects}", + "{overprintFill?: bool, overprintStroke?: bool (aimed as object.setOverprint's fill and stroke, item? too), showCenter?: bool (the canvas shows the selected object's centre point), imageMap?: \"none\"|\"rectangle\"|\"polygon\", url?: string (\"\" removes it; SVG, PDF and .ai export link the object), note?: string, ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} set the Attributes panel's values on ids or the selection, as one undo step; a URL given joins the recent URLs (attributes.info) → {changed: objects}", has_doc, set ), diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs index 71c9ab25de..cfb3d93441 100644 --- a/crates/pdf/src/export.rs +++ b/crates/pdf/src/export.rs @@ -33,6 +33,7 @@ use crate::{Compatibility, ExportReport, PdfError, PdfOptions, Standard}; mod entry; mod exporter; mod images; +mod links; mod nodes; mod paint; mod text; diff --git a/crates/pdf/src/export/entry.rs b/crates/pdf/src/export/entry.rs index 6a4294c699..92607d5c51 100644 --- a/crates/pdf/src/export/entry.rs +++ b/crates/pdf/src/export/entry.rs @@ -79,6 +79,16 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha // In PDF 1.6 and later files that aren't PDF/X files, a page with a side longer than // [`MAX_PAGE_SIDE`] is written in larger units; other files have every page in points. let scales = set.compatibility.has_user_unit() && !set.standard.is_pdfx(); + // PDF/X files have no annotations over the art (ISO 15930: only printer's mark and trap + // network annotations, outside the bleed box): objects' URLs aren't written as links there. + let links = !set.standard.is_pdfx(); + let mut linked = false; + for layer in doc.layers.iter().filter(|_| !links) { + layer.walk(&mut |n| linked |= n.url().is_some()); + } + if linked { + warnings.push(format!("{} files have no links: the objects' URLs aren't clickable", set.standard.label())); + } let mut units = Vec::with_capacity(pages.len()); let total = pages.len() as u64; for (written, (i, boxes)) in pages.into_iter().enumerate() { @@ -107,6 +117,7 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha clip: m != r, marks: art.as_ref(), negative: false, + links, }; w.page(&mut ex, &sheet).map_err(|_| PdfError::BadArtboard(i))?; } diff --git a/crates/pdf/src/export/links.rs b/crates/pdf/src/export/links.rs new file mode 100644 index 0000000000..5eec2fd837 --- /dev/null +++ b/crates/pdf/src/export/links.rs @@ -0,0 +1,121 @@ +//! The objects' URLs (Window › Attributes) as link annotations: a rectangle over each linked +//! object's bounds on the page that opens its URL (ISO 32000-1 §12.5.6.5 Link Annotations, with a +//! URI action, §12.6.4.7). + +use super::{Affine, Exporter, Node, NodeKind, Rect, krilla}; + +/// Most links written on one page: the rest are left out with a warning. +pub(super) const MAX_LINKS: usize = 10_000; + +/// The warning for the links left out past [`MAX_LINKS`]. +pub(super) const TOO_MANY_LINKS: &str = "a page has more linked objects than a PDF page keeps links for: the rest aren't clickable"; + +/// Does a link open `uri`? Web and mail URLs only, the ones the app's Browser button opens: a URL +/// can come from an imported file, and a `javascript:` or `file:` one has no place in a PDF. +fn opens(uri: &str) -> bool { + let scheme = uri.trim().split_once(':').map_or("", |(s, _)| s); + ["http", "https", "mailto"].iter().any(|k| scheme.eq_ignore_ascii_case(k)) +} + +/// A link to write: the URI it opens, and the area it covers in page space (y down). +pub(super) struct Link { + pub uri: String, + pub rect: Rect, +} + +impl Exporter<'_> { + /// The links of the art drawn on a page: each linked object that shows (on a layer that + /// prints, or any layer when non-printing layers are written; not on a template layer), over + /// its bounds within the clipping groups it is in and within `area` (document space, the art + /// drawn), mapped onto the page by `to_page`. A group's link comes before its objects', so an + /// object's own link lies over it. The second value: links were left out past [`MAX_LINKS`]. + pub(super) fn links(&self, area: Rect, to_page: Affine) -> (Vec, bool) { + let mut links = vec![]; + let mut more = false; + for layer in &self.doc.layers { + self.link_node(layer, area, to_page, &mut links, &mut more); + } + (links, more) + } + + fn link_node(&self, n: &Node, within: Rect, to_page: Affine, links: &mut Vec, more: &mut bool) { + if !n.visible || matches!(n.kind, NodeKind::Path { guide: true, .. }) { + return; + } + if let NodeKind::Layer { template, printable, .. } = n.kind + && (template || !(printable || self.non_printing)) + { + return; + } + let bounds = n.visual_bounds_with(&self.symbols).filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())); + if let (Some(uri), Some(b)) = (n.url().filter(|u| opens(u)), bounds) { + let shown = b.intersect(within); + if shown.width() > 0.0 && shown.height() > 0.0 { + let rect = to_page.transform_rect_bbox(shown); + if [rect.x0, rect.y0, rect.x1, rect.y1].iter().any(|v| !v.is_finite()) { + // Off any page a reader can show: no link. + } else if links.len() < MAX_LINKS { + links.push(Link { uri: uri_bytes(uri), rect }); + } else { + *more = true; + } + } + } + // What a clipping group holds shows only inside its clipping path's bounds. + let within = match bounds { + Some(b) if n.clips() => b.intersect(within), + None if n.clips() => return, + _ => within, + }; + if within.width() <= 0.0 || within.height() <= 0.0 { + return; + } + for child in n.children().into_iter().flatten() { + self.link_node(child, within, to_page, links, more); + } + } +} + +/// `uri` as a PDF URI (ISO 32000-1 §12.6.4.7: 7-bit ASCII): spaces, control characters and +/// non-ASCII bytes percent-encoded (RFC 3986 §2.1), leading and trailing spaces dropped. +fn uri_bytes(uri: &str) -> String { + let mut out = String::with_capacity(uri.len()); + for b in uri.trim().bytes() { + if b.is_ascii_graphic() { + out.push(char::from(b)); + } else { + out.push_str(&format!("%{b:02X}")); + } + } + out +} + +/// The annotation of `link`: a borderless rectangle that opens its URI. +pub(super) fn annotation(link: Link) -> Option { + let r = link.rect; + let rect = krilla::geom::Rect::from_ltrb(r.x0 as f32, r.y0 as f32, r.x1 as f32, r.y1 as f32)?; + let target = krilla::annotation::Target::Action(krilla::action::LinkAction::new(link.uri.clone()).into()); + Some(krilla::annotation::Annotation::new_link(krilla::annotation::LinkAnnotation::new(rect, target), Some(link.uri))) +} + +#[cfg(test)] +mod tests { + use super::{opens, uri_bytes}; + + #[test] + fn only_web_and_mail_urls_become_links() { + for ok in ["https://example.com/a", "HTTP://example.com", "mailto:someone@example.com", " https://example.com "] { + assert!(opens(ok), "{ok}"); + } + for refused in ["javascript:alert(1)", "file:///etc/passwd", "smb://host/share", "ms-settings:", "example.com", ""] { + assert!(!opens(refused), "{refused}"); + } + } + + #[test] + fn uris_are_written_in_ascii() { + assert_eq!(uri_bytes(" https://example.com/a b "), "https://example.com/a%20b"); + assert_eq!(uri_bytes("https://example.com/café"), "https://example.com/caf%C3%A9"); + assert_eq!(uri_bytes("mailto:a@b.c?subject=x\ny"), "mailto:a@b.c?subject=x%0Ay"); + } +} diff --git a/crates/pdf/src/export/writer.rs b/crates/pdf/src/export/writer.rs index 5e7c7e77ab..7f9b939f92 100644 --- a/crates/pdf/src/export/writer.rs +++ b/crates/pdf/src/export/writer.rs @@ -51,6 +51,8 @@ pub(crate) struct Sheet<'a> { pub marks: Option<&'a Node>, /// Invert the page: paper black, ink clear (a film negative). pub negative: bool, + /// The objects' URLs are written as links over them ([`super::links`]). + pub links: bool, } impl Writer { @@ -190,6 +192,15 @@ impl Writer { s.pop(); } s.finish(); + if fits && sheet.links { + let (links, more) = ex.links(r, sheet.view * sheet.place); + for annotation in links.into_iter().filter_map(super::links::annotation) { + page.add_annotation(annotation); + } + if more { + ex.warn(super::links::TOO_MANY_LINKS); + } + } page.finish(); Ok(()) } diff --git a/crates/pdf/src/print.rs b/crates/pdf/src/print.rs index a8e54b3248..559fc61475 100644 --- a/crates/pdf/src/print.rs +++ b/crates/pdf/src/print.rs @@ -338,6 +338,8 @@ impl PlannedSheet { clip: true, marks: self.marks.as_ref(), negative: self.negative, + // A printed sheet has no links to click. + links: false, } } } diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 132b338e76..f8df385009 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -27,6 +27,7 @@ mod import_lines; mod import_options; mod import_overprint; mod layers; +mod links; pub(super) mod live_text; mod marks; mod mesh_export; diff --git a/crates/pdf/src/tests/links.rs b/crates/pdf/src/tests/links.rs new file mode 100644 index 0000000000..c23854439f --- /dev/null +++ b/crates/pdf/src/tests/links.rs @@ -0,0 +1,119 @@ +//! Objects with a URL (Window › Attributes) export as link annotations over their bounds that +//! open it; hidden ones and PDF/X files have none. + +use std::sync::Arc; + +use craft_pdf::syntax::Pdf; +use craft_pdf::syntax::object::{Array, Dict, Name}; +use vectorcraft_color::Color; +use vectorcraft_doc::{Document, Node, NodeId}; +use vectorcraft_geom::{Rect, shapes}; + +use super::{add, doc, rect_node}; +use crate::*; + +/// A rectangle over `r` linking to `url`. +fn linked(r: Rect, url: &str) -> Node { + let mut n = rect_node(r, Color::rgb(1.0, 0.0, 0.0)); + n.edit_attrs(|a| a.url = url.into()); + n +} + +/// Each link annotation of each page: its URI and its rectangle (PDF space, y up). +fn links(pdf: &[u8]) -> Vec> { + let file = Pdf::new(Arc::new(pdf.to_vec())).unwrap(); + file.pages() + .iter() + .map(|page| { + let Some(annots) = page.raw().get::>(b"Annots") else { return vec![] }; + annots + .iter::>() + .filter(|a| a.get::>(b"Subtype").is_some_and(|s| s.as_ref() == b"Link")) + .map(|a| { + let action = a.get::>(b"A").unwrap(); + assert_eq!(action.get::>(b"S").unwrap().as_ref(), b"URI"); + let uri = action.get::>(b"URI").unwrap().as_bytes().to_vec(); + let r: Vec = a.get::>(b"Rect").unwrap().iter::().collect(); + (String::from_utf8(uri).unwrap(), [r[0], r[1], r[2], r[3]]) + }) + .collect() + }) + .collect() +} + +fn near(a: [f32; 4], b: [f32; 4]) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.01) +} + +#[test] +fn a_linked_object_exports_a_link_over_its_bounds() { + let mut d = doc(200.0, 100.0); + add(&mut d, rect_node(Rect::new(0.0, 0.0, 5.0, 5.0), Color::rgb(0.0, 0.0, 1.0))); + add(&mut d, linked(Rect::new(10.0, 10.0, 50.0, 30.0), "https://example.com/a b")); + for bytes in [export(&d, &PdfOptions::default()).unwrap(), export(&d, &PdfOptions::uncompressed()).unwrap()] { + let pages = links(&bytes); + assert_eq!(pages.len(), 1); + let [(uri, rect)] = pages[0].as_slice() else { panic!("one link: {pages:?}") }; + // In ASCII, as a PDF URI is (the space percent-encoded). + assert_eq!(uri, "https://example.com/a%20b"); + // y up from the page's bottom edge: 100 − 30 to 100 − 10. + assert!(near(*rect, [10.0, 70.0, 50.0, 90.0]), "{rect:?}"); + } +} + +#[test] +fn hidden_and_unprinted_objects_have_no_links_and_clipping_trims_them() { + let mut d = doc(200.0, 100.0); + let mut hidden = linked(Rect::new(10.0, 10.0, 50.0, 30.0), "https://example.com/hidden"); + hidden.visible = false; + add(&mut d, hidden); + // Clipped to x 20…40: the link covers only what shows. + let clip = Node::path(NodeId(0), shapes::rectangle(Rect::new(20.0, 0.0, 40.0, 100.0)), Default::default()); + let mut group = Node::group(NodeId(0), vec![Arc::new(clip), Arc::new(linked(Rect::new(0.0, 40.0, 200.0, 60.0), "https://example.com/clipped"))]); + group.set_clips(true); + let group = d.reid(&group); + add(&mut d, group); + // Off the artboard: nothing to click. + add(&mut d, linked(Rect::new(300.0, 10.0, 350.0, 30.0), "https://example.com/off")); + let pages = links(&export(&d, &PdfOptions::default()).unwrap()); + let [(uri, rect)] = pages[0].as_slice() else { panic!("one link: {pages:?}") }; + assert_eq!(uri, "https://example.com/clipped"); + assert!(near(*rect, [20.0, 40.0, 40.0, 60.0]), "{rect:?}"); + + // A layer that doesn't print leaves its links out with its art. + let mut d = doc(200.0, 100.0); + add(&mut d, linked(Rect::new(10.0, 10.0, 50.0, 30.0), "https://example.com/")); + if let vectorcraft_doc::NodeKind::Layer { printable, .. } = &mut Arc::make_mut(&mut d.layers[0]).kind { + *printable = false; + } + assert_eq!(links(&export(&d, &PdfOptions::default()).unwrap()), vec![Vec::<(String, [f32; 4])>::new()]); +} + +#[test] +fn each_page_links_its_own_artboard_objects() { + let mut d = doc(200.0, 100.0); + let mut second = d.artboards[0].clone(); + second.id = 2; + second.rect = Rect::new(300.0, 0.0, 400.0, 100.0); + d.artboards.push(second); + add(&mut d, linked(Rect::new(310.0, 20.0, 330.0, 40.0), "mailto:a@example.com")); + let pages = links(&export(&d, &PdfOptions::default()).unwrap()); + assert_eq!(pages[0], vec![]); + let [(uri, rect)] = pages[1].as_slice() else { panic!("one link: {pages:?}") }; + assert_eq!(uri, "mailto:a@example.com"); + assert!(near(*rect, [10.0, 60.0, 30.0, 80.0]), "{rect:?}"); +} + +#[test] +fn pdfx_files_have_no_links() { + let mut d: Document = doc(200.0, 100.0); + add(&mut d, linked(Rect::new(10.0, 10.0, 50.0, 30.0), "https://example.com/")); + let mut o = PdfOptions::default(); + (o.settings.standard, o.settings.compatibility) = (Standard::PdfX4, Standard::PdfX4.version()); + o.created = Some(1_700_000_000); + let report = export_with_report(&d, &o).unwrap(); + assert_eq!(links(&report.bytes), vec![Vec::<(String, [f32; 4])>::new()]); + assert!(report.warnings.iter().any(|w| w.contains("URLs aren't clickable")), "{:?}", report.warnings); + // Without links, no such warning. + assert!(!export_with_report(&doc(200.0, 100.0), &o).unwrap().warnings.iter().any(|w| w.contains("URLs"))); +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 4791a586e5..a3e1aca39d 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`, `OPEN_EXTS`, `PLACE_EXTS` in `crates/engine/src/cmd/fileio/formats.rs`). Illustrator's list comes from its public @@ -152,7 +152,7 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri | VectorCraft `.vectorcraft` / `.vctemplate` | — | yes | yes | lossless JSON, versioned, save down to v1; property-tested round trips (`format/tests/prop_format.rs`); documents with a lot of path data are written as compact JSON, about a fifth of the size (#1492); a save falls back to a plain fsync and to writing elsewhere and copying in when the folder refuses the usual steps (#1625, #1649, part of #1620; not confirmed on a real network share); the size limits on embedded data also apply to files read from memory (#1783), and saving over a private file on Unix leaves no readable temporary copy beside it (#1778); a dynamic symbol's type (`dynamic` on the symbol) and an instance's appearance changes to its art (`symbol_overrides`, each path at most 64 deep, counted against the object budget) are written only when set, so documents without them save as before (#4938) | | Illustrator template `.ait` | open, save | yes | PDF-compatible only, from Save as Template (`.vctemplate` stays its default) | New from Template opens a saved `.ait` untitled with its layers and art (`tests_pdfedit.rs`) | | Illustrator `.ai` | open, save | yes (PDF-compatible + editing-data structure with template layers and ruler guides, File Info) | PDF-compatible, or legacy version 7 (layers and groups) | see above; no real-file corpus | -| PDF | open, place, save | yes (layers, masks, editable text, security, overprint, File Info from the XMP packet and the document information dictionary; Crop To › Trim takes the bleed box as the document's bleed) | yes (presets, PDF/X-1a/3/4, layers, marks and bleed, ICC, fast web view, 1.3+) | fuzzed import; shared guarded writer and windowed reader ([pdf-backend.md](pdf-backend.md)), metadata, incomplete-content and dependency-source regressions; PDF text opens where the file draws it, glyph by glyph (#722: kerning or none, spacing per character, text rise as baseline shift, vertical writing, justified text boxes); alpha soft masks drawn as images import with the mask (#1551); a clip only counts as covering the page when its shape does (#1542); a PDF another app copied pastes as editable vector art (#1499); letter-spaced type on a path keeps its length and its glyph-by-glyph stroke comes in as one text object (#1586, #1585); a crafted name tree with shared nodes no longer takes exponential time on open (#1781); fonts named with hyphens (`Noto-Sans-Bold`) or with a composite font's CMap (`Name-Identity-H`) find the installed family; invisible text (rendering mode 3: a scanned page's recognized text) opens as type with no fill or stroke and saves back as invisible, searchable text (#2675); PDF/X-1a and X-3 flattening in a CMYK document keeps CMYK inks where it rasterizes (#2160) | +| PDF | open, place, save | yes (layers, masks, editable text, security, overprint, File Info from the XMP packet and the document information dictionary; Crop To › Trim takes the bleed box as the document's bleed) | yes (presets, PDF/X-1a/3/4, layers, marks and bleed, ICC, fast web view, 1.3+; objects' URLs as link annotations, not in PDF/X) | fuzzed import; shared guarded writer and windowed reader ([pdf-backend.md](pdf-backend.md)), metadata, incomplete-content and dependency-source regressions; PDF text opens where the file draws it, glyph by glyph (#722: kerning or none, spacing per character, text rise as baseline shift, vertical writing, justified text boxes); alpha soft masks drawn as images import with the mask (#1551); a clip only counts as covering the page when its shape does (#1542); a PDF another app copied pastes as editable vector art (#1499); letter-spaced type on a path keeps its length and its glyph-by-glyph stroke comes in as one text object (#1586, #1585); a crafted name tree with shared nodes no longer takes exponential time on open (#1781); fonts named with hyphens (`Noto-Sans-Bold`) or with a composite font's CMap (`Name-Identity-H`) find the installed family; invisible text (rendering mode 3: a scanned page's recognized text) opens as type with no fill or stroke and saves back as invisible, searchable text (#2675); PDF/X-1a and X-3 flattening in a CMYK document keeps CMYK inks where it rasterizes (#2160) | | EPS | open, place, save | yes (own PostScript L3 interpreter, Illustrator EPS editing data structure) | yes (L2/L3, TIFF previews) | CID-keyed CJK type not read; #505; images encoded with `CCITTFaxDecode` (ITU-T T.4 Group 3 and T.6 Group 4, with `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1`) draw, and damaged data keeps the rows decoded before its first damaged row; Type 42 (TrueType) fonts set type at its size (#1553); a clip only counts as covering the page when its shape does (#1542); an EPS another app copied pastes as editable vector art (`clipboard.importEps`, #1499); a stitched shading keeps its hard colour changes on import (#1654); CMYK images, CMYK JPEGs included, keep their ink amounts on import, as from PDF, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask; ruzstd 0.9.1 for compressed editing data (#1807, RUSTSEC-2026-0344) | | PostScript `.ps` | open, place | yes (the EPS reader reads its first page; `.epsf` files open and place as EPS) | via Print to PostScript | `tests_epsimport.rs` | | SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598); an artboard exported on its own (Export As with Use Artboards, Export for Screens, Asset Export) has the artboard's name as ``, Save the document's (#3544); attributes in other applications' XML namespaces (`plotter:pen="2"`) kept on their objects from import to export, as `data-*` attributes are (`crates/svg/tests/it/foreign_attributes.rs`); simple shapes export as `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>` and `<polyline>` where they draw the same as the path (#4652, `crates/svg/tests/it/basic_shapes.rs`) | @@ -191,6 +191,7 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri | Date | Change | Summary | |---|---|---| +| 2026-11-06 | minor | PDF export and PDF-compatible `.ai` saves write each object's URL (Attributes panel) as a link annotation with a URI action (web and mail URLs only) over the bounds of the object that shows, trimmed by its clipping groups (ISO 32000-1, 12.5.6.5 and 12.6.4.7); hidden objects, layers that don't print and prints have none, and PDF/X files leave them out with a warning (#5785). Own-fixture tests in `tests::links`; PDF import doesn't read links back as URLs yet; scores unchanged | | 2026-11-06 | minor | SVG import: a gradient with `color-interpolation="linearRGB"` (on it, inherited, or from a style sheet) mixes its stops in linear light, as SVG 1.1 §11.7.1 asks: the document gradient gets extra stops wherever display-RGB mixing would stray by half a colour level or more, so black to white is about 188/255 mid-way instead of 128 (#5878). A gradient several objects share is mixed so on every one. Opacity still mixes evenly; at most 4096 stops per gradient. Tests `import::linear_rgb`, `gradients::linear_rgb_*` (crate `vectorcraft-svg`); scores unchanged | | 2026-11-05 | minor | `.ai` import (#372): a path with a Calligraphic brush comes in as the path with the brush on its stroke (its weight scales the brush) when its art style's brush settings are the brush's own and its angle is on the page, else as its drawn look; a Calligraphic brush's Tilt, Bearing and Rotation codes come in as those channels instead of Random. Checked against a user's file of 6D Art Pen strokes (used locally, not committed); synthetic tests in `import::ai::tests` | | 2026-11-05 | minor | PDF import: the stops of an axial or radial shading in a DeviceN space of one spot ink and process plates link to the ink's swatch and keep the plates (`GradientStop.plates` in the native format); PDF and EPS export write them in a DeviceN space again (#3235) | From 41ceaadc7e5149c7b766981f91d3b4aeab85a31a Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Fri, 6 Nov 2026 04:01:37 -0500 Subject: [PATCH 190/196] SVG import: Gaussian blurs keep color-interpolation-filters; Gaussian Blur can blur in linear light (#5877) --- crates/effects/src/catalog.rs | 8 +++++- crates/effects/src/pixel.rs | 41 +++++++++++++++++++++++++++++ crates/effects/src/pixel/tests.rs | 22 ++++++++++++++++ crates/effects/src/raster.rs | 8 +++--- crates/engine/src/tests/params.rs | 2 +- crates/render/src/fx/pixels.rs | 5 +++- crates/render/src/fx/raster.rs | 2 +- crates/render/src/fx/renderer.rs | 2 +- crates/svg/src/css.rs | 2 +- crates/svg/src/export/paint.rs | 5 +++- crates/svg/src/import/fx.rs | 4 ++- crates/svg/tests/it/import_live.rs | 42 ++++++++++++++++++++++++++++-- docs/file-format-parity.md | 3 ++- 13 files changed, 132 insertions(+), 14 deletions(-) diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index d1560ec7ca..8440639328 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -307,7 +307,13 @@ pub fn effect_catalog() -> Vec<EffectInfo> { json!({"mode": "screen", "opacity": 75.0, "blur": 5.0, "color": "#ffff00"}), ), r("stylize.feather", "Feather…", STYLIZE, "{radius: pt (5)}", json!({"radius": 5.0})), - r("blur.gaussian", "Gaussian Blur…", BLUR, "{radius: pt (5)}", json!({"radius": 5.0})), + r( + "blur.gaussian", + "Gaussian Blur…", + BLUR, + "{radius: pt (5), linear?: bool (false; blurs the colours in linear light, as an SVG filter with color-interpolation-filters=\"linearRGB\" does)}", + json!({"radius": 5.0}), + ), r( "artistic.coloredPencil", "Colored Pencil…", diff --git a/crates/effects/src/pixel.rs b/crates/effects/src/pixel.rs index 2a122bb664..6be45756b4 100644 --- a/crates/effects/src/pixel.rs +++ b/crates/effects/src/pixel.rs @@ -1079,6 +1079,47 @@ pub fn gaussian_rgba(data: &mut [u8], w: usize, h: usize, sigma: f64) { } } +/// [`gaussian_rgba`] with the colours mixed in linear light: decoded from sRGB before the blur +/// and encoded again after it (Filter Effects 1 §16, `color-interpolation-filters: linearRGB`, +/// <https://www.w3.org/TR/filter-effects-1/#ColorInterpolationFiltersProperty>). The blur runs on +/// 16-bit values, so dark linear tones keep their steps. +pub fn gaussian_rgba_linear(data: &mut [u8], w: usize, h: usize, sigma: f64) { + use vectorcraft_doc::color::cms::lab::{linear_to_srgb, srgb_to_linear}; + if let Some(px) = pixels(data, w, h) + && sigma >= 0.2 + { + // Each colour is unpremultiplied, decoded (by table) and premultiplied again. + let decode: Vec<f32> = (0..=255u8).map(|v| srgb_to_linear(f32::from(v) / 255.0)).collect(); + let mut wide: Vec<Px16> = px + .iter() + .map(|p| { + let a = f32::from(p[3]) / 255.0; + let lin = |v: u8| { + if p[3] == 0 { + return 0; + } + let straight = (f32::from(v) / f32::from(p[3]) * 255.0).round().clamp(0.0, 255.0) as usize; + (decode.get(straight).copied().unwrap_or(0.0) * a * 65535.0).round().clamp(0.0, 65535.0) as u16 + }; + [lin(p[0]), lin(p[1]), lin(p[2]), u16::from(p[3]) * 257] + }) + .collect(); + gaussian(&mut wide, w, sigma); + for (p, q) in px.iter_mut().zip(&wide) { + let a = to8(q[3]); + let alpha = f32::from(q[3]) / 65535.0; + let enc = |v: u16| { + if alpha <= 0.0 { + return 0; + } + let straight = (f32::from(v) / 65535.0 / alpha).clamp(0.0, 1.0); + (linear_to_srgb(straight) * f32::from(a)).round().clamp(0.0, f32::from(a)) as u8 + }; + *p = [enc(q[0]), enc(q[1]), enc(q[2]), a]; + } + } +} + #[cfg(test)] mod tests; #[cfg(test)] diff --git a/crates/effects/src/pixel/tests.rs b/crates/effects/src/pixel/tests.rs index 8261d408a1..a1a083f0fe 100644 --- a/crates/effects/src/pixel/tests.rs +++ b/crates/effects/src/pixel/tests.rs @@ -887,6 +887,28 @@ fn gaussian_and_plane_blurs_keep_their_mass() { assert!((plane.iter().sum::<f32>() - 100.0).abs() < 0.5 && plane[15 * w + 13] > 0.0 && plane[13 * w + 15] > 0.0); } +/// Blurred in linear light, black beside white meets at about 188/255 (half the light, encoded), +/// where the plain blur meets at about 128; flat areas and alpha stay as they are (#5877). +#[test] +fn linear_light_blur_mixes_light_not_values() { + // Large enough that the transparency past the edges doesn't reach the middle. + let (w, h) = (120, 60); + let src = image(w, h, |x, _| if x < 60 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }); + let (mut plain, mut linear) = (src.clone(), src.clone()); + gaussian_rgba(&mut plain, w, h, 3.0); + gaussian_rgba_linear(&mut linear, w, h, 3.0); + let mid = |d: &[u8]| (f32::from(at(d, w, 59, 30)[0]) + f32::from(at(d, w, 60, 30)[0])) / 2.0; + assert!((mid(&plain) - 128.0).abs() < 6.0, "{}", mid(&plain)); + assert!((mid(&linear) - 188.0).abs() < 6.0, "{}", mid(&linear)); + assert_eq!((at(&linear, w, 30, 30), at(&linear, w, 90, 30)), ([0, 0, 0, 255], [255, 255, 255, 255])); + // Premultiplied input: a half-transparent white square blurs to white at any alpha. + let mut soft = image(30, 30, |x, y| if (10..20).contains(&x) && (10..20).contains(&y) { [128, 128, 128, 128] } else { [0, 0, 0, 0] }); + gaussian_rgba_linear(&mut soft, 30, 30, 2.0); + for p in soft.as_chunks::<4>().0 { + assert!(p[0] <= p[3] && p[3] <= 128 && (p[3] < 8 || p[0] + 2 >= p[3]), "{p:?}"); + } +} + /// Timings on a 2000 × 2000 raster (`cargo test -p vectorcraft-effects --release -- --ignored /// --nocapture pixel_timings`). #[test] diff --git a/crates/effects/src/raster.rs b/crates/effects/src/raster.rs index a1d8df2d61..cfa51ca2b0 100644 --- a/crates/effects/src/raster.rs +++ b/crates/effects/src/raster.rs @@ -48,9 +48,11 @@ pub enum RasterFx { Feather { radius: f64, }, - /// Blur the whole object (σ = radius / 2). + /// Blur the whole object (σ = radius / 2): its colours mixed as they are, or in linear light + /// (`linear`, as an SVG filter asks with `color-interpolation-filters="linearRGB"`). GaussianBlur { radius: f64, + linear: bool, }, /// A Photoshop-style filter over the object's pixels (Radial Blur, Unsharp Mask…). Pixel(PixelFx), @@ -77,7 +79,7 @@ impl RasterFx { RasterFx::DropShadow { dx, dy, blur, .. } => dx.abs().max(dy.abs()) + 1.5 * blur, RasterFx::OuterGlow { blur, .. } => 1.5 * blur, RasterFx::InnerGlow { .. } | RasterFx::Feather { .. } => 0.0, - RasterFx::GaussianBlur { radius } => 1.5 * radius, + RasterFx::GaussianBlur { radius, .. } => 1.5 * radius, RasterFx::Pixel(p) => p.outset(bounds), RasterFx::Rasterize(r) => r.outset(), } @@ -416,7 +418,7 @@ pub fn raster_effects(effects: &[Effect]) -> Vec<RasterFx> { center: text(&p, "source", "edge").eq_ignore_ascii_case("center"), }, "stylize.feather" => RasterFx::Feather { radius: num(&p, "radius", 5.0).clamp(0.0, 1000.0) }, - "blur.gaussian" => RasterFx::GaussianBlur { radius: num(&p, "radius", 5.0).clamp(0.0, 1000.0) }, + "blur.gaussian" => RasterFx::GaussianBlur { radius: num(&p, "radius", 5.0).clamp(0.0, 1000.0), linear: flag(&p, "linear", false) }, RASTERIZE => RasterFx::Rasterize(Rasterize::parse(&p)), id => RasterFx::Pixel(pixel::parse(id, &p)?), }) diff --git a/crates/engine/src/tests/params.rs b/crates/engine/src/tests/params.rs index e989597ae5..2eba6c81ae 100644 --- a/crates/engine/src/tests/params.rs +++ b/crates/engine/src/tests/params.rs @@ -126,7 +126,7 @@ fn effect_params_are_the_effects_own() { check_effect_params("effect.apply", e.id, &e.defaults).unwrap_or_else(|why| panic!("{}'s defaults: {why}", e.id)); } let apply = |effect: &str, params| json!({"effect": effect, "params": params}); - assert_eq!(refusal("effect.apply", apply("blur.gaussian", json!({"blurr": 3}))), "unknown parameter `blurr`; the command takes: radius"); + assert_eq!(refusal("effect.apply", apply("blur.gaussian", json!({"blurr": 3}))), "unknown parameter `blurr`; the command takes: radius, linear"); assert_eq!( refusal("appearance.addEffect", apply("stylize.dropShadow", json!({"opacty": 50}))), "unknown parameter `opacty`; did you mean `opacity`?" diff --git a/crates/render/src/fx/pixels.rs b/crates/render/src/fx/pixels.rs index 8159673cae..3f13d1b3e3 100644 --- a/crates/render/src/fx/pixels.rs +++ b/crates/render/src/fx/pixels.rs @@ -236,7 +236,10 @@ impl Renderer { bounds = fx.spread(before, space.line); let outline = image_outline.as_ref().map(|g| (g, FillRule::NonZero)).or(content.outline); match fx { - RasterFx::GaussianBlur { radius } => effects::pixel::gaussian_rgba(pm.data_as_u8_slice_mut(), wz, hz, radius / 2.0 / px), + RasterFx::GaussianBlur { radius, linear } => { + let blur = if *linear { effects::pixel::gaussian_rgba_linear } else { effects::pixel::gaussian_rgba }; + blur(pm.data_as_u8_slice_mut(), wz, hz, radius / 2.0 / px) + } RasterFx::Feather { radius } => { effects::pixel::gaussian_rgba(pm.data_as_u8_slice_mut(), wz, hz, radius / 2.0 / px); if let Some((g, rule)) = outline { diff --git a/crates/render/src/fx/raster.rs b/crates/render/src/fx/raster.rs index 23f080daf4..5fa9b107ed 100644 --- a/crates/render/src/fx/raster.rs +++ b/crates/render/src/fx/raster.rs @@ -74,7 +74,7 @@ pub(super) fn hard_edged(chain: &[&RasterFx], px: f64) -> bool { /// document's raster grid lines `line` apart; `None` when anywhere in the object. pub(super) fn looks_around(fx: &RasterFx, line: f64) -> Option<f64> { match fx { - RasterFx::Feather { radius } | RasterFx::GaussianBlur { radius } => Some(1.5 * radius), + RasterFx::Feather { radius } | RasterFx::GaussianBlur { radius, .. } => Some(1.5 * radius), RasterFx::Pixel(p) => p.reach(line), RasterFx::Rasterize(r) => Some(r.reach()), _ => Some(0.0), diff --git a/crates/render/src/fx/renderer.rs b/crates/render/src/fx/renderer.rs index fae143a239..fd8d68a98d 100644 --- a/crates/render/src/fx/renderer.rs +++ b/crates/render/src/fx/renderer.rs @@ -691,7 +691,7 @@ impl Renderer { // The content itself (blurred / feathered / filtered), on its pixels: a filter layer's blur // works on a coarser grid tied to the canvas, so the blurred art shifted by up to a pixel // and looked blocky as the view moved by parts of a pixel (#755). - let blurs = rfx.iter().any(|fx| matches!(fx, RasterFx::Feather { radius } | RasterFx::GaussianBlur { radius } if *radius > 0.0)); + let blurs = rfx.iter().any(|fx| matches!(fx, RasterFx::Feather { radius } | RasterFx::GaussianBlur { radius, .. } if *radius > 0.0)); if blurs || rfx.iter().any(|fx| matches!(fx, RasterFx::Pixel(_) | RasterFx::Rasterize(_))) { self.pixel_content(ctx, f, content, rfx, paint); } else { diff --git a/crates/svg/src/css.rs b/crates/svg/src/css.rs index 1b19da8019..78113dcd8c 100644 --- a/crates/svg/src/css.rs +++ b/crates/svg/src/css.rs @@ -668,7 +668,7 @@ impl Rules<'_> { RasterFx::InnerGlow { opacity, blur, color, center: false, .. } if !text => { shadows.push(format!("inset 0 0 {} {}", self.len(blur), color_css(&color, opacity))) } - RasterFx::GaussianBlur { radius } => filter = Some(format!("blur({})", self.len(radius / 2.0))), + RasterFx::GaussianBlur { radius, .. } => filter = Some(format!("blur({})", self.len(radius / 2.0))), RasterFx::InnerGlow { .. } | RasterFx::Feather { .. } => art.unsupported("inner glows or feathering"), RasterFx::Pixel(_) | RasterFx::Rasterize(_) => art.unsupported("pixel effects"), } diff --git a/crates/svg/src/export/paint.rs b/crates/svg/src/export/paint.rs index 462387d70f..902bfc7e1b 100644 --- a/crates/svg/src/export/paint.rs +++ b/crates/svg/src/export/paint.rs @@ -601,7 +601,10 @@ impl Writer<'_> { "<feGaussianBlur in=\"SourceAlpha\" stdDeviation=\"{}\" result=\"soft\"/><feComposite in=\"SourceGraphic\" in2=\"soft\" operator=\"in\" result=\"f\"/><feComposite in=\"f\" in2=\"SourceAlpha\" operator=\"in\"/>", sd(*radius) ), - RasterFx::GaussianBlur { radius } => format!("<feGaussianBlur in=\"SourceGraphic\" stdDeviation=\"{}\"/>", sd(*radius)), + RasterFx::GaussianBlur { radius, linear } => { + let space = if *linear { " color-interpolation-filters=\"linearRGB\"" } else { "" }; + format!("<feGaussianBlur in=\"SourceGraphic\" stdDeviation=\"{}\"{space}/>", sd(*radius)) + } RasterFx::Pixel(_) | RasterFx::Rasterize(_) => continue, }; // Filters composite normally: a shadow's or glow's other blend mode is recorded for import. diff --git a/crates/svg/src/import/fx.rs b/crates/svg/src/import/fx.rs index 8c809f0cd7..e5da2936d6 100644 --- a/crates/svg/src/import/fx.rs +++ b/crates/svg/src/import/fx.rs @@ -347,7 +347,9 @@ pub(super) fn effects(filters: &[Arc<Filter>], ts: Affine, blends: &HashMap<Stri let paint = |c: Color, o: f32| (c.to_hex(), num(o as f64 * 100.0)); let (id, params) = match eval(f, k)? { V::Graphic => continue, - V::Blurred(sd, _) => ("blur.gaussian", json!({ "radius": blur(sd) })), + // SVG blurs in linear light unless the filter asks for sRGB (`color-interpolation-filters`). + V::Blurred(sd, true) => ("blur.gaussian", json!({ "radius": blur(sd), "linear": true })), + V::Blurred(sd, false) => ("blur.gaussian", json!({ "radius": blur(sd) })), V::Feathered(sd) => ("stylize.feather", json!({ "radius": blur(sd) })), V::Stack(layers) => match layers.as_slice() { [V::Paint { shape, color, opacity, clipped: false }, V::Graphic] if !shape.inverted => { diff --git a/crates/svg/tests/it/import_live.rs b/crates/svg/tests/it/import_live.rs index b4dd58256d..13e32ebf58 100644 --- a/crates/svg/tests/it/import_live.rs +++ b/crates/svg/tests/it/import_live.rs @@ -239,7 +239,7 @@ fn a_figma_blurred_shape_filter_becomes_gaussian_blur() { assert!(w.is_empty(), "{w:?}"); let fx = effects(&d); assert_eq!(fx.len(), 1); - assert_eq!((fx[0].id.as_str(), &fx[0].params), ("blur.gaussian", &json!({"radius": 6.0}))); + assert_eq!((fx[0].id.as_str(), &fx[0].params), ("blur.gaussian", &json!({"radius": 6.0, "linear": true}))); } #[test] @@ -274,7 +274,7 @@ fn a_gaussian_blur_becomes_the_effect_with_its_radius() { assert!(w.is_empty(), "{w:?}"); let fx = effects(&d); assert_eq!(fx.len(), 1); - assert_eq!((fx[0].id.as_str(), &fx[0].params), ("blur.gaussian", &json!({"radius": 6.0}))); + assert_eq!((fx[0].id.as_str(), &fx[0].params), ("blur.gaussian", &json!({"radius": 6.0, "linear": true}))); // In a scaled group, the radius scales too. let (d, _) = open( r##"<defs><filter id="b"><feGaussianBlur stdDeviation="3"/></filter></defs><g transform="scale(2)"><rect width="30" height="20" filter="url(#b)"/></g>"##, @@ -282,6 +282,44 @@ fn a_gaussian_blur_becomes_the_effect_with_its_radius() { assert_eq!(effects(&d)[0].params["radius"], json!(12.0)); } +/// `color-interpolation-filters` (SVG 1.1 §15.7.6, initially linearRGB: +/// https://www.w3.org/TR/SVG11/painting.html#ColorInterpolationFiltersProperty) picks whether the +/// blur mixes colours in linear light; sRGB, on the primitive or the filter, keeps them as they +/// are (#5877). +#[test] +fn a_gaussian_blur_keeps_its_colour_space() { + let blur = |filter: &str, primitive: &str| { + let (d, w) = open(&format!( + r##"<defs><filter id="b"{filter}><feGaussianBlur stdDeviation="10"{primitive}/></filter></defs><rect width="100" height="200" filter="url(#b)"/>"## + )); + assert!(w.is_empty(), "{w:?}"); + effects(&d)[0].params.clone() + }; + let linear = json!({"radius": 20.0, "linear": true}); + let srgb = json!({"radius": 20.0}); + assert_eq!(blur("", r#" color-interpolation-filters="linearRGB""#), linear); + assert_eq!(blur("", ""), linear, "linearRGB is the initial value"); + assert_eq!(blur("", r#" color-interpolation-filters="sRGB""#), srgb); + assert_eq!(blur(r#" color-interpolation-filters="sRGB""#, ""), srgb, "inherited from the filter"); + // Export writes the space back on the blur, so it survives a round trip. + let (d, _) = + open(r##"<defs><filter id="b"><feGaussianBlur stdDeviation="10"/></filter></defs><rect width="100" height="200" filter="url(#b)"/>"##); + let svg = export(&d, &ExportOptions::default()); + assert!(svg.contains(r#"color-interpolation-filters="linearRGB"/>"#), "{svg}"); + assert_eq!(effects(&import(&svg).unwrap())[0].params, linear); + // Drawn, black beside white meets as resvg (which blurs in either space) draws it. + for space in ["linearRGB", "sRGB"] { + let source = format!( + r##"<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"><defs><filter id="f" x="-50%" y="-50%" width="200%" height="200%"><feGaussianBlur stdDeviation="10" color-interpolation-filters="{space}"/></filter></defs><g filter="url(#f)"><rect width="100" height="200"/><rect x="100" width="100" height="200" fill="white"/></g></svg>"## + ); + let (ours, theirs) = (render_artboard(&import(&source).unwrap()), resvg_render(&source, 200, 200)); + for x in [95, 99, 100, 105] { + let at = 4 * (100 * 200 + x) as usize; + assert!(ours.rgba[at].abs_diff(theirs.rgba[at]) <= 6, "{space} at {x}: {} vs {}", ours.rgba[at], theirs.rgba[at]); + } + } +} + /// The one drop shadow of the only object: (dx, dy, blur, colour, opacity %). fn shadow(d: &Document) -> (f64, f64, f64, Color, f32) { let fx = vectorcraft_effects::raster_effects(&effects(d)); diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index a3e1aca39d..6d17acd7e5 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`, `OPEN_EXTS`, `PLACE_EXTS` in `crates/engine/src/cmd/fileio/formats.rs`). Illustrator's list comes from its public @@ -191,6 +191,7 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri | Date | Change | Summary | |---|---|---| +| 2026-11-06 | minor | SVG import: a Gaussian blur keeps the colour space its filter asks for with `color-interpolation-filters` (initially `linearRGB`, SVG 1.1 §15.7.6): a linear-light blur becomes Gaussian Blur with the new `linear` parameter, which blurs the colours in linear light (black beside white meets at about 188/255 instead of 128), and SVG export writes it back on the `feGaussianBlur` (#5877). Blurs that ask for sRGB, and the blurs our own export writes, are as before. CSS export still writes `blur()`. Tests `pixel::tests::linear_light_blur_mixes_light_not_values` (crate `vectorcraft-effects`), `import_live::a_gaussian_blur_keeps_its_colour_space` (crate `vectorcraft-svg`); scores unchanged | | 2026-11-06 | minor | PDF export and PDF-compatible `.ai` saves write each object's URL (Attributes panel) as a link annotation with a URI action (web and mail URLs only) over the bounds of the object that shows, trimmed by its clipping groups (ISO 32000-1, 12.5.6.5 and 12.6.4.7); hidden objects, layers that don't print and prints have none, and PDF/X files leave them out with a warning (#5785). Own-fixture tests in `tests::links`; PDF import doesn't read links back as URLs yet; scores unchanged | | 2026-11-06 | minor | SVG import: a gradient with `color-interpolation="linearRGB"` (on it, inherited, or from a style sheet) mixes its stops in linear light, as SVG 1.1 §11.7.1 asks: the document gradient gets extra stops wherever display-RGB mixing would stray by half a colour level or more, so black to white is about 188/255 mid-way instead of 128 (#5878). A gradient several objects share is mixed so on every one. Opacity still mixes evenly; at most 4096 stops per gradient. Tests `import::linear_rgb`, `gradients::linear_rgb_*` (crate `vectorcraft-svg`); scores unchanged | | 2026-11-05 | minor | `.ai` import (#372): a path with a Calligraphic brush comes in as the path with the brush on its stroke (its weight scales the brush) when its art style's brush settings are the brush's own and its angle is on the page, else as its drawn look; a Calligraphic brush's Tilt, Bearing and Rotation codes come in as those channels instead of Random. Checked against a user's file of 6D Art Pen strokes (used locally, not committed); synthetic tests in `import::ai::tests` | From 74b5966bbdcdc1954ffa09c12d2fcff0e2c274f9 Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Fri, 6 Nov 2026 04:06:07 -0500 Subject: [PATCH 191/196] Stroke Weight Up and Down: Cmd/Ctrl+Alt+. and , step the selected strokes' weight (#5797) --- crates/engine/src/cmd/stroke.rs | 93 +++++++++++++++++++++++++++++ crates/engine/src/tests/strokeux.rs | 46 ++++++++++++++ docs/target-app-parity.md | 7 ++- docs/ui-parity.md | 6 +- 4 files changed, 150 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index 3b1289a862..4937ff200a 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -24,6 +24,24 @@ pub fn specs() -> Vec<CommandSpec> { has_doc, stroke_set ), + cmd!( + "stroke.weightUp", + "Stroke Weight Up", + [], + Some("Cmd+Alt+."), + "{ids?|id?} raise each selected stroke's weight by one step of Units › Stroke (a quarter unit below one unit, then whole units; up to 1000 pt), each from its own weight: the selected objects' active or top stroke, type's stroked characters; objects without a stroke are left alone. With nothing selected (and no ids), the weight of the next object drawn → {objects}", + has_doc, + |s, p| stroke_step(s, p, true) + ), + cmd!( + "stroke.weightDown", + "Stroke Weight Down", + [], + Some("Cmd+Alt+,"), + "{ids?|id?} lower each selected stroke's weight by one step, as stroke.weightUp raises it, down to a quarter unit (a thinner weight is kept) → {objects}", + has_doc, + |s, p| stroke_step(s, p, false) + ), cmd!( "stroke.setAdvanced", "Stroke Options", @@ -261,6 +279,61 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> { Ok(json!({"objects": ids.iter().collect::<std::collections::BTreeSet<_>>().len()})) } +/// `w` (pt) one step up or down in `unit` (Units › Stroke): a quarter unit up to one unit, +/// whole units above it, from 0.25 unit to 1000 pt. A weight between steps goes to the next step +/// in that direction (0.6 pt up is 0.75 pt); a weight below a quarter unit doesn't go down. +pub(crate) fn step_weight(w: f64, unit: Unit, up: bool) -> f64 { + const EPS: f64 = 1e-9; + let k = Some(unit.to_pt(1.0)).filter(|k| k.is_finite() && *k > 0.0).unwrap_or(1.0); + let w = if w.is_finite() { w.max(0.0) } else { 0.0 }; + let v = w / k; + let next = if up { + if v < 1.0 - EPS { ((v * 4.0 + EPS).floor() + 1.0) / 4.0 } else { (v + EPS).floor() + 1.0 } + } else if v <= 1.0 + EPS { + (((v * 4.0 - EPS).ceil() - 1.0) / 4.0).max(0.25) + } else { + (v - EPS).ceil() - 1.0 + }; + let r = (next * k).min(1000.0); + // Never a step the wrong way: past 1000 pt up stays, below a quarter unit down stays. + if up { r.max(w) } else { r.min(w) } +} + +/// `stroke.weightUp` / `stroke.weightDown`: each target stroke stepped from its own weight. +fn stroke_step(s: &mut Session, p: &Value, up: bool) -> Result<Value> { + let c = if up { "stroke.weightUp" } else { "stroke.weightDown" }; + let unit = s.stroke_unit(); + let item = item_target(s, p, c)?.of_kind(s, false); + let ids = item.targets(s, p)?; + if no_targets(&ids, p) { + let w = step_weight(s.paint.stroke_width, unit, up); + s.paint.stroke_width = w; + if let Some(st) = s.new_art_stroke_mut() { + st.width = w; + } + return Ok(json!({"objects": 0})); + } + let label = if up { "Stroke Weight Up" } else { "Stroke Weight Down" }; + edit_items(s, &ids, item, c, label, false, |n, index| { + if index.is_none() + && let NodeKind::Text(t) = &mut n.kind + { + // Character strokes are drawn in text space, scaled by the type's transform. + let k = Scaling::factor(t.xf).filter(|k| k.is_finite() && *k > 1e-12).unwrap_or(1.0); + for r in t.runs.iter_mut().filter(|r| !matches!(r.style.stroke, Paint::None)) { + let change = StrokeChange { weight: Some(step_weight(r.style.stroke_width * k, unit, up)), ..StrokeChange::default() }; + change.apply_char_scaled(&mut r.style, k); + } + return Ok(()); + } + if let Some(st) = n.appearance.stroke_at_mut(index) { + st.width = step_weight(st.width, unit, up); + } + Ok(()) + })?; + Ok(json!({"objects": ids.iter().collect::<std::collections::BTreeSet<_>>().len()})) +} + impl Session { /// Units > Stroke (Preferences): the unit stroke weights and dash lengths show in. pub fn stroke_unit(&self) -> Unit { @@ -514,3 +587,23 @@ fn profile_list(s: &mut Session, _: &Value) -> Result<Value> { let current = s.shown_stroke().map(|st| s.profile_entry(st.profile.as_ref()).map_or("custom", |e| e.id).to_string()); Ok(json!({ "profiles": profiles, "current": current })) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn weight_steps_follow_units_and_stop_at_their_bounds() { + assert_eq!(step_weight(0.6, Unit::Points, true), 0.75); + assert_eq!(step_weight(0.6, Unit::Points, false), 0.5); + assert_eq!(step_weight(2.5, Unit::Points, true), 3.0); + assert_eq!(step_weight(2.5, Unit::Points, false), 2.0); + assert_eq!(step_weight(0.1, Unit::Points, false), 0.1, "below a quarter point a step down keeps it"); + assert_eq!(step_weight(1000.0, Unit::Points, true), 1000.0); + assert_eq!(step_weight(2000.0, Unit::Points, true), 2000.0, "a step up never lowers a weight"); + assert_eq!(step_weight(f64::NAN, Unit::Points, true), 0.25); + let mm = Unit::Millimeters.to_pt(1.0); + assert!((step_weight(mm, Unit::Millimeters, true) - 2.0 * mm).abs() < 1e-9); + assert!((step_weight(mm, Unit::Millimeters, false) - 0.75 * mm).abs() < 1e-9); + } +} diff --git a/crates/engine/src/tests/strokeux.rs b/crates/engine/src/tests/strokeux.rs index 82d3aae69a..1c94cfa01f 100644 --- a/crates/engine/src/tests/strokeux.rs +++ b/crates/engine/src/tests/strokeux.rs @@ -111,3 +111,49 @@ fn inspect_reports_stroke_options() { let text = doc["layers"][0]["children"].as_array().unwrap().iter().find(|c| c["kind"] == "Text" || c.get("text").is_some()).unwrap().clone(); assert_eq!(text["strokeOptions"]["join"], "round", "{text}"); } + +/// Stroke Weight Up and Down (Cmd/Ctrl+Alt+. and ,) step each selected stroke from its own +/// weight, a quarter point at a time below 1 pt and whole points above, in one undo step each. +#[test] +fn stroke_weight_up_and_down_step_each_selected_stroke() { + let mut s = session(); + let (a, b, bare) = (rect(&mut s, 10.0), rect(&mut s, 60.0), rect(&mut s, 110.0)); + select(&mut s, &[a]); + run(&mut s, "stroke.set", json!({"weight": 0.6})); + select(&mut s, &[b]); + run(&mut s, "stroke.set", json!({"weight": 3})); + select(&mut s, &[bare]); + run(&mut s, "paint.setStroke", json!({"none": true})); + let has_stroke = |s: &Session| { + s.doc().unwrap().doc.node(bare).unwrap().appearance.stroke().is_some_and(|st| !matches!(st.paint, vectorcraft_color::Paint::None)) + }; + let bare_before = has_stroke(&s); + let w = |s: &Session, id| s.doc().unwrap().doc.node(id).unwrap().appearance.stroke_width(); + select(&mut s, &[a, b, bare]); + run(&mut s, "stroke.weightUp", json!({})); + assert_eq!((w(&s, a), w(&s, b)), (0.75, 4.0)); + run(&mut s, "stroke.weightUp", json!({})); + assert_eq!((w(&s, a), w(&s, b)), (1.0, 5.0)); + assert_eq!(has_stroke(&s), bare_before, "an object without a stroke takes none"); + for _ in 0..6 { + run(&mut s, "stroke.weightDown", json!({})); + } + // 1 → 0.75 → 0.5 → 0.25, where it stays; 5 → 4 → 3 → 2 → 1 → 0.75 → 0.5. + assert_eq!((w(&s, a), w(&s, b)), (0.25, 0.5)); + run(&mut s, "edit.undo", json!({})); + assert_eq!((w(&s, a), w(&s, b)), (0.25, 0.75), "one undo step per press"); +} + +/// With nothing selected the next object drawn takes the stepped weight. +#[test] +fn stroke_weight_up_with_nothing_selected_sets_up_new_art() { + let mut s = session(); + run(&mut s, "select.none", json!({})); + run(&mut s, "stroke.set", json!({"weight": 2})); + run(&mut s, "stroke.weightUp", json!({})); + assert_eq!(s.paint.stroke_width, 3.0); + let r = rect(&mut s, 10.0); + assert_eq!(s.doc().unwrap().doc.node(r).unwrap().appearance.stroke_width(), 3.0); + assert_eq!(crate::cmd::find_command("stroke.weightUp").unwrap().shortcut, Some("Cmd+Alt+.")); + assert_eq!(crate::cmd::find_command("stroke.weightDown").unwrap().shortcut, Some("Cmd+Alt+,")); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ab402e6856..e7bde0bb4a 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-06 · **Change:** minor (Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -1670,6 +1670,10 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition (it replaces a script some users ran), so no area score moves. Object › Plug-ins › Color Effects › Create Swatch Legend… (`addon.color.swatchLegend`) opens a dialog (columns, chip size, gap, values, selected swatches only, with a preview) and draws a chip per colour swatch (the selected ones, else all) filled with and linked to its swatch, labelled with its name and values (HEX, RGB, CMYK, Lab or Grayscale; by default its own model; spot swatches marked), black on light chips and white on dark ones, in a grid of chosen columns, chip size and spacing, as one selected group in one undo step (#4919). Tests: `cmd::addons::color::legend::tests` (engine), `addons::color::legend::tests::create_swatch_legend_opens_its_dialog_previews_and_runs_on_ok` (ui-egui). +## Stroke Weight Up and Down shortcuts (2026-11-06) + +Cmd/Ctrl+Alt+. (`stroke.weightUp`) and Cmd/Ctrl+Alt+, (`stroke.weightDown`) raise and lower the weight of each selected stroke from its own weight, with the keys a [public feature request reply](https://illustrator.uservoice.com/forums/333657-illustrator-desktop-feature-requests/suggestions/32307397-increment-decrement-stroke-weight-key-commands) names: a quarter unit of Units › Stroke at a time up to one unit, whole units above it, no lower than a quarter unit and no higher than 1000 pt. Type steps its stroked characters; objects without a stroke are left alone; with nothing selected the weight of the next object drawn steps. Each press is one undo step (#5797). Evidence: `tests::strokeux::stroke_weight_up_and_down_step_each_selected_stroke`, `stroke_weight_up_with_nothing_selected_sets_up_new_art`, `cmd::stroke::tests::weight_steps_follow_units_and_stop_at_their_bounds`. Scores unchanged. + ## Keyboard shortcuts for Effect menu items (2026-11-01) Edit › Keyboard Shortcuts lists every item of the Effect menu under its menu path (Effect › Distort & Transform › Transform…) and gives each one a shortcut of its own (stored as `effect:<id>`; they all run `effect.dialog {effect}`, or `effect.apply` for an effect without options, so a shortcut on the command alone couldn't tell them apart). The menu shows the shortcut, and pressing it opens that effect's dialog for the selection (#3296). Test: `shortcuts::tests::an_effect_menu_item_takes_a_shortcut_of_its_own`. @@ -1698,6 +1702,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-06 | minor | Stroke Weight Up and Down (Cmd/Ctrl+Alt+. and ,) step each selected stroke's weight (#5797); evidence added; scores unchanged. | | 2026-11-06 | minor | Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged | | 2026-11-06 | minor | Properties in Edit Artboards: a Transform section (reference point, X, Y, W, H, preset, orientation, Move and Scale Artwork) above the Artboards section (name, Artboard Options, Fill), X and Y of the shared reference point (#5219); evidence updated; scores unchanged. | | 2026-11-06 | minor | Scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields; a click still opens the panel (#4088); evidence updated; scores unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index bfa2318436..629834c3e0 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) ## Feature submission evidence @@ -314,6 +314,9 @@ panel-menu commands such as Break Link to Symbol), so they can be given shortcut Align panel's Align Objects, Distribute Objects and Distribute Spacing rows under Align, with no default shortcut, and a shortcut set there runs what a click on the button runs, with the panel's Align To choice and Distribute Spacing value. The [ and ] keys reach the Blob Brush, the Eraser and the Symbolism tools in the app (#1734, part of #1661). +Cmd/Ctrl+Alt+. (`stroke.weightUp`, Stroke Weight Up) and Cmd/Ctrl+Alt+, (`stroke.weightDown`, Stroke Weight Down), the keys a [public feature request reply](https://illustrator.uservoice.com/forums/333657-illustrator-desktop-feature-requests/suggestions/32307397-increment-decrement-stroke-weight-key-commands) gives them, step the weight of each selected stroke from its own weight: by a quarter unit of Units › Stroke up to one +unit, then by whole units, down to a quarter unit; with nothing selected they step the weight of the next object drawn (#5797). + Cmd/Ctrl+Alt+N (`file.newWithoutDialog`, New Without Dialog in the shortcut editor) makes a document with the settings the New Document dialog opens on (the first Recent entry, or the Print category's Letter while Recent is empty), without opening the dialog. @@ -464,6 +467,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-06 | minor | Keyboard shortcuts: Cmd/Ctrl+Alt+. and Cmd/Ctrl+Alt+, (Stroke Weight Up and Down) step each selected stroke's weight, or the next object drawn's (#5797); scores and estimates unchanged | | 2026-11-06 | minor | Properties: Quick Actions has Repeat Options for one selected radial, grid or mirror repeat, opening Object › Repeat › Options with its values (#5181); scores and estimates unchanged | | 2026-11-06 | minor | Control bar: with type selected, a Paragraph: link (the Paragraph panel in a popover) and the Align left, Align center and Align right buttons follow the Character controls; the bar leaves them out from its right end when short of room, after X/Y/W/H and the Align buttons (#5372); scores and estimates unchanged | | 2026-11-04 | minor | Contour add-on (beyond Illustrator): drag away from a selected shape's edge to grow a live copy of it, or toward the inside to shrink it; the copy carries a live Offset Path effect, so it stays editable until Bake (Expand Appearance), a second drag changes the same Contour instead of nesting one, and a floating bar sets the distance and the Sharp, Round or Square corners. `addon.contour.set` is the command behind it. It is a built-in add-on: Object › Plug-ins › Contour, and its own heading in All Tools, with no default shortcut or toolbar slot. A VectorCraft design built on Offset Path; no other application was inspected. Scores and estimates unchanged. | From f08381df8dfacf1d118d61744b1cfeddb57a2d40 Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Fri, 6 Nov 2026 16:38:57 +0700 Subject: [PATCH 192/196] SVG import: filter and mask regions clip what they declare (#5876, #5875) Squashed from #5913 onto main. --- crates/svg/src/import/importer.rs | 61 +++++++++++++++++++++++++++++- crates/svg/tests/it/import_live.rs | 58 +++++++++++++++++++++++++++- docs/file-format-parity.md | 3 +- 3 files changed, 119 insertions(+), 3 deletions(-) diff --git a/crates/svg/src/import/importer.rs b/crates/svg/src/import/importer.rs index 3b0f2001dc..49bcfaab75 100644 --- a/crates/svg/src/import/importer.rs +++ b/crates/svg/src/import/importer.rs @@ -145,7 +145,10 @@ impl Importer { let url = self.links.get(g.id()).cloned(); let mut n = match self.instance(g, acc) { Some(n) => n, - None => self.group_node(g, acc)?, + None => { + let n = self.group_node(g, acc)?; + self.filter_regions(g, acc * aff(g.transform()), n)? + } }; if let Some(url) = url { link(&mut n, &url); @@ -361,6 +364,58 @@ impl Importer { Some(n) } + /// `n`, made of group `g` (whose user space `ts` maps to the document), clipped to the regions + /// of the filters it imported as effects: SVG 1.1 §15.5 + /// (<https://www.w3.org/TR/SVG11/filters.html#FilterEffectsRegion>) cuts a filter's result at + /// its region. A filter that didn't import (drawn without it) clips nothing. + fn filter_regions(&mut self, g: &usvg::Group, ts: Affine, mut n: Node) -> Option<Node> { + if g.filters().is_empty() || fx::effects(g.filters(), ts, &self.blends).is_none() { + return Some(n); + } + for f in g.filters() { + n = self.region_clipped(n, f.rect(), ts)?; + } + Some(n) + } + + /// `n` in a clip group cut to `region` (a filter's or mask's, in the user space `ts` maps to + /// the document), unless all it paints (its visual bounds, grown by the reach of its effects) + /// lies inside the region. `None` only past the object limit. + fn region_clipped(&mut self, n: Node, region: usvg::NonZeroRect, ts: Affine) -> Option<Node> { + let r = Rect::new(region.left() as f64, region.top() as f64, region.right() as f64, region.bottom() as f64); + let det = ts.determinant(); + let Some(bounds) = n.visual_bounds_with(&self.doc.symbol_boxes()) else { return Some(n) }; + if !det.is_finite() || det.abs() < 1e-12 { + return Some(n); + } + // A clip group paints inside its clipping path; anything else as far as its effects reach + // (as export sizes the filter regions it writes: an Outer Glow grows by a quarter of a + // raster pixel first). + let reach = if matches!(n.kind, NodeKind::Group { clip: true, .. }) { + 0.0 + } else { + let grow = 18.0 / self.doc.raster_ppi(); + vectorcraft_effects::raster_effects(&n.appearance.effects) + .iter() + .map(|f| f.outset(bounds) + if matches!(f, vectorcraft_effects::RasterFx::OuterGlow { .. }) { grow } else { 0.0 }) + .sum() + }; + let painted = bounds.inflate(reach, reach); + let to_user = ts.inverse(); + let eps = 1e-6 * (1.0 + r.width().max(r.height())); + let inside = + [(painted.x0, painted.y0), (painted.x1, painted.y0), (painted.x1, painted.y1), (painted.x0, painted.y1)].into_iter().all(|(x, y)| { + let p = to_user * Point::new(x, y); + p.x >= r.x0 - eps && p.x <= r.x1 + eps && p.y >= r.y0 - eps && p.y <= r.y1 + eps + }); + if inside { + return Some(n); + } + let path = shapes::rectangle(r).transformed(ts); + let clip = self.named("", NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: true, guide: false })?; + self.named("", NodeKind::Group { children: vec![Arc::new(clip), Arc::new(n)], clip: true }) + } + /// `<mask>` → opacity mask. An alpha mask's art comes in white with its opacity kept, so its /// luminance is its alpha (images in it keep their colours, with a warning). A mask our export wrote gets its /// options back ([`mask_flags`]) and its art without what stands for them: the inverting @@ -370,6 +425,7 @@ impl Importer { self.warn(format!("nested mask on {label} ignored")); } let (clip, invert) = self.mask_flags.get(m.id()).copied().unwrap_or((true, false)); + let user = ts; let (mut nodes, mut ts) = (m.root().children(), ts); if invert && let [usvg::Node::Group(g)] = nodes @@ -397,6 +453,9 @@ impl Importer { 1 => Arc::unwrap_or_clone(children.pop()?), _ => self.named("", NodeKind::Group { children, clip: false })?, }; + // SVG 1.1 §14.4 (https://www.w3.org/TR/SVG11/masking.html#MaskElement): the mask's art + // counts only inside its region. + let art = self.region_clipped(art, m.rect(), user)?; let mut mask = vectorcraft_doc::OpacityMask::new(art, clip); mask.invert = invert; Some(Box::new(mask)) diff --git a/crates/svg/tests/it/import_live.rs b/crates/svg/tests/it/import_live.rs index 13e32ebf58..b93314b54d 100644 --- a/crates/svg/tests/it/import_live.rs +++ b/crates/svg/tests/it/import_live.rs @@ -111,7 +111,9 @@ fn resvg_render(svg: &str, w: u32, h: u32) -> Image { /// The effects of the only object. fn effects(d: &Document) -> Vec<Effect> { - let a = art(d); + // Not the clip group a filter's region may put it in (SVG 1.1 §15.5), nor its clipping path. + let a: Vec<&Node> = + art(d).into_iter().filter(|n| !matches!(n.kind, NodeKind::Group { clip: true, .. } | NodeKind::Path { clipping: true, .. })).collect(); assert_eq!(a.len(), 1, "{a:?}"); a[0].appearance.effects.clone() } @@ -320,6 +322,60 @@ fn a_gaussian_blur_keeps_its_colour_space() { } } +/// The colour of pixel (`x`, `y`) of `svg` imported and drawn on white. +fn drawn_at(svg: &str, x: u32, y: u32) -> [u8; 4] { + let img = render_artboard(&import(svg).unwrap()); + let at = 4 * (y * img.width + x) as usize; + [img.rgba[at], img.rgba[at + 1], img.rgba[at + 2], img.rgba[at + 3]] +} + +/// SVG 1.1 §15.5 (https://www.w3.org/TR/SVG11/filters.html#FilterEffectsRegion): a filter's +/// result is cut at its region, so a blurred square shows only inside it (#5876). A region that +/// holds the whole blur adds no clip. +#[test] +fn a_blur_is_cut_at_its_filter_region() { + let doc = |width: u32| { + format!( + r##"<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"><defs><filter id="f" filterUnits="userSpaceOnUse" x="0" y="0" width="{width}" height="200"><feGaussianBlur stdDeviation="5"/></filter></defs><rect width="200" height="200" fill="red" filter="url(#f)"/></svg>"## + ) + }; + let red = |p: [u8; 4]| p[0] > 240 && p[1] < 30 && p[2] < 30; + assert!(red(drawn_at(&doc(50), 25, 100))); + assert_eq!(drawn_at(&doc(50), 100, 100), [255, 255, 255, 255], "outside the region"); + assert!(red(drawn_at(&doc(200), 100, 100))); + // With room for the blur all round, the object is as before: no clip group. + let roomy = r##"<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"><defs><filter id="f" filterUnits="userSpaceOnUse" x="0" y="0" width="200" height="200"><feGaussianBlur stdDeviation="2"/></filter></defs><rect x="50" y="50" width="100" height="100" fill="red" filter="url(#f)"/></svg>"##; + let d = import(roomy).unwrap(); + assert_eq!(art(&d).len(), 1); + // Our own export sizes the region to the blur: it comes back unclipped. + let back = import(&export(&d, &ExportOptions::default())).unwrap(); + assert_eq!(art(&back).len(), 1); +} + +/// SVG 1.1 §14.4 (https://www.w3.org/TR/SVG11/masking.html#MaskElement): a mask's art counts +/// only inside the mask's region, in user space or the object's bounding box (#5875). +#[test] +fn a_mask_counts_only_inside_its_region() { + let doc = |region: &str| { + format!( + r##"<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"><defs><mask id="m" {region}><rect width="200" height="200" fill="white"/></mask></defs><rect width="200" height="200" fill="red" mask="url(#m)"/></svg>"## + ) + }; + let red = [255, 0, 0, 255]; + for region in + [r#"maskUnits="userSpaceOnUse" x="0" y="0" width="50" height="200""#, r#"maskUnits="objectBoundingBox" x="0" y="0" width="0.25" height="1""#] + { + assert_eq!(drawn_at(&doc(region), 25, 100), red, "{region}"); + assert_eq!(drawn_at(&doc(region), 100, 100), [255, 255, 255, 255], "{region}"); + } + let wide = doc(r#"maskUnits="userSpaceOnUse" x="0" y="0" width="200" height="200""#); + assert_eq!(drawn_at(&wide, 100, 100), red); + // The default region (-10% to 120% of the object) holds the art: the mask art is as before. + let d = import(&doc("")).unwrap(); + let mask = art(&d)[0].extras().mask.clone().unwrap(); + assert!(matches!(mask.art.kind, NodeKind::Path { .. }), "{:?}", mask.art.kind); +} + /// The one drop shadow of the only object: (dx, dy, blur, colour, opacity %). fn shadow(d: &Document) -> (f64, f64, f64, Color, f32) { let fx = vectorcraft_effects::raster_effects(&effects(d)); diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 6d17acd7e5..d3e2f03031 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`, `OPEN_EXTS`, `PLACE_EXTS` in `crates/engine/src/cmd/fileio/formats.rs`). Illustrator's list comes from its public @@ -191,6 +191,7 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri | Date | Change | Summary | |---|---|---| +| 2026-11-06 | minor | SVG import: filter and mask regions clip (SVG 1.1 §15.5, §14.4). An object whose imported blur, shadow or glow reaches past its filter's region comes in inside a clip group cut to the region (#5876), and a mask's art is cut to the mask's region, in user space or the object's bounding box (#5875). Objects that fit their regions, and our own exports, are unchanged; primitive subregions are still ignored. Tests `import_live::a_blur_is_cut_at_its_filter_region`, `import_live::a_mask_counts_only_inside_its_region` (crate `vectorcraft-svg`); scores unchanged | | 2026-11-06 | minor | SVG import: a Gaussian blur keeps the colour space its filter asks for with `color-interpolation-filters` (initially `linearRGB`, SVG 1.1 §15.7.6): a linear-light blur becomes Gaussian Blur with the new `linear` parameter, which blurs the colours in linear light (black beside white meets at about 188/255 instead of 128), and SVG export writes it back on the `feGaussianBlur` (#5877). Blurs that ask for sRGB, and the blurs our own export writes, are as before. CSS export still writes `blur()`. Tests `pixel::tests::linear_light_blur_mixes_light_not_values` (crate `vectorcraft-effects`), `import_live::a_gaussian_blur_keeps_its_colour_space` (crate `vectorcraft-svg`); scores unchanged | | 2026-11-06 | minor | PDF export and PDF-compatible `.ai` saves write each object's URL (Attributes panel) as a link annotation with a URI action (web and mail URLs only) over the bounds of the object that shows, trimmed by its clipping groups (ISO 32000-1, 12.5.6.5 and 12.6.4.7); hidden objects, layers that don't print and prints have none, and PDF/X files leave them out with a warning (#5785). Own-fixture tests in `tests::links`; PDF import doesn't read links back as URLs yet; scores unchanged | | 2026-11-06 | minor | SVG import: a gradient with `color-interpolation="linearRGB"` (on it, inherited, or from a style sheet) mixes its stops in linear light, as SVG 1.1 §11.7.1 asks: the document gradient gets extra stops wherever display-RGB mixing would stray by half a colour level or more, so black to white is about 188/255 mid-way instead of 128 (#5878). A gradient several objects share is mixed so on every one. Opacity still mixes evenly; at most 4096 stops per gradient. Tests `import::linear_rgb`, `gradients::linear_rgb_*` (crate `vectorcraft-svg`); scores unchanged | From 0864db94945b3074c659bca012e406c73a713b70 Mon Sep 17 00:00:00 2001 From: Adithya Shankaran <72570811+adikshan11@users.noreply.github.com> Date: Fri, 6 Nov 2026 14:21:54 +0530 Subject: [PATCH 193/196] Keep the other library when two names share a file name MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A library called COM¹ is saved as COM¹-, which can be the file of a library really called COM¹-, and the numbered file one of them then gets can be asked for by a third name. Saving one replaced the other. Each now gets a free file name, and saving it again goes back to that file. --- crates/engine/src/cmd/swatchlib.rs | 23 ++++++++++++++++++++++- crates/engine/src/tests/swatchlib.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index 8e929f14d2..9ecec6c672 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -211,7 +211,28 @@ impl<L: LibraryFile> Libraries<L> { .user_dir() .ok_or_else(|| bad(cmd, "no user library folder here (save with a path, or without one to get the data)"))? .to_string(); - let file = library_file_name(name, ext); + let mut file = library_file_name(name, ext); + // `COM¹` is saved as `COM¹-`, which can be another library's own name, and a library put + // under a numbered name holds a file another name can ask for: such a file is kept. + self.rescan(); + let device = crate::file_access::is_device_name; + let id = format!("user/{file}").to_lowercase(); + let fallback = |other: &str| library_file_name(other, ext).to_lowercase() != file.to_lowercase(); + if self + .extra + .iter() + .any(|e| e.info.id.to_lowercase() == id && e.lib.name() != name && (device(name) || device(e.lib.name()) || fallback(e.lib.name()))) + { + // Saved again, it goes back to the file it was given the first time. + let own = self.extra.iter().find(|e| e.info.category == "user" && e.lib.name() == name && extension(&e.info.id) == extension(&file)); + file = match own.and_then(|e| e.info.id.strip_prefix("user/")) { + Some(own) => own.to_string(), + None => { + let mut taken: HashSet<String> = library_files(&dir, L::EXTS).iter().map(|p| file_name(p).to_lowercase()).collect(); + free_name(&file, &mut taken) + } + }; + } let path = std::path::Path::new(&dir).join(&file).to_string_lossy().to_string(); // The app's own folder, under a name made safe: no root applies. crate::file_access::unconfined(|| create_dir(&dir).and_then(|()| write_file(&path, bytes)))?; diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index 18d2ecd337..23980c5d5a 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -765,6 +765,33 @@ fn a_pattern_library_adds_only_the_picked_pattern_and_it_undoes_and_saves() { assert_eq!(back.swatch("Checkerboard").map(|w| &w.paint), doc(&s).swatch("Checkerboard").map(|w| &w.paint)); } +/// A device name is saved with a `-` after it, which can be another library's own name: neither +/// library replaces the other, and saving either again replaces only itself. +#[test] +fn a_library_named_like_a_device_keeps_the_library_with_its_file_name() { + for (first, second) in [("COM¹", "COM¹-"), ("COM¹-", "COM¹"), ("com¹", "COM¹-")] { + let dir = temp_dir("device-collision"); + let mut s = session(); + s.swatch_libraries.set_user_dir(Some(dir.to_string_lossy().to_string())); + let save = + |s: &mut Session, name: &str| run(s, "swatch.library.save", json!({"user": true, "name": name}))["library"].as_str().unwrap().to_string(); + let a = save(&mut s, first); + let b = save(&mut s, second); + assert_ne!(a, b); + assert_eq!(save(&mut s, first), a, "saving {first} again replaces {first}"); + assert_eq!(save(&mut s, second), b, "saving {second} again replaces {second}"); + assert_eq!(s.swatch_libraries.get(&a).unwrap().1.name, first); + assert_eq!(s.swatch_libraries.get(&b).unwrap().1.name, second); + // The name of the numbered file the second one got is a third library's own name. + let third = b.strip_prefix("user/").unwrap().strip_suffix(".vcswatches").unwrap().to_string(); + let c = save(&mut s, &third); + assert!(c != a && c != b, "{third}: {c}"); + assert_eq!(save(&mut s, &third), c, "saving {third} again replaces {third}"); + assert_eq!(s.swatch_libraries.get(&b).unwrap().1.name, second); + let _ = std::fs::remove_dir_all(&dir); + } +} + /// #3602: a library titled with a Windows device name is saved under a name that is not one. #[test] fn a_library_file_name_is_never_a_windows_device_name() { From a76e157de77eebb1428a9cc68a77e79e9a8637b8 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Fri, 6 Nov 2026 10:51:51 +0100 Subject: [PATCH 194/196] Keep a symbol's options when pasting it into another document Fixes #5902 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- crates/engine/src/cmd/brushsym.rs | 1 + crates/engine/src/cmd/brushsym/symbols.rs | 11 +-- crates/engine/src/cmd/clipboard.rs | 4 +- crates/engine/src/cmd/clipboard/resources.rs | 67 ++++++++++++-- crates/engine/src/tests/clipboard.rs | 91 ++++++++++++++++++++ 5 files changed, 163 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index a6505a057b..3e097f8fca 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -37,6 +37,7 @@ use dynamic::{symbol_instance_reset, symbol_instance_set_appearance}; use symbols::selected_instances; pub(crate) use symbols::{ expand_instances_under, expandable_instances, instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol, + stored_natural_size, }; use symbols::{ symbol_adjust, symbol_break_link, symbol_delete, symbol_duplicate, symbol_list, symbol_new, symbol_options, symbol_place, symbol_replace, diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 6ab7acad0b..406511ff16 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -8,11 +8,12 @@ use super::{ // ---------- symbols ---------- pub(crate) fn natural_size(d: &Document, name: &str) -> (f64, f64) { - d.unknown - .get(SIZES_KEY) - .and_then(|m| m.get(name)) - .and_then(|v| Some((v.get(0)?.as_f64()?, v.get(1)?.as_f64()?))) - .unwrap_or((2.0 * HALF, 2.0 * HALF)) + stored_natural_size(d, name).unwrap_or((2.0 * HALF, 2.0 * HALF)) +} + +/// The natural size `d` records for symbol `name` (`None` when it records none). +pub(crate) fn stored_natural_size(d: &Document, name: &str) -> Option<(f64, f64)> { + d.unknown.get(SIZES_KEY).and_then(|m| m.get(name)).and_then(|v| Some((v.get(0)?.as_f64()?, v.get(1)?.as_f64()?))) } pub(crate) fn set_natural_size(d: &mut Document, name: &str, size: Option<(f64, f64)>) { diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index aa8f3b7df3..1f2707fbef 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -24,7 +24,7 @@ use vectorcraft_geom::{PathData, Rect}; pub use flavours::{AI, BITMAP, EMF, EPS, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture}; pub use flavours::{ImageRead, read_image}; pub(crate) use resources::SwatchChoices; -pub use resources::{ArtResources, art_resources}; +pub use resources::{ArtResources, SymbolOptions, art_resources}; use super::{CommandSpec, Result, Session, always, bad, cmd, f64_or, has_doc, point_param, str_param}; use crate::DocState; @@ -70,6 +70,8 @@ pub struct Clipboard { pub images: BTreeMap<String, ImageBlob>, /// Symbols the objects place (also inside other symbols and patterns). pub symbols: Vec<Symbol>, + /// The Symbol Options of [`Self::symbols`] (which the document keeps by name), by symbol name. + pub symbol_options: BTreeMap<String, SymbolOptions>, /// Patterns the objects paint with (pasting makes their swatches again). pub patterns: Vec<PatternDef>, /// Global and spot swatches the objects' colours link to, the tint swatches of the tints they diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index 6a436ab31d..22159ca2a9 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -20,7 +20,12 @@ use std::sync::Arc; use serde_json::{Map, Value, json}; use vectorcraft_brush::Brush; use vectorcraft_color::{Color, Paint, Swatch}; -use vectorcraft_doc::{Appearance, AppearanceItem, Document, GraphicStyle, Node, NodeKind, PatternDef, Symbol, TextStyleDef}; +use vectorcraft_doc::{ + Appearance, AppearanceItem, Document, GraphicStyle, Node, NodeKind, PatternDef, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration, + TextStyleDef, +}; + +use super::super::brushsym::{set_natural_size, stored_natural_size}; use super::super::patterncmds::add_pattern; use super::super::{Result, bad, unique_name}; @@ -628,6 +633,38 @@ fn shows_definitions(b: &Brush) -> bool { found } +/// A symbol's Symbol Options, which its document keeps by symbol name: copied with the symbol and +/// given to it under the name pasting adds it as. +#[derive(Clone, Debug, PartialEq)] +pub struct SymbolOptions { + /// Natural size `(w, h)` (`None`: the document records none). + pub size: Option<(f64, f64)>, + pub registration: SymbolRegistration, + pub export_type: SymbolExportType, + /// 9-slice guides (`None`: 9-slice scaling off). + pub nine_slice: Option<SymbolNineSlice>, +} + +impl SymbolOptions { + /// The options `d` keeps for symbol `name`. + fn of(d: &Document, name: &str) -> Self { + Self { + size: stored_natural_size(d, name), + registration: d.symbol_registration(name), + export_type: d.symbol_export_type(name), + nine_slice: d.symbol_nine_slice(name), + } + } + + /// Make them the options of `d`'s symbol `name`. + fn give(&self, d: &mut Document, name: &str) { + set_natural_size(d, name, self.size); + d.set_symbol_registration(name, self.registration); + d.set_symbol_export_type(name, self.export_type); + d.set_symbol_nine_slice(name, self.nine_slice); + } +} + /// What pasting did to the document's resources (part of the paste result). #[derive(Debug, Default)] pub(crate) struct Imported { @@ -671,6 +708,12 @@ impl Clipboard { Self { images: src.images.iter().filter(|(k, _)| used.has(Res::Image, k)).map(|(k, b)| (k.clone(), b.clone())).collect(), symbols: src.symbols.iter().filter(|s| used.has(Res::Symbol, &s.name)).cloned().collect(), + symbol_options: src + .symbols + .iter() + .filter(|s| used.has(Res::Symbol, &s.name)) + .map(|s| (s.name.clone(), SymbolOptions::of(src, &s.name))) + .collect(), patterns: src.patterns.iter().filter(|p| used.has(Res::Pattern, &p.name)).cloned().collect(), swatches: src.swatches_iter().filter(|w| used.carries(w)).cloned().collect(), graphic_styles: src.graphic_styles.iter().filter(|g| g.id != 0 && used.styles.contains(&g.id)).cloned().collect(), @@ -725,13 +768,27 @@ impl Clipboard { out.placed(r, &def.name, &p); } } - // Symbols and patterns, compared once relinked. Those added are relinked at the end, when - // every new name and graphic style id is known. + // Symbols and patterns, compared once relinked (symbols with their options too). Those + // added are relinked at the end, when every new name and graphic style id is known. let mut added_symbols = HashSet::new(); for def in self.symbols.iter().filter(|s| used.has(Res::Symbol, &s.name)) { + let options = self.symbol_options.get(&def.name); + let theirs: HashMap<String, SymbolOptions> = match options { + Some(_) => { + d.symbols.iter().filter(|s| copy_of(&def.name, &s.name)).map(|s| (s.name.clone(), SymbolOptions::of(d, &s.name))).collect() + } + None => HashMap::new(), + }; let r = &out.relink; - let p = place(&mut d.symbols, def, same_doc, |a, b| same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art))); - added_symbols.extend(p.new_name(&def.name)); + let p = place(&mut d.symbols, def, same_doc, |a, b| { + options.is_none_or(|o| theirs.get(&a.name) == Some(o)) && same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art)) + }); + if let Some(name) = p.new_name(&def.name) { + if let Some(o) = options { + o.give(d, &name); + } + added_symbols.insert(name); + } out.placed(Res::Symbol, &def.name, &p); } let mut added_patterns = HashSet::new(); diff --git a/crates/engine/src/tests/clipboard.rs b/crates/engine/src/tests/clipboard.rs index e7ddbc7c08..79b336df0e 100644 --- a/crates/engine/src/tests/clipboard.rs +++ b/crates/engine/src/tests/clipboard.rs @@ -850,3 +850,94 @@ fn artwork_drop_uses_the_current_layer_even_when_paste_remembers_hidden_or_locke assert!(doc(&s).paste_remembers_layers, "the preference still applies to ordinary Paste"); } } + +/// Two touching rectangles made into 9-slice symbol `Audit`, its instance scaled 150% × 75% and +/// copied (#5902). +fn copied_nine_slice_instance(s: &mut Session) -> Document { + let red = rect(s, 30.0, 30.0, 80.0, 60.0); + s.execute("paint.setFill", &json!({"ids": [red.0], "color": "#ff0000"})).unwrap(); + let blue = rect(s, 110.0, 90.0, 40.0, 30.0); + s.execute("paint.setFill", &json!({"ids": [blue.0], "color": "#0000ff"})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + s.execute("symbol.new", &json!({"name": "Audit", "nineSlice": true, "registration": 0, "exportType": "graphic"})).unwrap(); + s.execute("object.scale", &json!({"sx": 150, "sy": 75})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + doc(s).clone() +} + +/// The symbol options pasted symbol `to` should have: those of `from` in `src`. +fn assert_same_symbol_options(src: &Document, from: &str, d: &Document, to: &str) { + assert!(src.symbol_nine_slice(from).is_some()); + assert_eq!(d.symbol_nine_slice(to), src.symbol_nine_slice(from)); + assert_eq!(d.symbol_registration(to), src.symbol_registration(from)); + assert_eq!(d.symbol_export_type(to), src.symbol_export_type(from)); + assert_eq!(d.symbol_natural_xf(to), src.symbol_natural_xf(from)); +} + +#[test] +fn a_nine_slice_symbol_pasted_into_another_document_keeps_its_options_and_look() { + let mut s = session(); + let src = copied_nine_slice_instance(&mut s); + let before = render(&s); + new_doc(&mut s); + s.execute("edit.pasteInPlace", &json!({})).unwrap(); + assert_same_symbol_options(&src, "Audit", doc(&s), "Audit"); + assert!(before == render(&s), "the pasted instance draws as in the source"); + // Pasting again uses the symbol the first paste added. + let v = s.execute("edit.pasteInPlace", &json!({})).unwrap(); + assert_eq!(v["added"], 0, "{v}"); +} + +#[test] +fn a_renamed_nine_slice_symbol_keeps_its_options_under_the_new_name() { + let mut s = session(); + let src = copied_nine_slice_instance(&mut s); + new_doc(&mut s); + let other = ellipse(&mut s); + sel(&mut s, &[other]); + s.execute("symbol.new", &json!({"name": "Audit"})).unwrap(); + let own = doc(&s).clone(); + let v = s.execute("edit.pasteInPlace", &json!({})).unwrap(); + assert!(renamed(&v).contains(&("symbol".into(), "Audit".into(), "Audit 2".into())), "{v}"); + assert_same_symbol_options(&src, "Audit", doc(&s), "Audit 2"); + // The document's own symbol keeps its options. + assert_eq!(doc(&s).symbol_nine_slice("Audit"), None); + assert_eq!(doc(&s).symbol_natural_xf("Audit"), own.symbol_natural_xf("Audit")); +} + +#[test] +fn a_same_named_symbol_with_other_options_is_not_reused() { + let mut s = session(); + let src = copied_nine_slice_instance(&mut s); + new_doc(&mut s); + s.execute("edit.pasteInPlace", &json!({})).unwrap(); + // The document's `Audit` has the same art but 9-slice scaling off now. + s.execute("symbol.options", &json!({"name": "Audit", "nineSlice": false})).unwrap(); + let v = s.execute("edit.pasteInPlace", &json!({})).unwrap(); + assert!(renamed(&v).contains(&("symbol".into(), "Audit".into(), "Audit 2".into())), "{v}"); + assert_same_symbol_options(&src, "Audit", doc(&s), "Audit 2"); + assert_eq!(doc(&s).symbol_nine_slice("Audit"), None, "the document's own symbol keeps its options"); +} + +#[test] +fn a_symbol_without_a_recorded_natural_size_is_pasted_without_one() { + let mut s = session(); + let r = rect(&mut s, 30.0, 30.0, 80.0, 60.0); + sel(&mut s, &[r]); + s.execute("symbol.new", &json!({"name": "Plain"})).unwrap(); + s.edit("Forget size", |d, _| { + if let Some(m) = d.unknown.get_mut(vectorcraft_doc::SYMBOL_SIZES).and_then(Value::as_object_mut) { + m.remove("Plain"); + } + Ok(()) + }) + .unwrap(); + assert_eq!(doc(&s).unknown.get(vectorcraft_doc::SYMBOL_SIZES).and_then(|m| m.get("Plain")), None); + s.execute("edit.copy", &json!({})).unwrap(); + let before = render(&s); + new_doc(&mut s); + s.execute("edit.pasteInPlace", &json!({})).unwrap(); + assert!(doc(&s).symbols.iter().any(|x| x.name == "Plain")); + assert_eq!(doc(&s).unknown.get(vectorcraft_doc::SYMBOL_SIZES).and_then(|m| m.get("Plain")), None, "no size is made up for it"); + assert!(before == render(&s), "the pasted instance draws as in the source"); +} From f7135db6e9f797052eee428f17bf4a5eb445e42c Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Fri, 6 Nov 2026 04:54:06 -0500 Subject: [PATCH 195/196] Drop Shadow and Outer Glow: spinner arrows step Opacity, the offsets, Blur and Darkness (#5367, #5368) --- crates/ui-egui/src/dialogs/effect.rs | 80 ++++++++++++++++++++++++++- crates/ui-egui/src/dialogs/form.rs | 27 ++++++++- crates/ui-egui/src/widgets.rs | 3 +- crates/ui-egui/src/widgets/numeric.rs | 47 ++++++++++++++++ docs/target-app-parity.md | 4 +- docs/ui-parity.md | 4 +- 6 files changed, 159 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index d305be1ffc..fa4c8dcee6 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -722,7 +722,7 @@ fn drop_shadow_fields(ui: &mut egui::Ui, d: &mut Dialog, unit: vectorcraft_doc:: d.fields.insert("shade".into(), json!("darkness")); } ui.add_enabled_ui(darkness, |ui| { - if let Some(v) = widgets::range_field(ui, "fx-darkness", d.f64("darkness", 100.0), 0.0..=100.0, "%", 0, 70.0) { + if let Some(v) = widgets::spin_range(ui, "fx-darkness", Some(d.f64("darkness", 100.0)), 0.0..=100.0, "%", 0, 86.0, 1.0) { d.fields.insert("darkness".into(), json!(v)); } }); @@ -1041,4 +1041,82 @@ mod tests { let fx = &st.doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects[0]; assert_eq!(fx.params.get("color"), Some(&json!("#00ff00")), "Outer Glow takes the picked colour"); } + + /// Effect > Stylize > Drop Shadow and Outer Glow: Opacity, the offsets, Blur and Darkness have + /// spinner arrows (#5367, #5368). A click on the top half steps up, on the bottom half down; + /// Opacity stops at 100 % and Blur at 0, and OK applies the stepped values. + #[test] + fn drop_shadow_and_outer_glow_fields_have_spinner_arrows() { + for (effect, count) in [("stylize.dropShadow", 5), ("stylize.outerGlow", 2)] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("effect.dialog", json!({"effect": effect})).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + let time = std::cell::Cell::new(0.0); + // One frame → the spinners' bounds, top to bottom. + let frame = |app: &mut VectorcraftApp, events: Vec<egui::Event>| { + time.set(time.get() + 0.05); + let mut out = + ctx.run_ui(egui::RawInput { time: Some(time.get()), events, ..Default::default() }, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + let mut spinners: Vec<egui::Rect> = out + .platform_output + .accesskit_update + .map(|u| u.nodes) + .unwrap_or_default() + .iter() + .filter(|(_, n)| n.label() == Some("Step up or down")) + .filter_map(|(_, n)| n.bounds()) + .map(|b| egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32))) + .collect(); + spinners.sort_by(|a, b| a.top().total_cmp(&b.top())); + spinners + }; + for _ in 0..6 { + frame(&mut app, vec![]); + } + let spinners = frame(&mut app, vec![]); + assert_eq!(spinners.len(), count, "{effect}: a spinner beside each number field: {spinners:?}"); + let click = |app: &mut VectorcraftApp, r: egui::Rect, up: bool| { + let pos = r.center() + egui::vec2(0.0, if up { -r.height() / 4.0 } else { r.height() / 4.0 }); + let button = + |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(app, vec![egui::Event::PointerMoved(pos), button(true)]); + frame(app, vec![button(false)]); + frame(app, vec![]); + }; + let (opacity, blur) = (spinners[0], spinners[count - 1 - usize::from(count == 5)]); + click(&mut app, opacity, true); + let field = |app: &VectorcraftApp, k: &str| app.ui.dialog.as_ref().unwrap().fields.get(k).and_then(Value::as_f64); + assert_eq!(field(&app, "opacity"), Some(76.0), "{effect}: the up arrow steps Opacity up"); + click(&mut app, blur, false); + assert_eq!(field(&app, "blur"), Some(4.0), "{effect}: the down arrow steps Blur down"); + app.ui.dialog.as_mut().unwrap().fields.insert("opacity".into(), json!(100.0)); + app.ui.dialog.as_mut().unwrap().fields.insert("blur".into(), json!(0.0)); + frame(&mut app, vec![]); + click(&mut app, opacity, true); + click(&mut app, blur, false); + assert_eq!((field(&app, "opacity"), field(&app, "blur")), (Some(100.0), Some(0.0)), "{effect}: the arrows stop at the ends"); + click(&mut app, opacity, false); + if count == 5 { + click(&mut app, spinners[1], true); + assert_eq!(field(&app, "x"), Some(8.0), "the X offset steps up"); + let darkness = spinners[4]; + app.ui.dialog.as_mut().unwrap().fields.insert("shade".into(), json!("darkness")); + frame(&mut app, vec![]); + click(&mut app, darkness, false); + assert_eq!(field(&app, "darkness"), Some(99.0), "Darkness steps down"); + } + super::super::confirm(&mut app).unwrap(); + let st = app.session.doc().unwrap(); + let fx = &st.doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects[0]; + let param = |k: &str| fx.params.get(k).and_then(Value::as_f64); + assert_eq!((param("opacity"), param("blur")), (Some(99.0), Some(0.0)), "{effect}: OK applies them"); + } + } } diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index 7238e191ed..5e5b4ea9c5 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -410,10 +410,16 @@ pub(crate) fn params(d: &Dialog) -> Value { /// The (label, value) choices of a parameter that picks one of some values. pub(super) type Choices = &'static [(&'static str, &'static str)]; +/// Effects whose dialogs give their number fields spinner arrows (#5367, #5368): Drop Shadow's +/// and the glows' Opacity, offsets and Blur, which are stepped more than typed. +pub(super) fn has_spinners(effect: &str) -> bool { + matches!(effect, "stylize.dropShadow" | "stylize.outerGlow" | "stylize.innerGlow") +} + /// Generic editor for command/effect parameters: numbers, booleans, strings and colours; the /// parameters `is_length` names are distances shown and typed in `unit`, those `choices` gives /// choices for are dropdowns. Fields come in `rank` order (by name among equals). Returns true when -/// a value changed. +/// a value changed. The fields of [`has_spinners`]' effects carry spinner arrows. pub(super) fn param_fields( ui: &mut egui::Ui, d: &mut Dialog, @@ -425,6 +431,7 @@ pub(super) fn param_fields( let t = Tokens::get(ui.ctx()); let mut changed = false; let mut pick: Option<(String, Color)> = None; + let spinners = has_spinners(&d.str("__effect")); egui::Grid::new("fxgrid").num_columns(2).spacing([12.0, 8.0]).show(ui, |ui| { let mut keys: Vec<(String, Value)> = d.fields.iter().filter(|(k, _)| !k.starts_with("__") && k.as_str() != "preview").map(|(k, v)| (k.clone(), v.clone())).collect(); @@ -446,7 +453,16 @@ pub(super) fn param_fields( if is_length(&k) { // An effect's documented range keeps the field to the distance it applies. let range = vectorcraft_effects::length_range(&d.str("__effect"), &k); - changed |= length_within(ui, d, &k, unit, 140.0, range); + if spinners { + let bounds = range.unwrap_or(if k == "blur" { 0.0..=f64::INFINITY } else { crate::widgets::ANY }); + let value = d.fields.contains_key(&k).then(|| d.f64(&k, 0.0)); + if let Some(x) = crate::widgets::spin_length_within(ui, ("dlg-len", k.as_str()), value, unit, 140.0, bounds) { + d.fields.insert(k.clone(), json!(x)); + changed = true; + } + } else { + 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) @@ -472,6 +488,13 @@ pub(super) fn param_fields( return; } match v { + Value::Number(n) if spinners => { + let range = if k == "opacity" { 0.0..=100.0 } else { crate::widgets::ANY }; + if let Some(x) = crate::widgets::spin_range(ui, ("fx-num", k.as_str()), n.as_f64(), range, "", 3, 140.0, 1.0) { + d.fields.insert(k.clone(), typed_number(x)); + changed = true; + } + } Value::Number(n) => { if let Some(x) = crate::widgets::plain_field(ui, ("fx-num", &k), n.as_f64().unwrap_or(0.0), "", 3, 140.0) { d.fields.insert(k.clone(), typed_number(x)); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 5c8a701dd0..efde0d0b15 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -54,7 +54,8 @@ pub(crate) use numeric::{ANY, round_to, set_bare_numbers_are_points, typed_unit} pub use numeric::{ SpinPick, mixed_field, mixed_field_named, num_field, num_field_live, num_field_named, num_field_within, num_field_within_empty, opt_field, opt_field_named, plain_field_live, range_field, range_field_live, range_field_named, range_field_stepped, size_field, size_field_named, slider, - spin_field, spin_field_auto, spin_field_auto_named, spin_field_named, spin_field_stops_named, spin_kerning, spin_plain, spin_plain_named, + spin_field, spin_field_auto, spin_field_auto_named, spin_field_named, spin_field_stops_named, spin_kerning, spin_length_within, spin_plain, + spin_plain_named, spin_range, }; #[cfg(test)] use numeric::{decimal_point, field_number, share_of, spinner_step, step_through, step_to_multiple, within_a_millionth}; diff --git a/crates/ui-egui/src/widgets/numeric.rs b/crates/ui-egui/src/widgets/numeric.rs index ed1f257eeb..d388387823 100644 --- a/crates/ui-egui/src/widgets/numeric.rs +++ b/crates/ui-egui/src/widgets/numeric.rs @@ -623,6 +623,53 @@ pub fn spin_field_stops_named( .and_then(SpinPick::value) } +/// A distance field with spinner arrows kept within `bounds` (points), as the Drop Shadow and +/// Outer Glow dialogs show their offsets and blur: the spinner steps one `unit` at a time +/// (Shift ×10, Ctrl/Cmd ÷10), and it, ↑/↓, the wheel, a scrub and a typed value stop at both +/// ends. Returns the committed or stepped value in points. +pub fn spin_length_within( + ui: &mut Ui, + id: impl std::hash::Hash + Copy, + value: Option<f64>, + unit: Unit, + width: f32, + bounds: RangeInclusive<f64>, +) -> Option<f64> { + let label = take_previous_label(ui); + let step = Some(unit.to_pt(1.0)).filter(|s| s.is_finite() && *s > 0.0).unwrap_or(1.0); + let field = bounds.clone(); + spin_generic(ui, label, value, None, None, None, width, step, *bounds.start(), &[], &[], &|v| unit.format(v), &mut |ui, fw, label| { + unit_field(ui, id, label, None, value, unit, fw, false, field.clone(), &[], false, "") + }) + .and_then(SpinPick::value) + .map(|v| within(v, &bounds)) +} + +/// [`range_field`] with spinner arrows (Opacity and Darkness in the Drop Shadow and Outer Glow +/// dialogs): the spinner steps by `step` (Shift ×10, Ctrl/Cmd ÷10) and, like ↑/↓, the wheel, a +/// scrub and a typed value, stops at the ends of `range`. +#[allow(clippy::too_many_arguments)] +pub fn spin_range( + ui: &mut Ui, + id: impl std::hash::Hash + Copy, + value: Option<f64>, + range: RangeInclusive<f64>, + suffix: &str, + decimals: usize, + width: f32, + step: f64, +) -> Option<f64> { + let label = take_previous_label(ui); + let places = decimals.min(6) as i32; + let value = value.map(|v| within(v, &range)); + let fmt = |v: f64| format!("{v}{suffix}"); + spin_generic(ui, label, value, None, None, None, width, step, *range.start(), &[], &[], &fmt, &mut |ui, fw, label| { + bounded_field(ui, id, label, None, value, suffix, decimals, fw, &range, None, false, false) + }) + .and_then(SpinPick::value) + .map(|v| within(round_to(v, places), &range)) +} + /// What a [`spin_field_auto`] returns: a value (points), or its Auto entry. #[derive(Clone, Copy, Debug, PartialEq)] pub enum SpinPick { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e7bde0bb4a..c7f4084230 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-06 · **Change:** minor (Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -1087,6 +1087,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur View › Proof Setup › Color blindness – Tritanopia-type turns Proof Colors on and proofs the canvas with the tritanopia simulation of Brettel, Viénot and Mollon (1997). The Separations Preview panel's Proof Setup list offers the same target (`view.proofSetup {target: "tritanopia"}`). Grays keep their value. The Separations Preview panel's Gamut Check button reports one color outside the CMYK gamut in the singular and more in the plural, in English and in each language's plural forms (`gamut_check_status_takes_the_plural_form` in `crates/ui-egui/src/i18n/tests.rs`). - **Document Color Mode outside the layers:** File › Document Color Mode (in one undo step) and `document.open {colorMode}` also convert the colors of graph designs, graphic styles, opacity-mask art, the tile that pattern editing's Cancel puts back and the art of brushes (with a Hue Shift brush's key color); a tint of a global swatch there becomes the converted swatch's color at its tint, as in the art. + - **Spinner arrows in the shadow and glow dialogs (#5367, #5368):** Drop Shadow's Opacity, X Offset, Y Offset, Blur and Darkness and the Outer and Inner Glow's Opacity and Blur have up and down arrows beside the field, as the other number fields with arrows do: a click steps by one (a unit for distances; Shift ×10, Ctrl/Cmd ÷10), holding repeats, Opacity and Darkness stop at 0 and 100 % and Blur at 0 (`dialogs::effect` test `drop_shadow_and_outer_glow_fields_have_spinner_arrows`). - **Colour swatches in effect dialogs (#5365):** a colour parameter of an effect dialog (Outer Glow's Color, Inner Glow's, Drop Shadow's) shows a swatch beside its hex field that follows the value typed in it; a double-click on the swatch opens the Color Picker over the dialog on that colour, whose OK fills the field and whose Cancel comes back unchanged, and the dialog previews the colour when it returns (`dialogs::effect` test `outer_glow_colour_swatch_opens_the_color_picker`). - **Document Color Mode for effects and graphs:** File › Document Color Mode and `document.open {colorMode}` convert the colors of effects (Drop Shadow, Inner Glow, Outer Glow and the other effects with a color, on objects, their fills and strokes and in graphic styles) and the series paints and label styles that a graph keeps, so a graph drawn again from new data keeps the converted colors; File › Document Color Mode also converts the fill and stroke that new art takes. Undo restores the original new-art fill and stroke and Redo applies the conversion again. - **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. @@ -1702,6 +1703,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-06 | minor | Drop Shadow, Outer Glow and Inner Glow: their number fields have spinner arrows (#5367, #5368); evidence added; scores unchanged. | | 2026-11-06 | minor | Stroke Weight Up and Down (Cmd/Ctrl+Alt+. and ,) step each selected stroke's weight (#5797); evidence added; scores unchanged. | | 2026-11-06 | minor | Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged | | 2026-11-06 | minor | Properties in Edit Artboards: a Transform section (reference point, X, Y, W, H, preset, orientation, Move and Scale Artwork) above the Artboards section (name, Artboard Options, Fill), X and Y of the shared reference point (#5219); evidence updated; scores unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 629834c3e0..5e65fc58f2 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) ## Feature submission evidence @@ -38,6 +38,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-06 | minor | Drop Shadow, Outer Glow and Inner Glow: spinner arrows beside Opacity, the offsets, Blur and Darkness (#5367, #5368); scores and estimates unchanged | | 2026-11-06 | minor | Rename (`ui.rename`, no default key) opens the Layers panel's name field on the selected layer, group or object's row, as double-clicking its name does; a key can be assigned in Keyboard Shortcuts (#5324, a VectorCraft addition); scores and estimates unchanged | | 2026-11-06 | minor | Properties panel in Edit Artboards (Shift+O): a Transform section with the shared reference point, X, Y, W and H, the preset and orientation, and Move and Scale Artwork with Artboard, above the Artboards section with the name, Artboard Options and Fill (#5219); scores and estimates unchanged | | 2026-11-06 | minor | Scrubby labels: the Control bar's Stroke: and Opacity: and the Properties panel's Stroke, links to their panels, scrub the field after them as other labels do; a click still opens the panel (#4088); scores and estimates unchanged | @@ -143,6 +144,7 @@ tools, never checked side by side) isn't captured row by row. | Add/Delete/Anchor Point tools; Anchor Point tool drags segments to reshape | done | #2267: a click on a handle end retracts that handle and leaves the anchor a corner with the other one; Shift held at the press on an anchor moves it, handles and all (Shift kept down: at 45° steps) instead of pulling out handles | | Pencil: Fidelity, Keep selected, Alt to Smooth, edit selected paths, close by proximity | done | Fidelity goes down to 0.01 pt in the dialog, the tool and `path.freehand` (the Smooth tool keeps 0.05); its slider runs across the Tool Options row on a logarithmic rail from 0.01 to 20 pt, the field shows hundredths, and the slider's and the field's arrow keys step hundredths up to 0.1 pt, tenths up to 1 pt and whole points above (Shift ×10) (#3328); Alt key toggles to Smooth Tool (#2001); Shift held at the press draws a straight line at 45° steps from the Constrain Angle, and Alt held at the press (with Alt key toggles to Smooth Tool off) a straight line at any angle (#3799), with a straight-line cursor while Shift or Alt is held before the press, and a path-continuation cursor over an end of a selected open path, where the line continues the path; Edit Selected Paths continues a selected path from an end and, from a stroke that starts and ends on a selected path, redraws the section between (the shorter way round a closed path, #2850); with Keep selected (Pencil and Paintbrush, on by default) on, a stroke selects the path it draws or continues and replaces the earlier selection, and off a new stroke leaves nothing selected, the earlier selection included, while a continued or redrawn path is deselected and the rest of the selection stays; a filled Pencil path keeps a stroke of None (#1804, part of #1679); while a freehand stroke is drawn back to within Close Paths When Ends Are Within of its start, the Pencil and the Paintbrush show the closing cursor, and a release there closes the path | | Pencil: Fidelity, Keep selected, Alt to Smooth, edit selected paths, close by proximity | done | Alt key toggles to Smooth Tool (#2001); Shift held at the press draws a straight line at 45° steps from the Constrain Angle, and Alt held at the press (with Alt key toggles to Smooth Tool off) a straight line at any angle (#3799), with a straight-line cursor while Shift or Alt is held before the press, and a path-continuation cursor over an end of a selected open path, where the line continues the path; Edit Selected Paths continues a selected path from an end and, from a stroke that starts and ends on a selected path, redraws the section between (the shorter way round a closed path, #2850); with Keep selected (Pencil and Paintbrush, on by default) on, a stroke selects the path it draws or continues and replaces the earlier selection, and off a new stroke leaves nothing selected, the earlier selection included, while a continued or redrawn path is deselected and the rest of the selection stays; a filled Pencil path keeps a stroke of None (#1804, part of #1679); while a freehand stroke is drawn back to within Close Paths When Ends Are Within of its start, the Pencil and the Paintbrush show the closing cursor, and a release there closes the path; a Pencil stroke from an end of one selected open path to an end of another connects the two into one path | +| Drop Shadow, Outer Glow and Inner Glow: Opacity, the offsets, Blur and Darkness have spinner arrows that step by one (a unit for distances), repeat when held and stop at the fields' ends (#5367, #5368) | done | dialogs::effect test drop_shadow_and_outer_glow_fields_have_spinner_arrows; other effect dialogs' number fields still have none | | Effect dialogs' colour fields: a swatch beside the hex follows typed values, and a double-click opens the Color Picker over the dialog, whose OK fills it and Cancel comes back unchanged (#5365) | done | dialogs::effect test outer_glow_colour_swatch_opens_the_color_picker; the picker previews nothing itself, the effect dialog previews the returned colour | | Join tool scrubbing, Average, Join | done | Join merges the direct-selected anchors lying on one another along a path, as after Average, into one (#1533); the Join tool trims two crossing open paths whose overhanging ends it scrubs over and joins them at the crossing, instead of drawing a segment between their ends (#5844) | | Average and Join in one step, with a corner or smooth choice for the joined anchor | done | Object › Path › Average & Join… (`path.averageJoin`, Cmd+Alt+Shift+J, "Create corner or smooth join" in [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)): two open path ends meet at their midpoint and join, a corner or smooth point as the dialog's Points choice asks (Corner first, then the last choice), in one undo step | From aabefa3a202048cc627457bf2af4bc5a57d7a77c Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 6 Nov 2026 11:50:02 +0100 Subject: [PATCH 196/196] Copy the shared house rules into AGENTS.md. The blocks come from craft-contrib at dde09ea31e2e457f5b4653a6e76f7cdf55944bdf. CLAUDE.md imports AGENTS.md. The house-rules workflow checks the copy. --- .github/workflows/house-rules.yml | 28 +++++++++++ AGENTS.md | 61 ++++++++++++++++++++++-- CLAUDE.md | 77 +------------------------------ 3 files changed, 85 insertions(+), 81 deletions(-) create mode 100644 .github/workflows/house-rules.yml diff --git a/.github/workflows/house-rules.yml b/.github/workflows/house-rules.yml new file mode 100644 index 0000000000..de64ad3ee4 --- /dev/null +++ b/.github/workflows/house-rules.yml @@ -0,0 +1,28 @@ +name: House rules + +on: + push: + branches: [main] + paths: + - AGENTS.md + - CLAUDE.md + - .github/workflows/house-rules.yml + pull_request: + paths: + - AGENTS.md + - CLAUDE.md + - .github/workflows/house-rules.yml + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: house-rules-${{ github.ref }} + cancel-in-progress: true + +jobs: + house-rules: + uses: storytold/craft-common-actions/.github/workflows/house-rules.yml@main + with: + rust: true diff --git a/AGENTS.md b/AGENTS.md index 0d33612d5c..58ab2d6d27 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,3 +1,56 @@ +<!-- craft-house-rules:start core source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=540e6cea75d12d0710c3dca89658328e81e508ecef102446ca5bb95b7c0b92bb --> +## House rules + +These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy. + +1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments. +2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish. +3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location. +4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix. +5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true. +6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why. +7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready. +8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception. +9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop. +10. **Keep secrets and personal details out** of the repository, logs and requests. +11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there. +12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it. +13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it. +14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit. +15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that. +<!-- craft-house-rules:end --> +<!-- craft-house-rules:start rust source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=387e0ccb4b49e567f60951d7d6fff7305054c89f43ad812b9993dc7c38528013 --> +## Rust Craft repositories + +These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib). + +1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix. +2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it. +3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository. +4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build. +5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md). +6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`. + +## Licence allowlist + +Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules. + +- `ISC` +- `MIT` +- `BSD-2-Clause` +- `BSD-3-Clause` +- `Apache-2.0` +- `OFL-1.1` +- `Ubuntu-font-1.0` +- `Bitstream-Vera` +- `CC0-1.0` +- `CC-BY-4.0` +- `CC-BY-SA-4.0` +- `LicenseRef-Public-Domain` + +`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so. +<!-- craft-house-rules:end --> + # VectorCraft — instructions for agents VectorCraft is a clean-room, open-source, Rust-native vector illustration app targeting Adobe Illustrator parity (and beyond). It runs natively on macOS, Windows and Linux, and on the web via WASM. Siblings: `../photocraft` (Photoshop-class) and `../pdfcraft` (Acrobat-class); same conventions. @@ -6,10 +59,7 @@ Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format ## Start every session here 1. Read [`ROADMAP.md`](ROADMAP.md) (stage, numbers by dimension, what's next) and the ranked work list in [`docs/gaps.md`](docs/gaps.md). Unless the user gives you a task, pick work from that list. -2. Read `plan/STATUS.md` (local session notes, may lag the ROADMAP), then the task in `plan/execution-plan.md` §3 and the relevant `plan/architecture.md` section. Behaviour reference: public documentation only (see Clean-room below); `plan/illustrator/*.md` holds notes from it. -3. Follow the autonomous operation protocol (`plan/execution-plan.md` §7): orient → plan → implement + test → verify → record → commit. Don't stop to ask unless §7 lists the decision as the user's. - -`plan/` is gitignored (local only). +2. `plan/` is an optional gitignored notebook. Behaviour notes may be in `plan/illustrator/*.md`. Do not ask for it and do not stop when it is absent. Orient, implement, test, verify, then record in the public docs. ## Non-negotiables - **Clean-room: never use Adobe software (absolute rule, from the project owner).** Adobe's Terms of Use forbid reverse engineering, including observing a program's inputs and outputs to recreate it. So: @@ -45,7 +95,6 @@ Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format - **Layering** is enforced by `cargo xtask layers`. Nothing below L6 depends on egui/eframe/winit/rfd. - **The UI is thin**: panels read engine state and act through `app.run(id, params)`. Colours come from `theme::Tokens`. - **Rust only** (no handwritten JS/TS). **Never break wasm** (`cargo xtask wasm`). -- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic). - **Shared test corpora.** Real-file test oracles (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`. - **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings including the no-panic lints, tests, layers, wasm). One task id per commit (`M2.1: pen tool`). @@ -88,3 +137,5 @@ When a task lands, update in the same PR: the area row in `docs/target-app-parit - Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. - Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time. - Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it. + +New workspace crates include `[lints] workspace = true` in `Cargo.toml`. Production crate roots declare the crate-level lint attributes before modules; crate-level `//!` documentation may precede them. diff --git a/CLAUDE.md b/CLAUDE.md index 17783d9a1f..43c994c2d3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,76 +1 @@ -# VectorCraft — instructions for agents - -VectorCraft is a clean-room, open-source, Rust-native vector illustration app targeting Adobe Illustrator parity (and beyond). It runs natively on macOS, Windows and Linux, and on the web via WASM. Siblings: `../photocraft` (Photoshop-class) and `../pdfcraft` (Acrobat-class); same conventions. - -Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format": "drawcraft"` headers still open (`vectorcraft_format::LEGACY_EXTENSION`), and preferences migrate from the old config folder. Keep those paths working; use the new name everywhere else. - -## Start every session here -1. Read [`ROADMAP.md`](ROADMAP.md) (stage, numbers by dimension, what's next) and the ranked work list in [`docs/gaps.md`](docs/gaps.md). Unless the user gives you a task, pick work from that list. -2. Read `plan/STATUS.md` (local session notes, may lag the ROADMAP), then the task in `plan/execution-plan.md` §3 and the relevant `plan/architecture.md` section. Behaviour reference: public documentation only (see Clean-room below); `plan/illustrator/*.md` holds notes from it. -3. Follow the autonomous operation protocol (`plan/execution-plan.md` §7): orient → plan → implement + test → verify → record → commit. Don't stop to ask unless §7 lists the decision as the user's. - -`plan/` is gitignored (local only). - -## Non-negotiables -- **Clean-room: never use Adobe software (absolute rule, from the project owner).** Adobe's Terms of Use forbid reverse engineering, including observing a program's inputs and outputs to recreate it. So: - - Never launch, run, script, automate (COM, AppleScript, ExtendScript, UI automation), screenshot or measure Illustrator or any other Adobe application, and never compare our output against one. Don't make test files with them, not even "synthetic" ones. - - Never read, disassemble or copy anything inside an Adobe install (binaries, plug-ins, presets, procsets, resources, help files, fonts, ICC profiles). - - Never copy Adobe-authored code or text into this repo, tests included: no PostScript procsets or prologs (AGM, CoolType, the Illustrator prologs), no sample files. Write test inputs from scratch from the public specifications (PostScript Language Reference, PDF / ISO 32000, TIFF, EPSF/DCS). - - Behaviour comes only from public documentation (helpx, published specs, public forum posts), cited by URL, and from files users send us that they own (used locally, never committed). Never copy Adobe icons, artwork, presets or wording beyond feature names. - - If a task seems to need any of this, stop and say so instead. `cargo xtask cleanroom` (run by `cargo xtask ci`) fails on Adobe copyright notices and on fixtures made with Adobe applications. - - Never copy GPL/AGPL code (Inkscape, lib2geom…). -- **Assets: no Adobe iconography or images — ever (absolute rule, from the project owner).** - - Never add, copy, trace, redraw-from, embed or ship any icon, image, artwork, cursor, preset, swatch/brush/symbol/pattern/style library, ICC profile or screenshot from Adobe products or from any other source whose licence doesn't allow it. - - Every image, icon, font or other asset must be one of: - - original work created for VectorCraft by a contributor (who licenses it MIT OR Apache-2.0); - - OSI open source; - - public domain / CC0; - - Creative Commons with redistribution allowed. - - **Every asset file must have a row in [`ASSETS.md`](ASSETS.md)** (path, author, source URL, licence, notes). Put licence texts next to the assets (e.g. `assets/fonts/OFL-*.txt`) and summarize them in `NOTICE`. - - `cargo xtask assets` (run by `cargo xtask ci`) fails on any unattributed asset. - - **Fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), never in this repo**. Never commit a font file here; add new fonts to craft-fonts. The app uses it only through the optional `CRAFT_FONTS_DIR` build option (`CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo xtask ci`; use an absolute path), read by `crates/text/build.rs` into `vectorcraft_text::CRAFT_FONTS`; never add it to a `Cargo.toml`. Everything must build, test and run with `CRAFT_FONTS` empty, and tests of its glyphs skip when it is. Details: `docs/development.md` › Fonts. - - Code and original assets are MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`, `NOTICE`). The ArtCraft logos in `docs/brand/` are trademarks, not open source, under `docs/brand/LICENSE-brand.txt`: never modify them or use them outside VectorCraft. - - Prefer art generated in code for defaults (swatches, brushes, symbols, patterns, cursors). If the provenance of an asset is unclear, don't add it. - - Reference screenshots of Illustrator stay local under the gitignored `plan/` and are never committed, published or used as assets. -- **Never crash: no panics in shipped code.** A crash loses the user's unsaved work. Files, pasted data, MCP and control messages, and command params are all untrusted input. - - Fallible work returns `Result` (or `Option`); callers handle it or propagate it with `?`. Failures reach the user as an error message (`EngineError` for commands, the crate's own error type or `String` below the engine), never as an abort. - - Workspace clippy lints ban these outside tests, so `cargo xtask ci` fails on them: `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, `unimplemented!`. Use instead: `?`, `.ok_or(…)?`, `let … else { return … }`, `if let`, `unwrap_or` / `unwrap_or_default` / `unwrap_or_else`, `.first()` / `.last()` / `.split_last()`, and a real error for a match arm you believe is impossible. - - New workspace crates must include `[lints] workspace = true` in `Cargo.toml` to inherit `[workspace.lints]`. Production crate roots must declare `#![forbid(unsafe_code)]` before modules or other crate items; crate-level `//!` documentation may precede it. - - Don't panic implicitly either: use `.get(i)` instead of `v[i]` or `&s[a..b]` when the index comes from data. Don't divide integers by something that can be zero, cap sizes and counts read from input (allocations, images, loops), and check that floats are finite before casting them or looping on them. - - Don't silence errors just to satisfy the lint: use `let _ =` or `.ok()` only where ignoring the failure is the right behaviour, with a comment saying why. - - Tests may unwrap and panic (`#[test]`, `#[cfg(test)]`, `tests/`, `testkit`). Integration-test files start with an `#![allow(…)]` for that. - - `vectorcraft_engine::guard` is the last line of defence. Every entry point (commands, tool events, MCP requests, the UI frame, control requests) catches a panic, rolls the document back and reports an internal error. It exists for bugs and doesn't replace `Result`: wasm aborts on panic, so the web app has no safety net. - - Untrusted input is fuzzed (`engine/tests/import_fuzz.rs`, `engine/tests/command_sweep.rs`, `format/tests/prop_format.rs`, `mcp/tests/protocol_props.rs`). Extend these when you add an importer, a parser or a protocol method. -- **Everything is a command.** User-visible behaviour = a command in `crates/engine/src/cmd/*` (id, label, menu path, shortcut, params doc, `enabled`, `run`) + tests. Tools emit commands (Begin/Preview/Commit). UI-only commands live in `crates/ui-egui/src/menus.rs` (`UI_COMMANDS`). The control channel and MCP reach all of them. -- **Adding a cursor.** The app decides which cursors exist; whoever draws them works from the list. For a new tool state with a cursor of its own: add the `Cursor` variant (`crates/tools/src/lib.rs`, with a doc comment), return it from the tool's `cursor()` with a tool test, cover it in `cursor_icon` (`crates/ui-egui/src/canvas.rs`), draw it in `crates/ui-egui/src/cursors.rs` or give it a stand-in in `Cursor::stand_in()` until it's drawn, and add its `[[cursor]]` entry to `crates/tools/src/cursors.toml` (when it shows, in plain behaviour terms, and its hotspot; never another app's look). A missing entry only warns (`cargo xtask cursors`): the cursor still works. -- **Layering** is enforced by `cargo xtask layers`. Nothing below L6 depends on egui/eframe/winit/rfd. -- **The UI is thin**: panels read engine state and act through `app.run(id, params)`. Colours come from `theme::Tokens`. -- **Rust only** (no handwritten JS/TS). **Never break wasm** (`cargo xtask wasm`). -- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic). -- **Shared test corpora.** Real-file test oracles (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`. -- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings including the no-panic lints, tests, layers, wasm). One task id per commit (`M2.1: pen tool`). - -## Running and looking at the app -- `cargo run --release -p vectorcraft -- --control 7979 [file.svg|file.vectorcraft]` (sibling apps' agents use the same default port: if the log says it failed to bind, pick another port — otherwise your requests reach a different app). -- Drive it: JSON lines on `127.0.0.1:7979`, e.g. `{"id":1,"method":"engine.execute","params":{"command":"shape.rectangle","params":{"x":10,"y":10,"width":100,"height":50}}}` then `{"id":2,"method":"ui.screenshot","params":{"path":"/tmp/shot.png"}}`. Methods: `crates/ui-egui/src/control.rs`. -- **For UI work, look at the result** (take `ui.screenshot`, read the PNG) and compare with the public documentation (`plan/illustrator/02-ui-ux.md` notes). `ui.screenshot` needs a presented frame: if it errors (screen locked), check the art with `ui.render` / `vectorcraft-cli run … --export x.png`, and cover panels with a headless egui frame test (see `panels/transparency.rs` tests). -- **Performance:** `vectorcraft-cli perf` checks the budgets (render/pan/zoom, hit test, save/open, SVG, Pathfinder) on a synthetic 50k-path document; `vectorcraft-cli bench FILE` times one file. Run them before and after renderer, format or geometry changes, on an idle machine (the report warns when the load average makes timings noise). -- MCP: `vectorcraft-cli mcp` (see `docs/mcp.md`). -- Shell gotcha: `mv`/`cp` are aliased interactive here — use `/bin/mv -f` / `/bin/cp -f`. -- Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own; write manifests atomically. Each target dir grows to ~30 GB: delete yours when you finish (a full disk fails links with `errno=28`). - -## Roadmap and progress docs -The progress docs: -- [`ROADMAP.md`](ROADMAP.md): stage, headline numbers, dimensions, features, languages, upcoming, progress log. -- [`docs/target-app-parity.md`](docs/target-app-parity.md): the authoritative parity assessment (area table, methodology, calibration, evidence of what ships). -- [`docs/gaps.md`](docs/gaps.md): every known shortfall, ranked; the work list. [`docs/roadmap.md`](docs/roadmap.md): milestones and current focus. -- Checklists: [`ui-parity.md`](docs/ui-parity.md), [`file-format-parity.md`](docs/file-format-parity.md), [`hardware-parity.md`](docs/hardware-parity.md), [`localization-parity.md`](docs/localization-parity.md), [`effects-parity.md`](docs/effects-parity.md), [`type-parity.md`](docs/type-parity.md); [`architecture.md`](docs/architecture.md). - -When a task lands, update in the same PR: the area row in `docs/target-app-parity.md` (score, missing items, hours) and its evidence list, the gap entry in `docs/gaps.md` if it closed or shrank, the checklist it belongs to, the milestone row in `docs/roadmap.md`, and the ROADMAP's tables and progress log when a headline number moves. Update each touched doc's status line and revision history. -- Grade by behaviour against the public documentation (`plan/illustrator/` notes), not by whether a menu item exists. Scores are self-assessed, so err low; mark each number measured or estimated. -- Keep the README's Status section in step with the ROADMAP headline. - -## CI workflows -- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. -- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time. -- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it. +@AGENTS.md